SemaChecking.cpp 644 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281
  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/None.h"
  70. #include "llvm/ADT/Optional.h"
  71. #include "llvm/ADT/STLExtras.h"
  72. #include "llvm/ADT/SmallBitVector.h"
  73. #include "llvm/ADT/SmallPtrSet.h"
  74. #include "llvm/ADT/SmallString.h"
  75. #include "llvm/ADT/SmallVector.h"
  76. #include "llvm/ADT/StringRef.h"
  77. #include "llvm/ADT/StringSet.h"
  78. #include "llvm/ADT/StringSwitch.h"
  79. #include "llvm/ADT/Triple.h"
  80. #include "llvm/Support/AtomicOrdering.h"
  81. #include "llvm/Support/Casting.h"
  82. #include "llvm/Support/Compiler.h"
  83. #include "llvm/Support/ConvertUTF.h"
  84. #include "llvm/Support/ErrorHandling.h"
  85. #include "llvm/Support/Format.h"
  86. #include "llvm/Support/Locale.h"
  87. #include "llvm/Support/MathExtras.h"
  88. #include "llvm/Support/SaveAndRestore.h"
  89. #include "llvm/Support/raw_ostream.h"
  90. #include <algorithm>
  91. #include <bitset>
  92. #include <cassert>
  93. #include <cctype>
  94. #include <cstddef>
  95. #include <cstdint>
  96. #include <functional>
  97. #include <limits>
  98. #include <string>
  99. #include <tuple>
  100. #include <utility>
  101. using namespace clang;
  102. using namespace sema;
  103. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  104. unsigned ByteNo) const {
  105. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  106. Context.getTargetInfo());
  107. }
  108. /// Checks that a call expression's argument count is the desired number.
  109. /// This is useful when doing custom type-checking. Returns true on error.
  110. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  111. unsigned argCount = call->getNumArgs();
  112. if (argCount == desiredArgCount) return false;
  113. if (argCount < desiredArgCount)
  114. return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
  115. << 0 /*function call*/ << desiredArgCount << argCount
  116. << call->getSourceRange();
  117. // Highlight all the excess arguments.
  118. SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
  119. call->getArg(argCount - 1)->getEndLoc());
  120. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  121. << 0 /*function call*/ << desiredArgCount << argCount
  122. << call->getArg(1)->getSourceRange();
  123. }
  124. /// Check that the first argument to __builtin_annotation is an integer
  125. /// and the second argument is a non-wide string literal.
  126. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  127. if (checkArgCount(S, TheCall, 2))
  128. return true;
  129. // First argument should be an integer.
  130. Expr *ValArg = TheCall->getArg(0);
  131. QualType Ty = ValArg->getType();
  132. if (!Ty->isIntegerType()) {
  133. S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
  134. << ValArg->getSourceRange();
  135. return true;
  136. }
  137. // Second argument should be a constant string.
  138. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  139. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  140. if (!Literal || !Literal->isAscii()) {
  141. S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
  142. << StrArg->getSourceRange();
  143. return true;
  144. }
  145. TheCall->setType(Ty);
  146. return false;
  147. }
  148. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  149. // We need at least one argument.
  150. if (TheCall->getNumArgs() < 1) {
  151. S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  152. << 0 << 1 << TheCall->getNumArgs()
  153. << TheCall->getCallee()->getSourceRange();
  154. return true;
  155. }
  156. // All arguments should be wide string literals.
  157. for (Expr *Arg : TheCall->arguments()) {
  158. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  159. if (!Literal || !Literal->isWide()) {
  160. S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
  161. << Arg->getSourceRange();
  162. return true;
  163. }
  164. }
  165. return false;
  166. }
  167. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  168. /// result type to the corresponding pointer type.
  169. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  170. if (checkArgCount(S, TheCall, 1))
  171. return true;
  172. ExprResult Arg(TheCall->getArg(0));
  173. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
  174. if (ResultType.isNull())
  175. return true;
  176. TheCall->setArg(0, Arg.get());
  177. TheCall->setType(ResultType);
  178. return false;
  179. }
  180. /// Check that the argument to __builtin_function_start is a function.
  181. static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
  182. if (checkArgCount(S, TheCall, 1))
  183. return true;
  184. ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  185. if (Arg.isInvalid())
  186. return true;
  187. TheCall->setArg(0, Arg.get());
  188. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
  189. Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
  190. if (!FD) {
  191. S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
  192. << TheCall->getSourceRange();
  193. return true;
  194. }
  195. return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  196. TheCall->getBeginLoc());
  197. }
  198. /// Check the number of arguments and set the result type to
  199. /// the argument type.
  200. static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
  201. if (checkArgCount(S, TheCall, 1))
  202. return true;
  203. TheCall->setType(TheCall->getArg(0)->getType());
  204. return false;
  205. }
  206. /// Check that the value argument for __builtin_is_aligned(value, alignment) and
  207. /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
  208. /// type (but not a function pointer) and that the alignment is a power-of-two.
  209. static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
  210. if (checkArgCount(S, TheCall, 2))
  211. return true;
  212. clang::Expr *Source = TheCall->getArg(0);
  213. bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
  214. auto IsValidIntegerType = [](QualType Ty) {
  215. return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
  216. };
  217. QualType SrcTy = Source->getType();
  218. // We should also be able to use it with arrays (but not functions!).
  219. if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
  220. SrcTy = S.Context.getDecayedType(SrcTy);
  221. }
  222. if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
  223. SrcTy->isFunctionPointerType()) {
  224. // FIXME: this is not quite the right error message since we don't allow
  225. // floating point types, or member pointers.
  226. S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
  227. << SrcTy;
  228. return true;
  229. }
  230. clang::Expr *AlignOp = TheCall->getArg(1);
  231. if (!IsValidIntegerType(AlignOp->getType())) {
  232. S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
  233. << AlignOp->getType();
  234. return true;
  235. }
  236. Expr::EvalResult AlignResult;
  237. unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
  238. // We can't check validity of alignment if it is value dependent.
  239. if (!AlignOp->isValueDependent() &&
  240. AlignOp->EvaluateAsInt(AlignResult, S.Context,
  241. Expr::SE_AllowSideEffects)) {
  242. llvm::APSInt AlignValue = AlignResult.Val.getInt();
  243. llvm::APSInt MaxValue(
  244. llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
  245. if (AlignValue < 1) {
  246. S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
  247. return true;
  248. }
  249. if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
  250. S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
  251. << toString(MaxValue, 10);
  252. return true;
  253. }
  254. if (!AlignValue.isPowerOf2()) {
  255. S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
  256. return true;
  257. }
  258. if (AlignValue == 1) {
  259. S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
  260. << IsBooleanAlignBuiltin;
  261. }
  262. }
  263. ExprResult SrcArg = S.PerformCopyInitialization(
  264. InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
  265. SourceLocation(), Source);
  266. if (SrcArg.isInvalid())
  267. return true;
  268. TheCall->setArg(0, SrcArg.get());
  269. ExprResult AlignArg =
  270. S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  271. S.Context, AlignOp->getType(), false),
  272. SourceLocation(), AlignOp);
  273. if (AlignArg.isInvalid())
  274. return true;
  275. TheCall->setArg(1, AlignArg.get());
  276. // For align_up/align_down, the return type is the same as the (potentially
  277. // decayed) argument type including qualifiers. For is_aligned(), the result
  278. // is always bool.
  279. TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
  280. return false;
  281. }
  282. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
  283. unsigned BuiltinID) {
  284. if (checkArgCount(S, TheCall, 3))
  285. return true;
  286. // First two arguments should be integers.
  287. for (unsigned I = 0; I < 2; ++I) {
  288. ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
  289. if (Arg.isInvalid()) return true;
  290. TheCall->setArg(I, Arg.get());
  291. QualType Ty = Arg.get()->getType();
  292. if (!Ty->isIntegerType()) {
  293. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  294. << Ty << Arg.get()->getSourceRange();
  295. return true;
  296. }
  297. }
  298. // Third argument should be a pointer to a non-const integer.
  299. // IRGen correctly handles volatile, restrict, and address spaces, and
  300. // the other qualifiers aren't possible.
  301. {
  302. ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
  303. if (Arg.isInvalid()) return true;
  304. TheCall->setArg(2, Arg.get());
  305. QualType Ty = Arg.get()->getType();
  306. const auto *PtrTy = Ty->getAs<PointerType>();
  307. if (!PtrTy ||
  308. !PtrTy->getPointeeType()->isIntegerType() ||
  309. PtrTy->getPointeeType().isConstQualified()) {
  310. S.Diag(Arg.get()->getBeginLoc(),
  311. diag::err_overflow_builtin_must_be_ptr_int)
  312. << Ty << Arg.get()->getSourceRange();
  313. return true;
  314. }
  315. }
  316. // Disallow signed bit-precise integer args larger than 128 bits to mul
  317. // function until we improve backend support.
  318. if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
  319. for (unsigned I = 0; I < 3; ++I) {
  320. const auto Arg = TheCall->getArg(I);
  321. // Third argument will be a pointer.
  322. auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
  323. if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
  324. S.getASTContext().getIntWidth(Ty) > 128)
  325. return S.Diag(Arg->getBeginLoc(),
  326. diag::err_overflow_builtin_bit_int_max_size)
  327. << 128;
  328. }
  329. }
  330. return false;
  331. }
  332. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  333. if (checkArgCount(S, BuiltinCall, 2))
  334. return true;
  335. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  336. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  337. Expr *Call = BuiltinCall->getArg(0);
  338. Expr *Chain = BuiltinCall->getArg(1);
  339. if (Call->getStmtClass() != Stmt::CallExprClass) {
  340. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  341. << Call->getSourceRange();
  342. return true;
  343. }
  344. auto CE = cast<CallExpr>(Call);
  345. if (CE->getCallee()->getType()->isBlockPointerType()) {
  346. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  347. << Call->getSourceRange();
  348. return true;
  349. }
  350. const Decl *TargetDecl = CE->getCalleeDecl();
  351. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  352. if (FD->getBuiltinID()) {
  353. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  354. << Call->getSourceRange();
  355. return true;
  356. }
  357. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  358. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  359. << Call->getSourceRange();
  360. return true;
  361. }
  362. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  363. if (ChainResult.isInvalid())
  364. return true;
  365. if (!ChainResult.get()->getType()->isPointerType()) {
  366. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  367. << Chain->getSourceRange();
  368. return true;
  369. }
  370. QualType ReturnTy = CE->getCallReturnType(S.Context);
  371. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  372. QualType BuiltinTy = S.Context.getFunctionType(
  373. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  374. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  375. Builtin =
  376. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  377. BuiltinCall->setType(CE->getType());
  378. BuiltinCall->setValueKind(CE->getValueKind());
  379. BuiltinCall->setObjectKind(CE->getObjectKind());
  380. BuiltinCall->setCallee(Builtin);
  381. BuiltinCall->setArg(1, ChainResult.get());
  382. return false;
  383. }
  384. namespace {
  385. class ScanfDiagnosticFormatHandler
  386. : public analyze_format_string::FormatStringHandler {
  387. // Accepts the argument index (relative to the first destination index) of the
  388. // argument whose size we want.
  389. using ComputeSizeFunction =
  390. llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
  391. // Accepts the argument index (relative to the first destination index), the
  392. // destination size, and the source size).
  393. using DiagnoseFunction =
  394. llvm::function_ref<void(unsigned, unsigned, unsigned)>;
  395. ComputeSizeFunction ComputeSizeArgument;
  396. DiagnoseFunction Diagnose;
  397. public:
  398. ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
  399. DiagnoseFunction Diagnose)
  400. : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
  401. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  402. const char *StartSpecifier,
  403. unsigned specifierLen) override {
  404. if (!FS.consumesDataArgument())
  405. return true;
  406. unsigned NulByte = 0;
  407. switch ((FS.getConversionSpecifier().getKind())) {
  408. default:
  409. return true;
  410. case analyze_format_string::ConversionSpecifier::sArg:
  411. case analyze_format_string::ConversionSpecifier::ScanListArg:
  412. NulByte = 1;
  413. break;
  414. case analyze_format_string::ConversionSpecifier::cArg:
  415. break;
  416. }
  417. analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
  418. if (FW.getHowSpecified() !=
  419. analyze_format_string::OptionalAmount::HowSpecified::Constant)
  420. return true;
  421. unsigned SourceSize = FW.getConstantAmount() + NulByte;
  422. Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
  423. if (!DestSizeAPS)
  424. return true;
  425. unsigned DestSize = DestSizeAPS->getZExtValue();
  426. if (DestSize < SourceSize)
  427. Diagnose(FS.getArgIndex(), DestSize, SourceSize);
  428. return true;
  429. }
  430. };
  431. class EstimateSizeFormatHandler
  432. : public analyze_format_string::FormatStringHandler {
  433. size_t Size;
  434. public:
  435. EstimateSizeFormatHandler(StringRef Format)
  436. : Size(std::min(Format.find(0), Format.size()) +
  437. 1 /* null byte always written by sprintf */) {}
  438. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  439. const char *, unsigned SpecifierLen,
  440. const TargetInfo &) override {
  441. const size_t FieldWidth = computeFieldWidth(FS);
  442. const size_t Precision = computePrecision(FS);
  443. // The actual format.
  444. switch (FS.getConversionSpecifier().getKind()) {
  445. // Just a char.
  446. case analyze_format_string::ConversionSpecifier::cArg:
  447. case analyze_format_string::ConversionSpecifier::CArg:
  448. Size += std::max(FieldWidth, (size_t)1);
  449. break;
  450. // Just an integer.
  451. case analyze_format_string::ConversionSpecifier::dArg:
  452. case analyze_format_string::ConversionSpecifier::DArg:
  453. case analyze_format_string::ConversionSpecifier::iArg:
  454. case analyze_format_string::ConversionSpecifier::oArg:
  455. case analyze_format_string::ConversionSpecifier::OArg:
  456. case analyze_format_string::ConversionSpecifier::uArg:
  457. case analyze_format_string::ConversionSpecifier::UArg:
  458. case analyze_format_string::ConversionSpecifier::xArg:
  459. case analyze_format_string::ConversionSpecifier::XArg:
  460. Size += std::max(FieldWidth, Precision);
  461. break;
  462. // %g style conversion switches between %f or %e style dynamically.
  463. // %f always takes less space, so default to it.
  464. case analyze_format_string::ConversionSpecifier::gArg:
  465. case analyze_format_string::ConversionSpecifier::GArg:
  466. // Floating point number in the form '[+]ddd.ddd'.
  467. case analyze_format_string::ConversionSpecifier::fArg:
  468. case analyze_format_string::ConversionSpecifier::FArg:
  469. Size += std::max(FieldWidth, 1 /* integer part */ +
  470. (Precision ? 1 + Precision
  471. : 0) /* period + decimal */);
  472. break;
  473. // Floating point number in the form '[-]d.ddde[+-]dd'.
  474. case analyze_format_string::ConversionSpecifier::eArg:
  475. case analyze_format_string::ConversionSpecifier::EArg:
  476. Size +=
  477. std::max(FieldWidth,
  478. 1 /* integer part */ +
  479. (Precision ? 1 + Precision : 0) /* period + decimal */ +
  480. 1 /* e or E letter */ + 2 /* exponent */);
  481. break;
  482. // Floating point number in the form '[-]0xh.hhhhp±dd'.
  483. case analyze_format_string::ConversionSpecifier::aArg:
  484. case analyze_format_string::ConversionSpecifier::AArg:
  485. Size +=
  486. std::max(FieldWidth,
  487. 2 /* 0x */ + 1 /* integer part */ +
  488. (Precision ? 1 + Precision : 0) /* period + decimal */ +
  489. 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
  490. break;
  491. // Just a string.
  492. case analyze_format_string::ConversionSpecifier::sArg:
  493. case analyze_format_string::ConversionSpecifier::SArg:
  494. Size += FieldWidth;
  495. break;
  496. // Just a pointer in the form '0xddd'.
  497. case analyze_format_string::ConversionSpecifier::pArg:
  498. Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
  499. break;
  500. // A plain percent.
  501. case analyze_format_string::ConversionSpecifier::PercentArg:
  502. Size += 1;
  503. break;
  504. default:
  505. break;
  506. }
  507. Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
  508. if (FS.hasAlternativeForm()) {
  509. switch (FS.getConversionSpecifier().getKind()) {
  510. default:
  511. break;
  512. // Force a leading '0'.
  513. case analyze_format_string::ConversionSpecifier::oArg:
  514. Size += 1;
  515. break;
  516. // Force a leading '0x'.
  517. case analyze_format_string::ConversionSpecifier::xArg:
  518. case analyze_format_string::ConversionSpecifier::XArg:
  519. Size += 2;
  520. break;
  521. // Force a period '.' before decimal, even if precision is 0.
  522. case analyze_format_string::ConversionSpecifier::aArg:
  523. case analyze_format_string::ConversionSpecifier::AArg:
  524. case analyze_format_string::ConversionSpecifier::eArg:
  525. case analyze_format_string::ConversionSpecifier::EArg:
  526. case analyze_format_string::ConversionSpecifier::fArg:
  527. case analyze_format_string::ConversionSpecifier::FArg:
  528. case analyze_format_string::ConversionSpecifier::gArg:
  529. case analyze_format_string::ConversionSpecifier::GArg:
  530. Size += (Precision ? 0 : 1);
  531. break;
  532. }
  533. }
  534. assert(SpecifierLen <= Size && "no underflow");
  535. Size -= SpecifierLen;
  536. return true;
  537. }
  538. size_t getSizeLowerBound() const { return Size; }
  539. private:
  540. static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
  541. const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
  542. size_t FieldWidth = 0;
  543. if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
  544. FieldWidth = FW.getConstantAmount();
  545. return FieldWidth;
  546. }
  547. static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
  548. const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
  549. size_t Precision = 0;
  550. // See man 3 printf for default precision value based on the specifier.
  551. switch (FW.getHowSpecified()) {
  552. case analyze_format_string::OptionalAmount::NotSpecified:
  553. switch (FS.getConversionSpecifier().getKind()) {
  554. default:
  555. break;
  556. case analyze_format_string::ConversionSpecifier::dArg: // %d
  557. case analyze_format_string::ConversionSpecifier::DArg: // %D
  558. case analyze_format_string::ConversionSpecifier::iArg: // %i
  559. Precision = 1;
  560. break;
  561. case analyze_format_string::ConversionSpecifier::oArg: // %d
  562. case analyze_format_string::ConversionSpecifier::OArg: // %D
  563. case analyze_format_string::ConversionSpecifier::uArg: // %d
  564. case analyze_format_string::ConversionSpecifier::UArg: // %D
  565. case analyze_format_string::ConversionSpecifier::xArg: // %d
  566. case analyze_format_string::ConversionSpecifier::XArg: // %D
  567. Precision = 1;
  568. break;
  569. case analyze_format_string::ConversionSpecifier::fArg: // %f
  570. case analyze_format_string::ConversionSpecifier::FArg: // %F
  571. case analyze_format_string::ConversionSpecifier::eArg: // %e
  572. case analyze_format_string::ConversionSpecifier::EArg: // %E
  573. case analyze_format_string::ConversionSpecifier::gArg: // %g
  574. case analyze_format_string::ConversionSpecifier::GArg: // %G
  575. Precision = 6;
  576. break;
  577. case analyze_format_string::ConversionSpecifier::pArg: // %d
  578. Precision = 1;
  579. break;
  580. }
  581. break;
  582. case analyze_format_string::OptionalAmount::Constant:
  583. Precision = FW.getConstantAmount();
  584. break;
  585. default:
  586. break;
  587. }
  588. return Precision;
  589. }
  590. };
  591. } // namespace
  592. void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
  593. CallExpr *TheCall) {
  594. if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
  595. isConstantEvaluated())
  596. return;
  597. bool UseDABAttr = false;
  598. const FunctionDecl *UseDecl = FD;
  599. const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
  600. if (DABAttr) {
  601. UseDecl = DABAttr->getFunction();
  602. assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
  603. UseDABAttr = true;
  604. }
  605. unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
  606. if (!BuiltinID)
  607. return;
  608. const TargetInfo &TI = getASTContext().getTargetInfo();
  609. unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
  610. auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
  611. // If we refer to a diagnose_as_builtin attribute, we need to change the
  612. // argument index to refer to the arguments of the called function. Unless
  613. // the index is out of bounds, which presumably means it's a variadic
  614. // function.
  615. if (!UseDABAttr)
  616. return Index;
  617. unsigned DABIndices = DABAttr->argIndices_size();
  618. unsigned NewIndex = Index < DABIndices
  619. ? DABAttr->argIndices_begin()[Index]
  620. : Index - DABIndices + FD->getNumParams();
  621. if (NewIndex >= TheCall->getNumArgs())
  622. return llvm::None;
  623. return NewIndex;
  624. };
  625. auto ComputeExplicitObjectSizeArgument =
  626. [&](unsigned Index) -> Optional<llvm::APSInt> {
  627. Optional<unsigned> IndexOptional = TranslateIndex(Index);
  628. if (!IndexOptional)
  629. return llvm::None;
  630. unsigned NewIndex = IndexOptional.getValue();
  631. Expr::EvalResult Result;
  632. Expr *SizeArg = TheCall->getArg(NewIndex);
  633. if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
  634. return llvm::None;
  635. llvm::APSInt Integer = Result.Val.getInt();
  636. Integer.setIsUnsigned(true);
  637. return Integer;
  638. };
  639. auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
  640. // If the parameter has a pass_object_size attribute, then we should use its
  641. // (potentially) more strict checking mode. Otherwise, conservatively assume
  642. // type 0.
  643. int BOSType = 0;
  644. // This check can fail for variadic functions.
  645. if (Index < FD->getNumParams()) {
  646. if (const auto *POS =
  647. FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
  648. BOSType = POS->getType();
  649. }
  650. Optional<unsigned> IndexOptional = TranslateIndex(Index);
  651. if (!IndexOptional)
  652. return llvm::None;
  653. unsigned NewIndex = IndexOptional.getValue();
  654. const Expr *ObjArg = TheCall->getArg(NewIndex);
  655. uint64_t Result;
  656. if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
  657. return llvm::None;
  658. // Get the object size in the target's size_t width.
  659. return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
  660. };
  661. auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
  662. Optional<unsigned> IndexOptional = TranslateIndex(Index);
  663. if (!IndexOptional)
  664. return llvm::None;
  665. unsigned NewIndex = IndexOptional.getValue();
  666. const Expr *ObjArg = TheCall->getArg(NewIndex);
  667. uint64_t Result;
  668. if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
  669. return llvm::None;
  670. // Add 1 for null byte.
  671. return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
  672. };
  673. Optional<llvm::APSInt> SourceSize;
  674. Optional<llvm::APSInt> DestinationSize;
  675. unsigned DiagID = 0;
  676. bool IsChkVariant = false;
  677. auto GetFunctionName = [&]() {
  678. StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
  679. // Skim off the details of whichever builtin was called to produce a better
  680. // diagnostic, as it's unlikely that the user wrote the __builtin
  681. // explicitly.
  682. if (IsChkVariant) {
  683. FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
  684. FunctionName = FunctionName.drop_back(std::strlen("_chk"));
  685. } else if (FunctionName.startswith("__builtin_")) {
  686. FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
  687. }
  688. return FunctionName;
  689. };
  690. switch (BuiltinID) {
  691. default:
  692. return;
  693. case Builtin::BI__builtin_strcpy:
  694. case Builtin::BIstrcpy: {
  695. DiagID = diag::warn_fortify_strlen_overflow;
  696. SourceSize = ComputeStrLenArgument(1);
  697. DestinationSize = ComputeSizeArgument(0);
  698. break;
  699. }
  700. case Builtin::BI__builtin___strcpy_chk: {
  701. DiagID = diag::warn_fortify_strlen_overflow;
  702. SourceSize = ComputeStrLenArgument(1);
  703. DestinationSize = ComputeExplicitObjectSizeArgument(2);
  704. IsChkVariant = true;
  705. break;
  706. }
  707. case Builtin::BIscanf:
  708. case Builtin::BIfscanf:
  709. case Builtin::BIsscanf: {
  710. unsigned FormatIndex = 1;
  711. unsigned DataIndex = 2;
  712. if (BuiltinID == Builtin::BIscanf) {
  713. FormatIndex = 0;
  714. DataIndex = 1;
  715. }
  716. const auto *FormatExpr =
  717. TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
  718. const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
  719. if (!Format)
  720. return;
  721. if (!Format->isAscii() && !Format->isUTF8())
  722. return;
  723. auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
  724. unsigned SourceSize) {
  725. DiagID = diag::warn_fortify_scanf_overflow;
  726. unsigned Index = ArgIndex + DataIndex;
  727. StringRef FunctionName = GetFunctionName();
  728. DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
  729. PDiag(DiagID) << FunctionName << (Index + 1)
  730. << DestSize << SourceSize);
  731. };
  732. StringRef FormatStrRef = Format->getString();
  733. auto ShiftedComputeSizeArgument = [&](unsigned Index) {
  734. return ComputeSizeArgument(Index + DataIndex);
  735. };
  736. ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
  737. const char *FormatBytes = FormatStrRef.data();
  738. const ConstantArrayType *T =
  739. Context.getAsConstantArrayType(Format->getType());
  740. assert(T && "String literal not of constant array type!");
  741. size_t TypeSize = T->getSize().getZExtValue();
  742. // In case there's a null byte somewhere.
  743. size_t StrLen =
  744. std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
  745. analyze_format_string::ParseScanfString(H, FormatBytes,
  746. FormatBytes + StrLen, getLangOpts(),
  747. Context.getTargetInfo());
  748. // Unlike the other cases, in this one we have already issued the diagnostic
  749. // here, so no need to continue (because unlike the other cases, here the
  750. // diagnostic refers to the argument number).
  751. return;
  752. }
  753. case Builtin::BIsprintf:
  754. case Builtin::BI__builtin___sprintf_chk: {
  755. size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
  756. auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
  757. if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
  758. if (!Format->isAscii() && !Format->isUTF8())
  759. return;
  760. StringRef FormatStrRef = Format->getString();
  761. EstimateSizeFormatHandler H(FormatStrRef);
  762. const char *FormatBytes = FormatStrRef.data();
  763. const ConstantArrayType *T =
  764. Context.getAsConstantArrayType(Format->getType());
  765. assert(T && "String literal not of constant array type!");
  766. size_t TypeSize = T->getSize().getZExtValue();
  767. // In case there's a null byte somewhere.
  768. size_t StrLen =
  769. std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
  770. if (!analyze_format_string::ParsePrintfString(
  771. H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
  772. Context.getTargetInfo(), false)) {
  773. DiagID = diag::warn_fortify_source_format_overflow;
  774. SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
  775. .extOrTrunc(SizeTypeWidth);
  776. if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
  777. DestinationSize = ComputeExplicitObjectSizeArgument(2);
  778. IsChkVariant = true;
  779. } else {
  780. DestinationSize = ComputeSizeArgument(0);
  781. }
  782. break;
  783. }
  784. }
  785. return;
  786. }
  787. case Builtin::BI__builtin___memcpy_chk:
  788. case Builtin::BI__builtin___memmove_chk:
  789. case Builtin::BI__builtin___memset_chk:
  790. case Builtin::BI__builtin___strlcat_chk:
  791. case Builtin::BI__builtin___strlcpy_chk:
  792. case Builtin::BI__builtin___strncat_chk:
  793. case Builtin::BI__builtin___strncpy_chk:
  794. case Builtin::BI__builtin___stpncpy_chk:
  795. case Builtin::BI__builtin___memccpy_chk:
  796. case Builtin::BI__builtin___mempcpy_chk: {
  797. DiagID = diag::warn_builtin_chk_overflow;
  798. SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
  799. DestinationSize =
  800. ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
  801. IsChkVariant = true;
  802. break;
  803. }
  804. case Builtin::BI__builtin___snprintf_chk:
  805. case Builtin::BI__builtin___vsnprintf_chk: {
  806. DiagID = diag::warn_builtin_chk_overflow;
  807. SourceSize = ComputeExplicitObjectSizeArgument(1);
  808. DestinationSize = ComputeExplicitObjectSizeArgument(3);
  809. IsChkVariant = true;
  810. break;
  811. }
  812. case Builtin::BIstrncat:
  813. case Builtin::BI__builtin_strncat:
  814. case Builtin::BIstrncpy:
  815. case Builtin::BI__builtin_strncpy:
  816. case Builtin::BIstpncpy:
  817. case Builtin::BI__builtin_stpncpy: {
  818. // Whether these functions overflow depends on the runtime strlen of the
  819. // string, not just the buffer size, so emitting the "always overflow"
  820. // diagnostic isn't quite right. We should still diagnose passing a buffer
  821. // size larger than the destination buffer though; this is a runtime abort
  822. // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
  823. DiagID = diag::warn_fortify_source_size_mismatch;
  824. SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
  825. DestinationSize = ComputeSizeArgument(0);
  826. break;
  827. }
  828. case Builtin::BImemcpy:
  829. case Builtin::BI__builtin_memcpy:
  830. case Builtin::BImemmove:
  831. case Builtin::BI__builtin_memmove:
  832. case Builtin::BImemset:
  833. case Builtin::BI__builtin_memset:
  834. case Builtin::BImempcpy:
  835. case Builtin::BI__builtin_mempcpy: {
  836. DiagID = diag::warn_fortify_source_overflow;
  837. SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
  838. DestinationSize = ComputeSizeArgument(0);
  839. break;
  840. }
  841. case Builtin::BIsnprintf:
  842. case Builtin::BI__builtin_snprintf:
  843. case Builtin::BIvsnprintf:
  844. case Builtin::BI__builtin_vsnprintf: {
  845. DiagID = diag::warn_fortify_source_size_mismatch;
  846. SourceSize = ComputeExplicitObjectSizeArgument(1);
  847. DestinationSize = ComputeSizeArgument(0);
  848. break;
  849. }
  850. }
  851. if (!SourceSize || !DestinationSize ||
  852. llvm::APSInt::compareValues(SourceSize.getValue(),
  853. DestinationSize.getValue()) <= 0)
  854. return;
  855. StringRef FunctionName = GetFunctionName();
  856. SmallString<16> DestinationStr;
  857. SmallString<16> SourceStr;
  858. DestinationSize->toString(DestinationStr, /*Radix=*/10);
  859. SourceSize->toString(SourceStr, /*Radix=*/10);
  860. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  861. PDiag(DiagID)
  862. << FunctionName << DestinationStr << SourceStr);
  863. }
  864. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  865. Scope::ScopeFlags NeededScopeFlags,
  866. unsigned DiagID) {
  867. // Scopes aren't available during instantiation. Fortunately, builtin
  868. // functions cannot be template args so they cannot be formed through template
  869. // instantiation. Therefore checking once during the parse is sufficient.
  870. if (SemaRef.inTemplateInstantiation())
  871. return false;
  872. Scope *S = SemaRef.getCurScope();
  873. while (S && !S->isSEHExceptScope())
  874. S = S->getParent();
  875. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  876. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  877. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  878. << DRE->getDecl()->getIdentifier();
  879. return true;
  880. }
  881. return false;
  882. }
  883. static inline bool isBlockPointer(Expr *Arg) {
  884. return Arg->getType()->isBlockPointerType();
  885. }
  886. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  887. /// void*, which is a requirement of device side enqueue.
  888. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  889. const BlockPointerType *BPT =
  890. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  891. ArrayRef<QualType> Params =
  892. BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
  893. unsigned ArgCounter = 0;
  894. bool IllegalParams = false;
  895. // Iterate through the block parameters until either one is found that is not
  896. // a local void*, or the block is valid.
  897. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  898. I != E; ++I, ++ArgCounter) {
  899. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  900. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  901. LangAS::opencl_local) {
  902. // Get the location of the error. If a block literal has been passed
  903. // (BlockExpr) then we can point straight to the offending argument,
  904. // else we just point to the variable reference.
  905. SourceLocation ErrorLoc;
  906. if (isa<BlockExpr>(BlockArg)) {
  907. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  908. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  909. } else if (isa<DeclRefExpr>(BlockArg)) {
  910. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  911. }
  912. S.Diag(ErrorLoc,
  913. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  914. IllegalParams = true;
  915. }
  916. }
  917. return IllegalParams;
  918. }
  919. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  920. // OpenCL device can support extension but not the feature as extension
  921. // requires subgroup independent forward progress, but subgroup independent
  922. // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
  923. if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
  924. !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
  925. S.getLangOpts())) {
  926. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  927. << 1 << Call->getDirectCallee()
  928. << "cl_khr_subgroups or __opencl_c_subgroups";
  929. return true;
  930. }
  931. return false;
  932. }
  933. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  934. if (checkArgCount(S, TheCall, 2))
  935. return true;
  936. if (checkOpenCLSubgroupExt(S, TheCall))
  937. return true;
  938. // First argument is an ndrange_t type.
  939. Expr *NDRangeArg = TheCall->getArg(0);
  940. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  941. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  942. << TheCall->getDirectCallee() << "'ndrange_t'";
  943. return true;
  944. }
  945. Expr *BlockArg = TheCall->getArg(1);
  946. if (!isBlockPointer(BlockArg)) {
  947. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  948. << TheCall->getDirectCallee() << "block";
  949. return true;
  950. }
  951. return checkOpenCLBlockArgs(S, BlockArg);
  952. }
  953. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  954. /// get_kernel_work_group_size
  955. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  956. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  957. if (checkArgCount(S, TheCall, 1))
  958. return true;
  959. Expr *BlockArg = TheCall->getArg(0);
  960. if (!isBlockPointer(BlockArg)) {
  961. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  962. << TheCall->getDirectCallee() << "block";
  963. return true;
  964. }
  965. return checkOpenCLBlockArgs(S, BlockArg);
  966. }
  967. /// Diagnose integer type and any valid implicit conversion to it.
  968. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  969. const QualType &IntType);
  970. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  971. unsigned Start, unsigned End) {
  972. bool IllegalParams = false;
  973. for (unsigned I = Start; I <= End; ++I)
  974. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  975. S.Context.getSizeType());
  976. return IllegalParams;
  977. }
  978. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  979. /// 'local void*' parameter of passed block.
  980. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  981. Expr *BlockArg,
  982. unsigned NumNonVarArgs) {
  983. const BlockPointerType *BPT =
  984. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  985. unsigned NumBlockParams =
  986. BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
  987. unsigned TotalNumArgs = TheCall->getNumArgs();
  988. // For each argument passed to the block, a corresponding uint needs to
  989. // be passed to describe the size of the local memory.
  990. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  991. S.Diag(TheCall->getBeginLoc(),
  992. diag::err_opencl_enqueue_kernel_local_size_args);
  993. return true;
  994. }
  995. // Check that the sizes of the local memory are specified by integers.
  996. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  997. TotalNumArgs - 1);
  998. }
  999. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  1000. /// overload formats specified in Table 6.13.17.1.
  1001. /// int enqueue_kernel(queue_t queue,
  1002. /// kernel_enqueue_flags_t flags,
  1003. /// const ndrange_t ndrange,
  1004. /// void (^block)(void))
  1005. /// int enqueue_kernel(queue_t queue,
  1006. /// kernel_enqueue_flags_t flags,
  1007. /// const ndrange_t ndrange,
  1008. /// uint num_events_in_wait_list,
  1009. /// clk_event_t *event_wait_list,
  1010. /// clk_event_t *event_ret,
  1011. /// void (^block)(void))
  1012. /// int enqueue_kernel(queue_t queue,
  1013. /// kernel_enqueue_flags_t flags,
  1014. /// const ndrange_t ndrange,
  1015. /// void (^block)(local void*, ...),
  1016. /// uint size0, ...)
  1017. /// int enqueue_kernel(queue_t queue,
  1018. /// kernel_enqueue_flags_t flags,
  1019. /// const ndrange_t ndrange,
  1020. /// uint num_events_in_wait_list,
  1021. /// clk_event_t *event_wait_list,
  1022. /// clk_event_t *event_ret,
  1023. /// void (^block)(local void*, ...),
  1024. /// uint size0, ...)
  1025. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  1026. unsigned NumArgs = TheCall->getNumArgs();
  1027. if (NumArgs < 4) {
  1028. S.Diag(TheCall->getBeginLoc(),
  1029. diag::err_typecheck_call_too_few_args_at_least)
  1030. << 0 << 4 << NumArgs;
  1031. return true;
  1032. }
  1033. Expr *Arg0 = TheCall->getArg(0);
  1034. Expr *Arg1 = TheCall->getArg(1);
  1035. Expr *Arg2 = TheCall->getArg(2);
  1036. Expr *Arg3 = TheCall->getArg(3);
  1037. // First argument always needs to be a queue_t type.
  1038. if (!Arg0->getType()->isQueueT()) {
  1039. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  1040. diag::err_opencl_builtin_expected_type)
  1041. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  1042. return true;
  1043. }
  1044. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  1045. if (!Arg1->getType()->isIntegerType()) {
  1046. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  1047. diag::err_opencl_builtin_expected_type)
  1048. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  1049. return true;
  1050. }
  1051. // Third argument is always an ndrange_t type.
  1052. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  1053. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  1054. diag::err_opencl_builtin_expected_type)
  1055. << TheCall->getDirectCallee() << "'ndrange_t'";
  1056. return true;
  1057. }
  1058. // With four arguments, there is only one form that the function could be
  1059. // called in: no events and no variable arguments.
  1060. if (NumArgs == 4) {
  1061. // check that the last argument is the right block type.
  1062. if (!isBlockPointer(Arg3)) {
  1063. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  1064. << TheCall->getDirectCallee() << "block";
  1065. return true;
  1066. }
  1067. // we have a block type, check the prototype
  1068. const BlockPointerType *BPT =
  1069. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  1070. if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
  1071. S.Diag(Arg3->getBeginLoc(),
  1072. diag::err_opencl_enqueue_kernel_blocks_no_args);
  1073. return true;
  1074. }
  1075. return false;
  1076. }
  1077. // we can have block + varargs.
  1078. if (isBlockPointer(Arg3))
  1079. return (checkOpenCLBlockArgs(S, Arg3) ||
  1080. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  1081. // last two cases with either exactly 7 args or 7 args and varargs.
  1082. if (NumArgs >= 7) {
  1083. // check common block argument.
  1084. Expr *Arg6 = TheCall->getArg(6);
  1085. if (!isBlockPointer(Arg6)) {
  1086. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  1087. << TheCall->getDirectCallee() << "block";
  1088. return true;
  1089. }
  1090. if (checkOpenCLBlockArgs(S, Arg6))
  1091. return true;
  1092. // Forth argument has to be any integer type.
  1093. if (!Arg3->getType()->isIntegerType()) {
  1094. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  1095. diag::err_opencl_builtin_expected_type)
  1096. << TheCall->getDirectCallee() << "integer";
  1097. return true;
  1098. }
  1099. // check remaining common arguments.
  1100. Expr *Arg4 = TheCall->getArg(4);
  1101. Expr *Arg5 = TheCall->getArg(5);
  1102. // Fifth argument is always passed as a pointer to clk_event_t.
  1103. if (!Arg4->isNullPointerConstant(S.Context,
  1104. Expr::NPC_ValueDependentIsNotNull) &&
  1105. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  1106. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  1107. diag::err_opencl_builtin_expected_type)
  1108. << TheCall->getDirectCallee()
  1109. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  1110. return true;
  1111. }
  1112. // Sixth argument is always passed as a pointer to clk_event_t.
  1113. if (!Arg5->isNullPointerConstant(S.Context,
  1114. Expr::NPC_ValueDependentIsNotNull) &&
  1115. !(Arg5->getType()->isPointerType() &&
  1116. Arg5->getType()->getPointeeType()->isClkEventT())) {
  1117. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  1118. diag::err_opencl_builtin_expected_type)
  1119. << TheCall->getDirectCallee()
  1120. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  1121. return true;
  1122. }
  1123. if (NumArgs == 7)
  1124. return false;
  1125. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  1126. }
  1127. // None of the specific case has been detected, give generic error
  1128. S.Diag(TheCall->getBeginLoc(),
  1129. diag::err_opencl_enqueue_kernel_incorrect_args);
  1130. return true;
  1131. }
  1132. /// Returns OpenCL access qual.
  1133. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  1134. return D->getAttr<OpenCLAccessAttr>();
  1135. }
  1136. /// Returns true if pipe element type is different from the pointer.
  1137. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  1138. const Expr *Arg0 = Call->getArg(0);
  1139. // First argument type should always be pipe.
  1140. if (!Arg0->getType()->isPipeType()) {
  1141. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  1142. << Call->getDirectCallee() << Arg0->getSourceRange();
  1143. return true;
  1144. }
  1145. OpenCLAccessAttr *AccessQual =
  1146. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  1147. // Validates the access qualifier is compatible with the call.
  1148. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  1149. // read_only and write_only, and assumed to be read_only if no qualifier is
  1150. // specified.
  1151. switch (Call->getDirectCallee()->getBuiltinID()) {
  1152. case Builtin::BIread_pipe:
  1153. case Builtin::BIreserve_read_pipe:
  1154. case Builtin::BIcommit_read_pipe:
  1155. case Builtin::BIwork_group_reserve_read_pipe:
  1156. case Builtin::BIsub_group_reserve_read_pipe:
  1157. case Builtin::BIwork_group_commit_read_pipe:
  1158. case Builtin::BIsub_group_commit_read_pipe:
  1159. if (!(!AccessQual || AccessQual->isReadOnly())) {
  1160. S.Diag(Arg0->getBeginLoc(),
  1161. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  1162. << "read_only" << Arg0->getSourceRange();
  1163. return true;
  1164. }
  1165. break;
  1166. case Builtin::BIwrite_pipe:
  1167. case Builtin::BIreserve_write_pipe:
  1168. case Builtin::BIcommit_write_pipe:
  1169. case Builtin::BIwork_group_reserve_write_pipe:
  1170. case Builtin::BIsub_group_reserve_write_pipe:
  1171. case Builtin::BIwork_group_commit_write_pipe:
  1172. case Builtin::BIsub_group_commit_write_pipe:
  1173. if (!(AccessQual && AccessQual->isWriteOnly())) {
  1174. S.Diag(Arg0->getBeginLoc(),
  1175. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  1176. << "write_only" << Arg0->getSourceRange();
  1177. return true;
  1178. }
  1179. break;
  1180. default:
  1181. break;
  1182. }
  1183. return false;
  1184. }
  1185. /// Returns true if pipe element type is different from the pointer.
  1186. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  1187. const Expr *Arg0 = Call->getArg(0);
  1188. const Expr *ArgIdx = Call->getArg(Idx);
  1189. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  1190. const QualType EltTy = PipeTy->getElementType();
  1191. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  1192. // The Idx argument should be a pointer and the type of the pointer and
  1193. // the type of pipe element should also be the same.
  1194. if (!ArgTy ||
  1195. !S.Context.hasSameType(
  1196. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  1197. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1198. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  1199. << ArgIdx->getType() << ArgIdx->getSourceRange();
  1200. return true;
  1201. }
  1202. return false;
  1203. }
  1204. // Performs semantic analysis for the read/write_pipe call.
  1205. // \param S Reference to the semantic analyzer.
  1206. // \param Call A pointer to the builtin call.
  1207. // \return True if a semantic error has been found, false otherwise.
  1208. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  1209. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  1210. // functions have two forms.
  1211. switch (Call->getNumArgs()) {
  1212. case 2:
  1213. if (checkOpenCLPipeArg(S, Call))
  1214. return true;
  1215. // The call with 2 arguments should be
  1216. // read/write_pipe(pipe T, T*).
  1217. // Check packet type T.
  1218. if (checkOpenCLPipePacketType(S, Call, 1))
  1219. return true;
  1220. break;
  1221. case 4: {
  1222. if (checkOpenCLPipeArg(S, Call))
  1223. return true;
  1224. // The call with 4 arguments should be
  1225. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  1226. // Check reserve_id_t.
  1227. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  1228. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1229. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  1230. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  1231. return true;
  1232. }
  1233. // Check the index.
  1234. const Expr *Arg2 = Call->getArg(2);
  1235. if (!Arg2->getType()->isIntegerType() &&
  1236. !Arg2->getType()->isUnsignedIntegerType()) {
  1237. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1238. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  1239. << Arg2->getType() << Arg2->getSourceRange();
  1240. return true;
  1241. }
  1242. // Check packet type T.
  1243. if (checkOpenCLPipePacketType(S, Call, 3))
  1244. return true;
  1245. } break;
  1246. default:
  1247. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  1248. << Call->getDirectCallee() << Call->getSourceRange();
  1249. return true;
  1250. }
  1251. return false;
  1252. }
  1253. // Performs a semantic analysis on the {work_group_/sub_group_
  1254. // /_}reserve_{read/write}_pipe
  1255. // \param S Reference to the semantic analyzer.
  1256. // \param Call The call to the builtin function to be analyzed.
  1257. // \return True if a semantic error was found, false otherwise.
  1258. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  1259. if (checkArgCount(S, Call, 2))
  1260. return true;
  1261. if (checkOpenCLPipeArg(S, Call))
  1262. return true;
  1263. // Check the reserve size.
  1264. if (!Call->getArg(1)->getType()->isIntegerType() &&
  1265. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  1266. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1267. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  1268. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  1269. return true;
  1270. }
  1271. // Since return type of reserve_read/write_pipe built-in function is
  1272. // reserve_id_t, which is not defined in the builtin def file , we used int
  1273. // as return type and need to override the return type of these functions.
  1274. Call->setType(S.Context.OCLReserveIDTy);
  1275. return false;
  1276. }
  1277. // Performs a semantic analysis on {work_group_/sub_group_
  1278. // /_}commit_{read/write}_pipe
  1279. // \param S Reference to the semantic analyzer.
  1280. // \param Call The call to the builtin function to be analyzed.
  1281. // \return True if a semantic error was found, false otherwise.
  1282. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  1283. if (checkArgCount(S, Call, 2))
  1284. return true;
  1285. if (checkOpenCLPipeArg(S, Call))
  1286. return true;
  1287. // Check reserve_id_t.
  1288. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  1289. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1290. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  1291. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  1292. return true;
  1293. }
  1294. return false;
  1295. }
  1296. // Performs a semantic analysis on the call to built-in Pipe
  1297. // Query Functions.
  1298. // \param S Reference to the semantic analyzer.
  1299. // \param Call The call to the builtin function to be analyzed.
  1300. // \return True if a semantic error was found, false otherwise.
  1301. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  1302. if (checkArgCount(S, Call, 1))
  1303. return true;
  1304. if (!Call->getArg(0)->getType()->isPipeType()) {
  1305. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  1306. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  1307. return true;
  1308. }
  1309. return false;
  1310. }
  1311. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  1312. // Performs semantic analysis for the to_global/local/private call.
  1313. // \param S Reference to the semantic analyzer.
  1314. // \param BuiltinID ID of the builtin function.
  1315. // \param Call A pointer to the builtin call.
  1316. // \return True if a semantic error has been found, false otherwise.
  1317. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  1318. CallExpr *Call) {
  1319. if (checkArgCount(S, Call, 1))
  1320. return true;
  1321. auto RT = Call->getArg(0)->getType();
  1322. if (!RT->isPointerType() || RT->getPointeeType()
  1323. .getAddressSpace() == LangAS::opencl_constant) {
  1324. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  1325. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  1326. return true;
  1327. }
  1328. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  1329. S.Diag(Call->getArg(0)->getBeginLoc(),
  1330. diag::warn_opencl_generic_address_space_arg)
  1331. << Call->getDirectCallee()->getNameInfo().getAsString()
  1332. << Call->getArg(0)->getSourceRange();
  1333. }
  1334. RT = RT->getPointeeType();
  1335. auto Qual = RT.getQualifiers();
  1336. switch (BuiltinID) {
  1337. case Builtin::BIto_global:
  1338. Qual.setAddressSpace(LangAS::opencl_global);
  1339. break;
  1340. case Builtin::BIto_local:
  1341. Qual.setAddressSpace(LangAS::opencl_local);
  1342. break;
  1343. case Builtin::BIto_private:
  1344. Qual.setAddressSpace(LangAS::opencl_private);
  1345. break;
  1346. default:
  1347. llvm_unreachable("Invalid builtin function");
  1348. }
  1349. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  1350. RT.getUnqualifiedType(), Qual)));
  1351. return false;
  1352. }
  1353. static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
  1354. if (checkArgCount(S, TheCall, 1))
  1355. return ExprError();
  1356. // Compute __builtin_launder's parameter type from the argument.
  1357. // The parameter type is:
  1358. // * The type of the argument if it's not an array or function type,
  1359. // Otherwise,
  1360. // * The decayed argument type.
  1361. QualType ParamTy = [&]() {
  1362. QualType ArgTy = TheCall->getArg(0)->getType();
  1363. if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
  1364. return S.Context.getPointerType(Ty->getElementType());
  1365. if (ArgTy->isFunctionType()) {
  1366. return S.Context.getPointerType(ArgTy);
  1367. }
  1368. return ArgTy;
  1369. }();
  1370. TheCall->setType(ParamTy);
  1371. auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
  1372. if (!ParamTy->isPointerType())
  1373. return 0;
  1374. if (ParamTy->isFunctionPointerType())
  1375. return 1;
  1376. if (ParamTy->isVoidPointerType())
  1377. return 2;
  1378. return llvm::Optional<unsigned>{};
  1379. }();
  1380. if (DiagSelect.hasValue()) {
  1381. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
  1382. << DiagSelect.getValue() << TheCall->getSourceRange();
  1383. return ExprError();
  1384. }
  1385. // We either have an incomplete class type, or we have a class template
  1386. // whose instantiation has not been forced. Example:
  1387. //
  1388. // template <class T> struct Foo { T value; };
  1389. // Foo<int> *p = nullptr;
  1390. // auto *d = __builtin_launder(p);
  1391. if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
  1392. diag::err_incomplete_type))
  1393. return ExprError();
  1394. assert(ParamTy->getPointeeType()->isObjectType() &&
  1395. "Unhandled non-object pointer case");
  1396. InitializedEntity Entity =
  1397. InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
  1398. ExprResult Arg =
  1399. S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
  1400. if (Arg.isInvalid())
  1401. return ExprError();
  1402. TheCall->setArg(0, Arg.get());
  1403. return TheCall;
  1404. }
  1405. // Emit an error and return true if the current object format type is in the
  1406. // list of unsupported types.
  1407. static bool CheckBuiltinTargetNotInUnsupported(
  1408. Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  1409. ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
  1410. llvm::Triple::ObjectFormatType CurObjFormat =
  1411. S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
  1412. if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
  1413. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  1414. << TheCall->getSourceRange();
  1415. return true;
  1416. }
  1417. return false;
  1418. }
  1419. // Emit an error and return true if the current architecture is not in the list
  1420. // of supported architectures.
  1421. static bool
  1422. CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  1423. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  1424. llvm::Triple::ArchType CurArch =
  1425. S.getASTContext().getTargetInfo().getTriple().getArch();
  1426. if (llvm::is_contained(SupportedArchs, CurArch))
  1427. return false;
  1428. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  1429. << TheCall->getSourceRange();
  1430. return true;
  1431. }
  1432. static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
  1433. SourceLocation CallSiteLoc);
  1434. bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  1435. CallExpr *TheCall) {
  1436. switch (TI.getTriple().getArch()) {
  1437. default:
  1438. // Some builtins don't require additional checking, so just consider these
  1439. // acceptable.
  1440. return false;
  1441. case llvm::Triple::arm:
  1442. case llvm::Triple::armeb:
  1443. case llvm::Triple::thumb:
  1444. case llvm::Triple::thumbeb:
  1445. return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
  1446. case llvm::Triple::aarch64:
  1447. case llvm::Triple::aarch64_32:
  1448. case llvm::Triple::aarch64_be:
  1449. return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
  1450. case llvm::Triple::bpfeb:
  1451. case llvm::Triple::bpfel:
  1452. return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
  1453. case llvm::Triple::hexagon:
  1454. return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
  1455. case llvm::Triple::mips:
  1456. case llvm::Triple::mipsel:
  1457. case llvm::Triple::mips64:
  1458. case llvm::Triple::mips64el:
  1459. return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
  1460. case llvm::Triple::systemz:
  1461. return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
  1462. case llvm::Triple::x86:
  1463. case llvm::Triple::x86_64:
  1464. return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
  1465. case llvm::Triple::ppc:
  1466. case llvm::Triple::ppcle:
  1467. case llvm::Triple::ppc64:
  1468. case llvm::Triple::ppc64le:
  1469. return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
  1470. case llvm::Triple::amdgcn:
  1471. return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
  1472. case llvm::Triple::riscv32:
  1473. case llvm::Triple::riscv64:
  1474. return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
  1475. }
  1476. }
  1477. ExprResult
  1478. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  1479. CallExpr *TheCall) {
  1480. ExprResult TheCallResult(TheCall);
  1481. // Find out if any arguments are required to be integer constant expressions.
  1482. unsigned ICEArguments = 0;
  1483. ASTContext::GetBuiltinTypeError Error;
  1484. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  1485. if (Error != ASTContext::GE_None)
  1486. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  1487. // If any arguments are required to be ICE's, check and diagnose.
  1488. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  1489. // Skip arguments not required to be ICE's.
  1490. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  1491. llvm::APSInt Result;
  1492. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  1493. return true;
  1494. ICEArguments &= ~(1 << ArgNo);
  1495. }
  1496. switch (BuiltinID) {
  1497. case Builtin::BI__builtin___CFStringMakeConstantString:
  1498. // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
  1499. // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
  1500. if (CheckBuiltinTargetNotInUnsupported(
  1501. *this, BuiltinID, TheCall,
  1502. {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
  1503. return ExprError();
  1504. assert(TheCall->getNumArgs() == 1 &&
  1505. "Wrong # arguments to builtin CFStringMakeConstantString");
  1506. if (CheckObjCString(TheCall->getArg(0)))
  1507. return ExprError();
  1508. break;
  1509. case Builtin::BI__builtin_ms_va_start:
  1510. case Builtin::BI__builtin_stdarg_start:
  1511. case Builtin::BI__builtin_va_start:
  1512. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  1513. return ExprError();
  1514. break;
  1515. case Builtin::BI__va_start: {
  1516. switch (Context.getTargetInfo().getTriple().getArch()) {
  1517. case llvm::Triple::aarch64:
  1518. case llvm::Triple::arm:
  1519. case llvm::Triple::thumb:
  1520. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  1521. return ExprError();
  1522. break;
  1523. default:
  1524. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  1525. return ExprError();
  1526. break;
  1527. }
  1528. break;
  1529. }
  1530. // The acquire, release, and no fence variants are ARM and AArch64 only.
  1531. case Builtin::BI_interlockedbittestandset_acq:
  1532. case Builtin::BI_interlockedbittestandset_rel:
  1533. case Builtin::BI_interlockedbittestandset_nf:
  1534. case Builtin::BI_interlockedbittestandreset_acq:
  1535. case Builtin::BI_interlockedbittestandreset_rel:
  1536. case Builtin::BI_interlockedbittestandreset_nf:
  1537. if (CheckBuiltinTargetInSupported(
  1538. *this, BuiltinID, TheCall,
  1539. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  1540. return ExprError();
  1541. break;
  1542. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  1543. case Builtin::BI_bittest64:
  1544. case Builtin::BI_bittestandcomplement64:
  1545. case Builtin::BI_bittestandreset64:
  1546. case Builtin::BI_bittestandset64:
  1547. case Builtin::BI_interlockedbittestandreset64:
  1548. case Builtin::BI_interlockedbittestandset64:
  1549. if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
  1550. {llvm::Triple::x86_64, llvm::Triple::arm,
  1551. llvm::Triple::thumb,
  1552. llvm::Triple::aarch64}))
  1553. return ExprError();
  1554. break;
  1555. case Builtin::BI__builtin_isgreater:
  1556. case Builtin::BI__builtin_isgreaterequal:
  1557. case Builtin::BI__builtin_isless:
  1558. case Builtin::BI__builtin_islessequal:
  1559. case Builtin::BI__builtin_islessgreater:
  1560. case Builtin::BI__builtin_isunordered:
  1561. if (SemaBuiltinUnorderedCompare(TheCall))
  1562. return ExprError();
  1563. break;
  1564. case Builtin::BI__builtin_fpclassify:
  1565. if (SemaBuiltinFPClassification(TheCall, 6))
  1566. return ExprError();
  1567. break;
  1568. case Builtin::BI__builtin_isfinite:
  1569. case Builtin::BI__builtin_isinf:
  1570. case Builtin::BI__builtin_isinf_sign:
  1571. case Builtin::BI__builtin_isnan:
  1572. case Builtin::BI__builtin_isnormal:
  1573. case Builtin::BI__builtin_signbit:
  1574. case Builtin::BI__builtin_signbitf:
  1575. case Builtin::BI__builtin_signbitl:
  1576. if (SemaBuiltinFPClassification(TheCall, 1))
  1577. return ExprError();
  1578. break;
  1579. case Builtin::BI__builtin_shufflevector:
  1580. return SemaBuiltinShuffleVector(TheCall);
  1581. // TheCall will be freed by the smart pointer here, but that's fine, since
  1582. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  1583. case Builtin::BI__builtin_prefetch:
  1584. if (SemaBuiltinPrefetch(TheCall))
  1585. return ExprError();
  1586. break;
  1587. case Builtin::BI__builtin_alloca_with_align:
  1588. case Builtin::BI__builtin_alloca_with_align_uninitialized:
  1589. if (SemaBuiltinAllocaWithAlign(TheCall))
  1590. return ExprError();
  1591. LLVM_FALLTHROUGH;
  1592. case Builtin::BI__builtin_alloca:
  1593. case Builtin::BI__builtin_alloca_uninitialized:
  1594. Diag(TheCall->getBeginLoc(), diag::warn_alloca)
  1595. << TheCall->getDirectCallee();
  1596. break;
  1597. case Builtin::BI__arithmetic_fence:
  1598. if (SemaBuiltinArithmeticFence(TheCall))
  1599. return ExprError();
  1600. break;
  1601. case Builtin::BI__assume:
  1602. case Builtin::BI__builtin_assume:
  1603. if (SemaBuiltinAssume(TheCall))
  1604. return ExprError();
  1605. break;
  1606. case Builtin::BI__builtin_assume_aligned:
  1607. if (SemaBuiltinAssumeAligned(TheCall))
  1608. return ExprError();
  1609. break;
  1610. case Builtin::BI__builtin_dynamic_object_size:
  1611. case Builtin::BI__builtin_object_size:
  1612. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  1613. return ExprError();
  1614. break;
  1615. case Builtin::BI__builtin_longjmp:
  1616. if (SemaBuiltinLongjmp(TheCall))
  1617. return ExprError();
  1618. break;
  1619. case Builtin::BI__builtin_setjmp:
  1620. if (SemaBuiltinSetjmp(TheCall))
  1621. return ExprError();
  1622. break;
  1623. case Builtin::BI__builtin_classify_type:
  1624. if (checkArgCount(*this, TheCall, 1)) return true;
  1625. TheCall->setType(Context.IntTy);
  1626. break;
  1627. case Builtin::BI__builtin_complex:
  1628. if (SemaBuiltinComplex(TheCall))
  1629. return ExprError();
  1630. break;
  1631. case Builtin::BI__builtin_constant_p: {
  1632. if (checkArgCount(*this, TheCall, 1)) return true;
  1633. ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  1634. if (Arg.isInvalid()) return true;
  1635. TheCall->setArg(0, Arg.get());
  1636. TheCall->setType(Context.IntTy);
  1637. break;
  1638. }
  1639. case Builtin::BI__builtin_launder:
  1640. return SemaBuiltinLaunder(*this, TheCall);
  1641. case Builtin::BI__sync_fetch_and_add:
  1642. case Builtin::BI__sync_fetch_and_add_1:
  1643. case Builtin::BI__sync_fetch_and_add_2:
  1644. case Builtin::BI__sync_fetch_and_add_4:
  1645. case Builtin::BI__sync_fetch_and_add_8:
  1646. case Builtin::BI__sync_fetch_and_add_16:
  1647. case Builtin::BI__sync_fetch_and_sub:
  1648. case Builtin::BI__sync_fetch_and_sub_1:
  1649. case Builtin::BI__sync_fetch_and_sub_2:
  1650. case Builtin::BI__sync_fetch_and_sub_4:
  1651. case Builtin::BI__sync_fetch_and_sub_8:
  1652. case Builtin::BI__sync_fetch_and_sub_16:
  1653. case Builtin::BI__sync_fetch_and_or:
  1654. case Builtin::BI__sync_fetch_and_or_1:
  1655. case Builtin::BI__sync_fetch_and_or_2:
  1656. case Builtin::BI__sync_fetch_and_or_4:
  1657. case Builtin::BI__sync_fetch_and_or_8:
  1658. case Builtin::BI__sync_fetch_and_or_16:
  1659. case Builtin::BI__sync_fetch_and_and:
  1660. case Builtin::BI__sync_fetch_and_and_1:
  1661. case Builtin::BI__sync_fetch_and_and_2:
  1662. case Builtin::BI__sync_fetch_and_and_4:
  1663. case Builtin::BI__sync_fetch_and_and_8:
  1664. case Builtin::BI__sync_fetch_and_and_16:
  1665. case Builtin::BI__sync_fetch_and_xor:
  1666. case Builtin::BI__sync_fetch_and_xor_1:
  1667. case Builtin::BI__sync_fetch_and_xor_2:
  1668. case Builtin::BI__sync_fetch_and_xor_4:
  1669. case Builtin::BI__sync_fetch_and_xor_8:
  1670. case Builtin::BI__sync_fetch_and_xor_16:
  1671. case Builtin::BI__sync_fetch_and_nand:
  1672. case Builtin::BI__sync_fetch_and_nand_1:
  1673. case Builtin::BI__sync_fetch_and_nand_2:
  1674. case Builtin::BI__sync_fetch_and_nand_4:
  1675. case Builtin::BI__sync_fetch_and_nand_8:
  1676. case Builtin::BI__sync_fetch_and_nand_16:
  1677. case Builtin::BI__sync_add_and_fetch:
  1678. case Builtin::BI__sync_add_and_fetch_1:
  1679. case Builtin::BI__sync_add_and_fetch_2:
  1680. case Builtin::BI__sync_add_and_fetch_4:
  1681. case Builtin::BI__sync_add_and_fetch_8:
  1682. case Builtin::BI__sync_add_and_fetch_16:
  1683. case Builtin::BI__sync_sub_and_fetch:
  1684. case Builtin::BI__sync_sub_and_fetch_1:
  1685. case Builtin::BI__sync_sub_and_fetch_2:
  1686. case Builtin::BI__sync_sub_and_fetch_4:
  1687. case Builtin::BI__sync_sub_and_fetch_8:
  1688. case Builtin::BI__sync_sub_and_fetch_16:
  1689. case Builtin::BI__sync_and_and_fetch:
  1690. case Builtin::BI__sync_and_and_fetch_1:
  1691. case Builtin::BI__sync_and_and_fetch_2:
  1692. case Builtin::BI__sync_and_and_fetch_4:
  1693. case Builtin::BI__sync_and_and_fetch_8:
  1694. case Builtin::BI__sync_and_and_fetch_16:
  1695. case Builtin::BI__sync_or_and_fetch:
  1696. case Builtin::BI__sync_or_and_fetch_1:
  1697. case Builtin::BI__sync_or_and_fetch_2:
  1698. case Builtin::BI__sync_or_and_fetch_4:
  1699. case Builtin::BI__sync_or_and_fetch_8:
  1700. case Builtin::BI__sync_or_and_fetch_16:
  1701. case Builtin::BI__sync_xor_and_fetch:
  1702. case Builtin::BI__sync_xor_and_fetch_1:
  1703. case Builtin::BI__sync_xor_and_fetch_2:
  1704. case Builtin::BI__sync_xor_and_fetch_4:
  1705. case Builtin::BI__sync_xor_and_fetch_8:
  1706. case Builtin::BI__sync_xor_and_fetch_16:
  1707. case Builtin::BI__sync_nand_and_fetch:
  1708. case Builtin::BI__sync_nand_and_fetch_1:
  1709. case Builtin::BI__sync_nand_and_fetch_2:
  1710. case Builtin::BI__sync_nand_and_fetch_4:
  1711. case Builtin::BI__sync_nand_and_fetch_8:
  1712. case Builtin::BI__sync_nand_and_fetch_16:
  1713. case Builtin::BI__sync_val_compare_and_swap:
  1714. case Builtin::BI__sync_val_compare_and_swap_1:
  1715. case Builtin::BI__sync_val_compare_and_swap_2:
  1716. case Builtin::BI__sync_val_compare_and_swap_4:
  1717. case Builtin::BI__sync_val_compare_and_swap_8:
  1718. case Builtin::BI__sync_val_compare_and_swap_16:
  1719. case Builtin::BI__sync_bool_compare_and_swap:
  1720. case Builtin::BI__sync_bool_compare_and_swap_1:
  1721. case Builtin::BI__sync_bool_compare_and_swap_2:
  1722. case Builtin::BI__sync_bool_compare_and_swap_4:
  1723. case Builtin::BI__sync_bool_compare_and_swap_8:
  1724. case Builtin::BI__sync_bool_compare_and_swap_16:
  1725. case Builtin::BI__sync_lock_test_and_set:
  1726. case Builtin::BI__sync_lock_test_and_set_1:
  1727. case Builtin::BI__sync_lock_test_and_set_2:
  1728. case Builtin::BI__sync_lock_test_and_set_4:
  1729. case Builtin::BI__sync_lock_test_and_set_8:
  1730. case Builtin::BI__sync_lock_test_and_set_16:
  1731. case Builtin::BI__sync_lock_release:
  1732. case Builtin::BI__sync_lock_release_1:
  1733. case Builtin::BI__sync_lock_release_2:
  1734. case Builtin::BI__sync_lock_release_4:
  1735. case Builtin::BI__sync_lock_release_8:
  1736. case Builtin::BI__sync_lock_release_16:
  1737. case Builtin::BI__sync_swap:
  1738. case Builtin::BI__sync_swap_1:
  1739. case Builtin::BI__sync_swap_2:
  1740. case Builtin::BI__sync_swap_4:
  1741. case Builtin::BI__sync_swap_8:
  1742. case Builtin::BI__sync_swap_16:
  1743. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1744. case Builtin::BI__sync_synchronize:
  1745. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  1746. << TheCall->getCallee()->getSourceRange();
  1747. break;
  1748. case Builtin::BI__builtin_nontemporal_load:
  1749. case Builtin::BI__builtin_nontemporal_store:
  1750. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1751. case Builtin::BI__builtin_memcpy_inline: {
  1752. clang::Expr *SizeOp = TheCall->getArg(2);
  1753. // We warn about copying to or from `nullptr` pointers when `size` is
  1754. // greater than 0. When `size` is value dependent we cannot evaluate its
  1755. // value so we bail out.
  1756. if (SizeOp->isValueDependent())
  1757. break;
  1758. if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
  1759. CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
  1760. CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
  1761. }
  1762. break;
  1763. }
  1764. #define BUILTIN(ID, TYPE, ATTRS)
  1765. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1766. case Builtin::BI##ID: \
  1767. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1768. #include "clang/Basic/Builtins.def"
  1769. case Builtin::BI__annotation:
  1770. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1771. return ExprError();
  1772. break;
  1773. case Builtin::BI__builtin_annotation:
  1774. if (SemaBuiltinAnnotation(*this, TheCall))
  1775. return ExprError();
  1776. break;
  1777. case Builtin::BI__builtin_addressof:
  1778. if (SemaBuiltinAddressof(*this, TheCall))
  1779. return ExprError();
  1780. break;
  1781. case Builtin::BI__builtin_function_start:
  1782. if (SemaBuiltinFunctionStart(*this, TheCall))
  1783. return ExprError();
  1784. break;
  1785. case Builtin::BI__builtin_is_aligned:
  1786. case Builtin::BI__builtin_align_up:
  1787. case Builtin::BI__builtin_align_down:
  1788. if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
  1789. return ExprError();
  1790. break;
  1791. case Builtin::BI__builtin_add_overflow:
  1792. case Builtin::BI__builtin_sub_overflow:
  1793. case Builtin::BI__builtin_mul_overflow:
  1794. if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
  1795. return ExprError();
  1796. break;
  1797. case Builtin::BI__builtin_operator_new:
  1798. case Builtin::BI__builtin_operator_delete: {
  1799. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1800. ExprResult Res =
  1801. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1802. if (Res.isInvalid())
  1803. CorrectDelayedTyposInExpr(TheCallResult.get());
  1804. return Res;
  1805. }
  1806. case Builtin::BI__builtin_dump_struct: {
  1807. // We first want to ensure we are called with 2 arguments
  1808. if (checkArgCount(*this, TheCall, 2))
  1809. return ExprError();
  1810. // Ensure that the first argument is of type 'struct XX *'
  1811. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1812. const QualType PtrArgType = PtrArg->getType();
  1813. if (!PtrArgType->isPointerType() ||
  1814. !PtrArgType->getPointeeType()->isRecordType()) {
  1815. Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1816. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1817. << "structure pointer";
  1818. return ExprError();
  1819. }
  1820. // Ensure that the second argument is of type 'FunctionType'
  1821. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1822. const QualType FnPtrArgType = FnPtrArg->getType();
  1823. if (!FnPtrArgType->isPointerType()) {
  1824. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1825. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1826. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1827. return ExprError();
  1828. }
  1829. const auto *FuncType =
  1830. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1831. if (!FuncType) {
  1832. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1833. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1834. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1835. return ExprError();
  1836. }
  1837. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1838. if (!FT->getNumParams()) {
  1839. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1840. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1841. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1842. return ExprError();
  1843. }
  1844. QualType PT = FT->getParamType(0);
  1845. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1846. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1847. !PT->getPointeeType().isConstQualified()) {
  1848. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1849. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1850. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1851. return ExprError();
  1852. }
  1853. }
  1854. TheCall->setType(Context.IntTy);
  1855. break;
  1856. }
  1857. case Builtin::BI__builtin_expect_with_probability: {
  1858. // We first want to ensure we are called with 3 arguments
  1859. if (checkArgCount(*this, TheCall, 3))
  1860. return ExprError();
  1861. // then check probability is constant float in range [0.0, 1.0]
  1862. const Expr *ProbArg = TheCall->getArg(2);
  1863. SmallVector<PartialDiagnosticAt, 8> Notes;
  1864. Expr::EvalResult Eval;
  1865. Eval.Diag = &Notes;
  1866. if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
  1867. !Eval.Val.isFloat()) {
  1868. Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
  1869. << ProbArg->getSourceRange();
  1870. for (const PartialDiagnosticAt &PDiag : Notes)
  1871. Diag(PDiag.first, PDiag.second);
  1872. return ExprError();
  1873. }
  1874. llvm::APFloat Probability = Eval.Val.getFloat();
  1875. bool LoseInfo = false;
  1876. Probability.convert(llvm::APFloat::IEEEdouble(),
  1877. llvm::RoundingMode::Dynamic, &LoseInfo);
  1878. if (!(Probability >= llvm::APFloat(0.0) &&
  1879. Probability <= llvm::APFloat(1.0))) {
  1880. Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
  1881. << ProbArg->getSourceRange();
  1882. return ExprError();
  1883. }
  1884. break;
  1885. }
  1886. case Builtin::BI__builtin_preserve_access_index:
  1887. if (SemaBuiltinPreserveAI(*this, TheCall))
  1888. return ExprError();
  1889. break;
  1890. case Builtin::BI__builtin_call_with_static_chain:
  1891. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1892. return ExprError();
  1893. break;
  1894. case Builtin::BI__exception_code:
  1895. case Builtin::BI_exception_code:
  1896. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1897. diag::err_seh___except_block))
  1898. return ExprError();
  1899. break;
  1900. case Builtin::BI__exception_info:
  1901. case Builtin::BI_exception_info:
  1902. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1903. diag::err_seh___except_filter))
  1904. return ExprError();
  1905. break;
  1906. case Builtin::BI__GetExceptionInfo:
  1907. if (checkArgCount(*this, TheCall, 1))
  1908. return ExprError();
  1909. if (CheckCXXThrowOperand(
  1910. TheCall->getBeginLoc(),
  1911. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1912. TheCall))
  1913. return ExprError();
  1914. TheCall->setType(Context.VoidPtrTy);
  1915. break;
  1916. // OpenCL v2.0, s6.13.16 - Pipe functions
  1917. case Builtin::BIread_pipe:
  1918. case Builtin::BIwrite_pipe:
  1919. // Since those two functions are declared with var args, we need a semantic
  1920. // check for the argument.
  1921. if (SemaBuiltinRWPipe(*this, TheCall))
  1922. return ExprError();
  1923. break;
  1924. case Builtin::BIreserve_read_pipe:
  1925. case Builtin::BIreserve_write_pipe:
  1926. case Builtin::BIwork_group_reserve_read_pipe:
  1927. case Builtin::BIwork_group_reserve_write_pipe:
  1928. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1929. return ExprError();
  1930. break;
  1931. case Builtin::BIsub_group_reserve_read_pipe:
  1932. case Builtin::BIsub_group_reserve_write_pipe:
  1933. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1934. SemaBuiltinReserveRWPipe(*this, TheCall))
  1935. return ExprError();
  1936. break;
  1937. case Builtin::BIcommit_read_pipe:
  1938. case Builtin::BIcommit_write_pipe:
  1939. case Builtin::BIwork_group_commit_read_pipe:
  1940. case Builtin::BIwork_group_commit_write_pipe:
  1941. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1942. return ExprError();
  1943. break;
  1944. case Builtin::BIsub_group_commit_read_pipe:
  1945. case Builtin::BIsub_group_commit_write_pipe:
  1946. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1947. SemaBuiltinCommitRWPipe(*this, TheCall))
  1948. return ExprError();
  1949. break;
  1950. case Builtin::BIget_pipe_num_packets:
  1951. case Builtin::BIget_pipe_max_packets:
  1952. if (SemaBuiltinPipePackets(*this, TheCall))
  1953. return ExprError();
  1954. break;
  1955. case Builtin::BIto_global:
  1956. case Builtin::BIto_local:
  1957. case Builtin::BIto_private:
  1958. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1959. return ExprError();
  1960. break;
  1961. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1962. case Builtin::BIenqueue_kernel:
  1963. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1964. return ExprError();
  1965. break;
  1966. case Builtin::BIget_kernel_work_group_size:
  1967. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1968. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1969. return ExprError();
  1970. break;
  1971. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1972. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1973. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1974. return ExprError();
  1975. break;
  1976. case Builtin::BI__builtin_os_log_format:
  1977. Cleanup.setExprNeedsCleanups(true);
  1978. LLVM_FALLTHROUGH;
  1979. case Builtin::BI__builtin_os_log_format_buffer_size:
  1980. if (SemaBuiltinOSLogFormat(TheCall))
  1981. return ExprError();
  1982. break;
  1983. case Builtin::BI__builtin_frame_address:
  1984. case Builtin::BI__builtin_return_address: {
  1985. if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
  1986. return ExprError();
  1987. // -Wframe-address warning if non-zero passed to builtin
  1988. // return/frame address.
  1989. Expr::EvalResult Result;
  1990. if (!TheCall->getArg(0)->isValueDependent() &&
  1991. TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
  1992. Result.Val.getInt() != 0)
  1993. Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
  1994. << ((BuiltinID == Builtin::BI__builtin_return_address)
  1995. ? "__builtin_return_address"
  1996. : "__builtin_frame_address")
  1997. << TheCall->getSourceRange();
  1998. break;
  1999. }
  2000. // __builtin_elementwise_abs restricts the element type to signed integers or
  2001. // floating point types only.
  2002. case Builtin::BI__builtin_elementwise_abs: {
  2003. if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
  2004. return ExprError();
  2005. QualType ArgTy = TheCall->getArg(0)->getType();
  2006. QualType EltTy = ArgTy;
  2007. if (auto *VecTy = EltTy->getAs<VectorType>())
  2008. EltTy = VecTy->getElementType();
  2009. if (EltTy->isUnsignedIntegerType()) {
  2010. Diag(TheCall->getArg(0)->getBeginLoc(),
  2011. diag::err_builtin_invalid_arg_type)
  2012. << 1 << /* signed integer or float ty*/ 3 << ArgTy;
  2013. return ExprError();
  2014. }
  2015. break;
  2016. }
  2017. // These builtins restrict the element type to floating point
  2018. // types only.
  2019. case Builtin::BI__builtin_elementwise_ceil:
  2020. case Builtin::BI__builtin_elementwise_floor:
  2021. case Builtin::BI__builtin_elementwise_roundeven:
  2022. case Builtin::BI__builtin_elementwise_trunc: {
  2023. if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
  2024. return ExprError();
  2025. QualType ArgTy = TheCall->getArg(0)->getType();
  2026. QualType EltTy = ArgTy;
  2027. if (auto *VecTy = EltTy->getAs<VectorType>())
  2028. EltTy = VecTy->getElementType();
  2029. if (!EltTy->isFloatingType()) {
  2030. Diag(TheCall->getArg(0)->getBeginLoc(),
  2031. diag::err_builtin_invalid_arg_type)
  2032. << 1 << /* float ty*/ 5 << ArgTy;
  2033. return ExprError();
  2034. }
  2035. break;
  2036. }
  2037. case Builtin::BI__builtin_elementwise_min:
  2038. case Builtin::BI__builtin_elementwise_max:
  2039. if (SemaBuiltinElementwiseMath(TheCall))
  2040. return ExprError();
  2041. break;
  2042. case Builtin::BI__builtin_reduce_max:
  2043. case Builtin::BI__builtin_reduce_min: {
  2044. if (PrepareBuiltinReduceMathOneArgCall(TheCall))
  2045. return ExprError();
  2046. const Expr *Arg = TheCall->getArg(0);
  2047. const auto *TyA = Arg->getType()->getAs<VectorType>();
  2048. if (!TyA) {
  2049. Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  2050. << 1 << /* vector ty*/ 4 << Arg->getType();
  2051. return ExprError();
  2052. }
  2053. TheCall->setType(TyA->getElementType());
  2054. break;
  2055. }
  2056. // These builtins support vectors of integers only.
  2057. case Builtin::BI__builtin_reduce_xor:
  2058. case Builtin::BI__builtin_reduce_or:
  2059. case Builtin::BI__builtin_reduce_and: {
  2060. if (PrepareBuiltinReduceMathOneArgCall(TheCall))
  2061. return ExprError();
  2062. const Expr *Arg = TheCall->getArg(0);
  2063. const auto *TyA = Arg->getType()->getAs<VectorType>();
  2064. if (!TyA || !TyA->getElementType()->isIntegerType()) {
  2065. Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  2066. << 1 << /* vector of integers */ 6 << Arg->getType();
  2067. return ExprError();
  2068. }
  2069. TheCall->setType(TyA->getElementType());
  2070. break;
  2071. }
  2072. case Builtin::BI__builtin_matrix_transpose:
  2073. return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
  2074. case Builtin::BI__builtin_matrix_column_major_load:
  2075. return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
  2076. case Builtin::BI__builtin_matrix_column_major_store:
  2077. return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
  2078. case Builtin::BI__builtin_get_device_side_mangled_name: {
  2079. auto Check = [](CallExpr *TheCall) {
  2080. if (TheCall->getNumArgs() != 1)
  2081. return false;
  2082. auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
  2083. if (!DRE)
  2084. return false;
  2085. auto *D = DRE->getDecl();
  2086. if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
  2087. return false;
  2088. return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
  2089. D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
  2090. };
  2091. if (!Check(TheCall)) {
  2092. Diag(TheCall->getBeginLoc(),
  2093. diag::err_hip_invalid_args_builtin_mangled_name);
  2094. return ExprError();
  2095. }
  2096. }
  2097. }
  2098. // Since the target specific builtins for each arch overlap, only check those
  2099. // of the arch we are compiling for.
  2100. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  2101. if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
  2102. assert(Context.getAuxTargetInfo() &&
  2103. "Aux Target Builtin, but not an aux target?");
  2104. if (CheckTSBuiltinFunctionCall(
  2105. *Context.getAuxTargetInfo(),
  2106. Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
  2107. return ExprError();
  2108. } else {
  2109. if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
  2110. TheCall))
  2111. return ExprError();
  2112. }
  2113. }
  2114. return TheCallResult;
  2115. }
  2116. // Get the valid immediate range for the specified NEON type code.
  2117. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  2118. NeonTypeFlags Type(t);
  2119. int IsQuad = ForceQuad ? true : Type.isQuad();
  2120. switch (Type.getEltType()) {
  2121. case NeonTypeFlags::Int8:
  2122. case NeonTypeFlags::Poly8:
  2123. return shift ? 7 : (8 << IsQuad) - 1;
  2124. case NeonTypeFlags::Int16:
  2125. case NeonTypeFlags::Poly16:
  2126. return shift ? 15 : (4 << IsQuad) - 1;
  2127. case NeonTypeFlags::Int32:
  2128. return shift ? 31 : (2 << IsQuad) - 1;
  2129. case NeonTypeFlags::Int64:
  2130. case NeonTypeFlags::Poly64:
  2131. return shift ? 63 : (1 << IsQuad) - 1;
  2132. case NeonTypeFlags::Poly128:
  2133. return shift ? 127 : (1 << IsQuad) - 1;
  2134. case NeonTypeFlags::Float16:
  2135. assert(!shift && "cannot shift float types!");
  2136. return (4 << IsQuad) - 1;
  2137. case NeonTypeFlags::Float32:
  2138. assert(!shift && "cannot shift float types!");
  2139. return (2 << IsQuad) - 1;
  2140. case NeonTypeFlags::Float64:
  2141. assert(!shift && "cannot shift float types!");
  2142. return (1 << IsQuad) - 1;
  2143. case NeonTypeFlags::BFloat16:
  2144. assert(!shift && "cannot shift float types!");
  2145. return (4 << IsQuad) - 1;
  2146. }
  2147. llvm_unreachable("Invalid NeonTypeFlag!");
  2148. }
  2149. /// getNeonEltType - Return the QualType corresponding to the elements of
  2150. /// the vector type specified by the NeonTypeFlags. This is used to check
  2151. /// the pointer arguments for Neon load/store intrinsics.
  2152. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  2153. bool IsPolyUnsigned, bool IsInt64Long) {
  2154. switch (Flags.getEltType()) {
  2155. case NeonTypeFlags::Int8:
  2156. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  2157. case NeonTypeFlags::Int16:
  2158. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  2159. case NeonTypeFlags::Int32:
  2160. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  2161. case NeonTypeFlags::Int64:
  2162. if (IsInt64Long)
  2163. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  2164. else
  2165. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  2166. : Context.LongLongTy;
  2167. case NeonTypeFlags::Poly8:
  2168. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  2169. case NeonTypeFlags::Poly16:
  2170. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  2171. case NeonTypeFlags::Poly64:
  2172. if (IsInt64Long)
  2173. return Context.UnsignedLongTy;
  2174. else
  2175. return Context.UnsignedLongLongTy;
  2176. case NeonTypeFlags::Poly128:
  2177. break;
  2178. case NeonTypeFlags::Float16:
  2179. return Context.HalfTy;
  2180. case NeonTypeFlags::Float32:
  2181. return Context.FloatTy;
  2182. case NeonTypeFlags::Float64:
  2183. return Context.DoubleTy;
  2184. case NeonTypeFlags::BFloat16:
  2185. return Context.BFloat16Ty;
  2186. }
  2187. llvm_unreachable("Invalid NeonTypeFlag!");
  2188. }
  2189. bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2190. // Range check SVE intrinsics that take immediate values.
  2191. SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
  2192. switch (BuiltinID) {
  2193. default:
  2194. return false;
  2195. #define GET_SVE_IMMEDIATE_CHECK
  2196. #include "clang/Basic/arm_sve_sema_rangechecks.inc"
  2197. #undef GET_SVE_IMMEDIATE_CHECK
  2198. }
  2199. // Perform all the immediate checks for this builtin call.
  2200. bool HasError = false;
  2201. for (auto &I : ImmChecks) {
  2202. int ArgNum, CheckTy, ElementSizeInBits;
  2203. std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
  2204. typedef bool(*OptionSetCheckFnTy)(int64_t Value);
  2205. // Function that checks whether the operand (ArgNum) is an immediate
  2206. // that is one of the predefined values.
  2207. auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
  2208. int ErrDiag) -> bool {
  2209. // We can't check the value of a dependent argument.
  2210. Expr *Arg = TheCall->getArg(ArgNum);
  2211. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2212. return false;
  2213. // Check constant-ness first.
  2214. llvm::APSInt Imm;
  2215. if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
  2216. return true;
  2217. if (!CheckImm(Imm.getSExtValue()))
  2218. return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
  2219. return false;
  2220. };
  2221. switch ((SVETypeFlags::ImmCheckType)CheckTy) {
  2222. case SVETypeFlags::ImmCheck0_31:
  2223. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
  2224. HasError = true;
  2225. break;
  2226. case SVETypeFlags::ImmCheck0_13:
  2227. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
  2228. HasError = true;
  2229. break;
  2230. case SVETypeFlags::ImmCheck1_16:
  2231. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
  2232. HasError = true;
  2233. break;
  2234. case SVETypeFlags::ImmCheck0_7:
  2235. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
  2236. HasError = true;
  2237. break;
  2238. case SVETypeFlags::ImmCheckExtract:
  2239. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2240. (2048 / ElementSizeInBits) - 1))
  2241. HasError = true;
  2242. break;
  2243. case SVETypeFlags::ImmCheckShiftRight:
  2244. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
  2245. HasError = true;
  2246. break;
  2247. case SVETypeFlags::ImmCheckShiftRightNarrow:
  2248. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
  2249. ElementSizeInBits / 2))
  2250. HasError = true;
  2251. break;
  2252. case SVETypeFlags::ImmCheckShiftLeft:
  2253. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2254. ElementSizeInBits - 1))
  2255. HasError = true;
  2256. break;
  2257. case SVETypeFlags::ImmCheckLaneIndex:
  2258. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2259. (128 / (1 * ElementSizeInBits)) - 1))
  2260. HasError = true;
  2261. break;
  2262. case SVETypeFlags::ImmCheckLaneIndexCompRotate:
  2263. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2264. (128 / (2 * ElementSizeInBits)) - 1))
  2265. HasError = true;
  2266. break;
  2267. case SVETypeFlags::ImmCheckLaneIndexDot:
  2268. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2269. (128 / (4 * ElementSizeInBits)) - 1))
  2270. HasError = true;
  2271. break;
  2272. case SVETypeFlags::ImmCheckComplexRot90_270:
  2273. if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
  2274. diag::err_rotation_argument_to_cadd))
  2275. HasError = true;
  2276. break;
  2277. case SVETypeFlags::ImmCheckComplexRotAll90:
  2278. if (CheckImmediateInSet(
  2279. [](int64_t V) {
  2280. return V == 0 || V == 90 || V == 180 || V == 270;
  2281. },
  2282. diag::err_rotation_argument_to_cmla))
  2283. HasError = true;
  2284. break;
  2285. case SVETypeFlags::ImmCheck0_1:
  2286. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
  2287. HasError = true;
  2288. break;
  2289. case SVETypeFlags::ImmCheck0_2:
  2290. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
  2291. HasError = true;
  2292. break;
  2293. case SVETypeFlags::ImmCheck0_3:
  2294. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
  2295. HasError = true;
  2296. break;
  2297. }
  2298. }
  2299. return HasError;
  2300. }
  2301. bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
  2302. unsigned BuiltinID, CallExpr *TheCall) {
  2303. llvm::APSInt Result;
  2304. uint64_t mask = 0;
  2305. unsigned TV = 0;
  2306. int PtrArgNum = -1;
  2307. bool HasConstPtr = false;
  2308. switch (BuiltinID) {
  2309. #define GET_NEON_OVERLOAD_CHECK
  2310. #include "clang/Basic/arm_neon.inc"
  2311. #include "clang/Basic/arm_fp16.inc"
  2312. #undef GET_NEON_OVERLOAD_CHECK
  2313. }
  2314. // For NEON intrinsics which are overloaded on vector element type, validate
  2315. // the immediate which specifies which variant to emit.
  2316. unsigned ImmArg = TheCall->getNumArgs()-1;
  2317. if (mask) {
  2318. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  2319. return true;
  2320. TV = Result.getLimitedValue(64);
  2321. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  2322. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  2323. << TheCall->getArg(ImmArg)->getSourceRange();
  2324. }
  2325. if (PtrArgNum >= 0) {
  2326. // Check that pointer arguments have the specified type.
  2327. Expr *Arg = TheCall->getArg(PtrArgNum);
  2328. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  2329. Arg = ICE->getSubExpr();
  2330. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  2331. QualType RHSTy = RHS.get()->getType();
  2332. llvm::Triple::ArchType Arch = TI.getTriple().getArch();
  2333. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  2334. Arch == llvm::Triple::aarch64_32 ||
  2335. Arch == llvm::Triple::aarch64_be;
  2336. bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
  2337. QualType EltTy =
  2338. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  2339. if (HasConstPtr)
  2340. EltTy = EltTy.withConst();
  2341. QualType LHSTy = Context.getPointerType(EltTy);
  2342. AssignConvertType ConvTy;
  2343. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  2344. if (RHS.isInvalid())
  2345. return true;
  2346. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  2347. RHS.get(), AA_Assigning))
  2348. return true;
  2349. }
  2350. // For NEON intrinsics which take an immediate value as part of the
  2351. // instruction, range check them here.
  2352. unsigned i = 0, l = 0, u = 0;
  2353. switch (BuiltinID) {
  2354. default:
  2355. return false;
  2356. #define GET_NEON_IMMEDIATE_CHECK
  2357. #include "clang/Basic/arm_neon.inc"
  2358. #include "clang/Basic/arm_fp16.inc"
  2359. #undef GET_NEON_IMMEDIATE_CHECK
  2360. }
  2361. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  2362. }
  2363. bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2364. switch (BuiltinID) {
  2365. default:
  2366. return false;
  2367. #include "clang/Basic/arm_mve_builtin_sema.inc"
  2368. }
  2369. }
  2370. bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  2371. CallExpr *TheCall) {
  2372. bool Err = false;
  2373. switch (BuiltinID) {
  2374. default:
  2375. return false;
  2376. #include "clang/Basic/arm_cde_builtin_sema.inc"
  2377. }
  2378. if (Err)
  2379. return true;
  2380. return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
  2381. }
  2382. bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
  2383. const Expr *CoprocArg, bool WantCDE) {
  2384. if (isConstantEvaluated())
  2385. return false;
  2386. // We can't check the value of a dependent argument.
  2387. if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
  2388. return false;
  2389. llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
  2390. int64_t CoprocNo = CoprocNoAP.getExtValue();
  2391. assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
  2392. uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
  2393. bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
  2394. if (IsCDECoproc != WantCDE)
  2395. return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
  2396. << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
  2397. return false;
  2398. }
  2399. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  2400. unsigned MaxWidth) {
  2401. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  2402. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  2403. BuiltinID == ARM::BI__builtin_arm_strex ||
  2404. BuiltinID == ARM::BI__builtin_arm_stlex ||
  2405. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  2406. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  2407. BuiltinID == AArch64::BI__builtin_arm_strex ||
  2408. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  2409. "unexpected ARM builtin");
  2410. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  2411. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  2412. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  2413. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  2414. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2415. // Ensure that we have the proper number of arguments.
  2416. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  2417. return true;
  2418. // Inspect the pointer argument of the atomic builtin. This should always be
  2419. // a pointer type, whose element is an integral scalar or pointer type.
  2420. // Because it is a pointer type, we don't have to worry about any implicit
  2421. // casts here.
  2422. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  2423. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  2424. if (PointerArgRes.isInvalid())
  2425. return true;
  2426. PointerArg = PointerArgRes.get();
  2427. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  2428. if (!pointerType) {
  2429. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  2430. << PointerArg->getType() << PointerArg->getSourceRange();
  2431. return true;
  2432. }
  2433. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  2434. // task is to insert the appropriate casts into the AST. First work out just
  2435. // what the appropriate type is.
  2436. QualType ValType = pointerType->getPointeeType();
  2437. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  2438. if (IsLdrex)
  2439. AddrType.addConst();
  2440. // Issue a warning if the cast is dodgy.
  2441. CastKind CastNeeded = CK_NoOp;
  2442. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  2443. CastNeeded = CK_BitCast;
  2444. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  2445. << PointerArg->getType() << Context.getPointerType(AddrType)
  2446. << AA_Passing << PointerArg->getSourceRange();
  2447. }
  2448. // Finally, do the cast and replace the argument with the corrected version.
  2449. AddrType = Context.getPointerType(AddrType);
  2450. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  2451. if (PointerArgRes.isInvalid())
  2452. return true;
  2453. PointerArg = PointerArgRes.get();
  2454. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  2455. // In general, we allow ints, floats and pointers to be loaded and stored.
  2456. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  2457. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  2458. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  2459. << PointerArg->getType() << PointerArg->getSourceRange();
  2460. return true;
  2461. }
  2462. // But ARM doesn't have instructions to deal with 128-bit versions.
  2463. if (Context.getTypeSize(ValType) > MaxWidth) {
  2464. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  2465. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  2466. << PointerArg->getType() << PointerArg->getSourceRange();
  2467. return true;
  2468. }
  2469. switch (ValType.getObjCLifetime()) {
  2470. case Qualifiers::OCL_None:
  2471. case Qualifiers::OCL_ExplicitNone:
  2472. // okay
  2473. break;
  2474. case Qualifiers::OCL_Weak:
  2475. case Qualifiers::OCL_Strong:
  2476. case Qualifiers::OCL_Autoreleasing:
  2477. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  2478. << ValType << PointerArg->getSourceRange();
  2479. return true;
  2480. }
  2481. if (IsLdrex) {
  2482. TheCall->setType(ValType);
  2483. return false;
  2484. }
  2485. // Initialize the argument to be stored.
  2486. ExprResult ValArg = TheCall->getArg(0);
  2487. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  2488. Context, ValType, /*consume*/ false);
  2489. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  2490. if (ValArg.isInvalid())
  2491. return true;
  2492. TheCall->setArg(0, ValArg.get());
  2493. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  2494. // but the custom checker bypasses all default analysis.
  2495. TheCall->setType(Context.IntTy);
  2496. return false;
  2497. }
  2498. bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  2499. CallExpr *TheCall) {
  2500. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  2501. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  2502. BuiltinID == ARM::BI__builtin_arm_strex ||
  2503. BuiltinID == ARM::BI__builtin_arm_stlex) {
  2504. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  2505. }
  2506. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  2507. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  2508. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  2509. }
  2510. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  2511. BuiltinID == ARM::BI__builtin_arm_wsr64)
  2512. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  2513. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  2514. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  2515. BuiltinID == ARM::BI__builtin_arm_wsr ||
  2516. BuiltinID == ARM::BI__builtin_arm_wsrp)
  2517. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  2518. if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
  2519. return true;
  2520. if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
  2521. return true;
  2522. if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
  2523. return true;
  2524. // For intrinsics which take an immediate value as part of the instruction,
  2525. // range check them here.
  2526. // FIXME: VFP Intrinsics should error if VFP not present.
  2527. switch (BuiltinID) {
  2528. default: return false;
  2529. case ARM::BI__builtin_arm_ssat:
  2530. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  2531. case ARM::BI__builtin_arm_usat:
  2532. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  2533. case ARM::BI__builtin_arm_ssat16:
  2534. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  2535. case ARM::BI__builtin_arm_usat16:
  2536. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  2537. case ARM::BI__builtin_arm_vcvtr_f:
  2538. case ARM::BI__builtin_arm_vcvtr_d:
  2539. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  2540. case ARM::BI__builtin_arm_dmb:
  2541. case ARM::BI__builtin_arm_dsb:
  2542. case ARM::BI__builtin_arm_isb:
  2543. case ARM::BI__builtin_arm_dbg:
  2544. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  2545. case ARM::BI__builtin_arm_cdp:
  2546. case ARM::BI__builtin_arm_cdp2:
  2547. case ARM::BI__builtin_arm_mcr:
  2548. case ARM::BI__builtin_arm_mcr2:
  2549. case ARM::BI__builtin_arm_mrc:
  2550. case ARM::BI__builtin_arm_mrc2:
  2551. case ARM::BI__builtin_arm_mcrr:
  2552. case ARM::BI__builtin_arm_mcrr2:
  2553. case ARM::BI__builtin_arm_mrrc:
  2554. case ARM::BI__builtin_arm_mrrc2:
  2555. case ARM::BI__builtin_arm_ldc:
  2556. case ARM::BI__builtin_arm_ldcl:
  2557. case ARM::BI__builtin_arm_ldc2:
  2558. case ARM::BI__builtin_arm_ldc2l:
  2559. case ARM::BI__builtin_arm_stc:
  2560. case ARM::BI__builtin_arm_stcl:
  2561. case ARM::BI__builtin_arm_stc2:
  2562. case ARM::BI__builtin_arm_stc2l:
  2563. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
  2564. CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
  2565. /*WantCDE*/ false);
  2566. }
  2567. }
  2568. bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
  2569. unsigned BuiltinID,
  2570. CallExpr *TheCall) {
  2571. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  2572. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  2573. BuiltinID == AArch64::BI__builtin_arm_strex ||
  2574. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  2575. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  2576. }
  2577. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  2578. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  2579. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  2580. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  2581. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  2582. }
  2583. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  2584. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  2585. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  2586. // Memory Tagging Extensions (MTE) Intrinsics
  2587. if (BuiltinID == AArch64::BI__builtin_arm_irg ||
  2588. BuiltinID == AArch64::BI__builtin_arm_addg ||
  2589. BuiltinID == AArch64::BI__builtin_arm_gmi ||
  2590. BuiltinID == AArch64::BI__builtin_arm_ldg ||
  2591. BuiltinID == AArch64::BI__builtin_arm_stg ||
  2592. BuiltinID == AArch64::BI__builtin_arm_subp) {
  2593. return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
  2594. }
  2595. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  2596. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  2597. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  2598. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  2599. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  2600. // Only check the valid encoding range. Any constant in this range would be
  2601. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  2602. // an exception for incorrect registers. This matches MSVC behavior.
  2603. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  2604. BuiltinID == AArch64::BI_WriteStatusReg)
  2605. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  2606. if (BuiltinID == AArch64::BI__getReg)
  2607. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  2608. if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
  2609. return true;
  2610. if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
  2611. return true;
  2612. // For intrinsics which take an immediate value as part of the instruction,
  2613. // range check them here.
  2614. unsigned i = 0, l = 0, u = 0;
  2615. switch (BuiltinID) {
  2616. default: return false;
  2617. case AArch64::BI__builtin_arm_dmb:
  2618. case AArch64::BI__builtin_arm_dsb:
  2619. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  2620. case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
  2621. }
  2622. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  2623. }
  2624. static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
  2625. if (Arg->getType()->getAsPlaceholderType())
  2626. return false;
  2627. // The first argument needs to be a record field access.
  2628. // If it is an array element access, we delay decision
  2629. // to BPF backend to check whether the access is a
  2630. // field access or not.
  2631. return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
  2632. isa<MemberExpr>(Arg->IgnoreParens()) ||
  2633. isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
  2634. }
  2635. static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
  2636. QualType VectorTy, QualType EltTy) {
  2637. QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
  2638. if (!Context.hasSameType(VectorEltTy, EltTy)) {
  2639. S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
  2640. << Call->getSourceRange() << VectorEltTy << EltTy;
  2641. return false;
  2642. }
  2643. return true;
  2644. }
  2645. static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
  2646. QualType ArgType = Arg->getType();
  2647. if (ArgType->getAsPlaceholderType())
  2648. return false;
  2649. // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
  2650. // format:
  2651. // 1. __builtin_preserve_type_info(*(<type> *)0, flag);
  2652. // 2. <type> var;
  2653. // __builtin_preserve_type_info(var, flag);
  2654. if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
  2655. !isa<UnaryOperator>(Arg->IgnoreParens()))
  2656. return false;
  2657. // Typedef type.
  2658. if (ArgType->getAs<TypedefType>())
  2659. return true;
  2660. // Record type or Enum type.
  2661. const Type *Ty = ArgType->getUnqualifiedDesugaredType();
  2662. if (const auto *RT = Ty->getAs<RecordType>()) {
  2663. if (!RT->getDecl()->getDeclName().isEmpty())
  2664. return true;
  2665. } else if (const auto *ET = Ty->getAs<EnumType>()) {
  2666. if (!ET->getDecl()->getDeclName().isEmpty())
  2667. return true;
  2668. }
  2669. return false;
  2670. }
  2671. static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
  2672. QualType ArgType = Arg->getType();
  2673. if (ArgType->getAsPlaceholderType())
  2674. return false;
  2675. // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
  2676. // format:
  2677. // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
  2678. // flag);
  2679. const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
  2680. if (!UO)
  2681. return false;
  2682. const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
  2683. if (!CE)
  2684. return false;
  2685. if (CE->getCastKind() != CK_IntegralToPointer &&
  2686. CE->getCastKind() != CK_NullToPointer)
  2687. return false;
  2688. // The integer must be from an EnumConstantDecl.
  2689. const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
  2690. if (!DR)
  2691. return false;
  2692. const EnumConstantDecl *Enumerator =
  2693. dyn_cast<EnumConstantDecl>(DR->getDecl());
  2694. if (!Enumerator)
  2695. return false;
  2696. // The type must be EnumType.
  2697. const Type *Ty = ArgType->getUnqualifiedDesugaredType();
  2698. const auto *ET = Ty->getAs<EnumType>();
  2699. if (!ET)
  2700. return false;
  2701. // The enum value must be supported.
  2702. return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
  2703. }
  2704. bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
  2705. CallExpr *TheCall) {
  2706. assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
  2707. BuiltinID == BPF::BI__builtin_btf_type_id ||
  2708. BuiltinID == BPF::BI__builtin_preserve_type_info ||
  2709. BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
  2710. "unexpected BPF builtin");
  2711. if (checkArgCount(*this, TheCall, 2))
  2712. return true;
  2713. // The second argument needs to be a constant int
  2714. Expr *Arg = TheCall->getArg(1);
  2715. Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
  2716. diag::kind kind;
  2717. if (!Value) {
  2718. if (BuiltinID == BPF::BI__builtin_preserve_field_info)
  2719. kind = diag::err_preserve_field_info_not_const;
  2720. else if (BuiltinID == BPF::BI__builtin_btf_type_id)
  2721. kind = diag::err_btf_type_id_not_const;
  2722. else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
  2723. kind = diag::err_preserve_type_info_not_const;
  2724. else
  2725. kind = diag::err_preserve_enum_value_not_const;
  2726. Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
  2727. return true;
  2728. }
  2729. // The first argument
  2730. Arg = TheCall->getArg(0);
  2731. bool InvalidArg = false;
  2732. bool ReturnUnsignedInt = true;
  2733. if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
  2734. if (!isValidBPFPreserveFieldInfoArg(Arg)) {
  2735. InvalidArg = true;
  2736. kind = diag::err_preserve_field_info_not_field;
  2737. }
  2738. } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
  2739. if (!isValidBPFPreserveTypeInfoArg(Arg)) {
  2740. InvalidArg = true;
  2741. kind = diag::err_preserve_type_info_invalid;
  2742. }
  2743. } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
  2744. if (!isValidBPFPreserveEnumValueArg(Arg)) {
  2745. InvalidArg = true;
  2746. kind = diag::err_preserve_enum_value_invalid;
  2747. }
  2748. ReturnUnsignedInt = false;
  2749. } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
  2750. ReturnUnsignedInt = false;
  2751. }
  2752. if (InvalidArg) {
  2753. Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
  2754. return true;
  2755. }
  2756. if (ReturnUnsignedInt)
  2757. TheCall->setType(Context.UnsignedIntTy);
  2758. else
  2759. TheCall->setType(Context.UnsignedLongTy);
  2760. return false;
  2761. }
  2762. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  2763. struct ArgInfo {
  2764. uint8_t OpNum;
  2765. bool IsSigned;
  2766. uint8_t BitWidth;
  2767. uint8_t Align;
  2768. };
  2769. struct BuiltinInfo {
  2770. unsigned BuiltinID;
  2771. ArgInfo Infos[2];
  2772. };
  2773. static BuiltinInfo Infos[] = {
  2774. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  2775. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  2776. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  2777. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
  2778. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  2779. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  2780. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  2781. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  2782. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  2783. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  2784. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  2785. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  2786. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  2787. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  2788. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  2789. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  2790. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  2791. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  2792. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  2793. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  2794. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  2795. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  2796. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  2797. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  2798. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  2799. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  2800. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  2801. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  2802. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  2803. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  2804. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  2805. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  2806. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  2807. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  2808. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  2809. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  2810. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  2811. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  2812. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  2813. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  2814. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  2815. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  2816. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  2817. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  2818. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  2819. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  2820. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  2821. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  2822. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  2823. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  2824. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  2825. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  2826. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  2827. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  2828. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  2829. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  2830. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  2831. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  2832. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  2833. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  2834. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  2835. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  2836. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  2837. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  2838. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  2839. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  2840. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  2841. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  2842. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  2843. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  2844. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  2845. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  2846. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  2847. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  2848. {{ 1, false, 6, 0 }} },
  2849. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  2850. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  2851. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  2852. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  2853. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  2854. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  2855. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  2856. {{ 1, false, 5, 0 }} },
  2857. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  2858. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  2859. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  2860. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  2861. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  2862. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  2863. { 2, false, 5, 0 }} },
  2864. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  2865. { 2, false, 6, 0 }} },
  2866. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  2867. { 3, false, 5, 0 }} },
  2868. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  2869. { 3, false, 6, 0 }} },
  2870. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  2871. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  2872. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  2873. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  2874. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  2875. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  2876. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  2877. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  2878. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  2879. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  2880. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  2881. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  2882. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  2883. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  2884. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  2885. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  2886. {{ 2, false, 4, 0 },
  2887. { 3, false, 5, 0 }} },
  2888. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  2889. {{ 2, false, 4, 0 },
  2890. { 3, false, 5, 0 }} },
  2891. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  2892. {{ 2, false, 4, 0 },
  2893. { 3, false, 5, 0 }} },
  2894. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  2895. {{ 2, false, 4, 0 },
  2896. { 3, false, 5, 0 }} },
  2897. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  2898. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  2899. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  2900. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  2901. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  2902. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  2903. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  2904. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  2905. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  2906. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  2907. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  2908. { 2, false, 5, 0 }} },
  2909. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  2910. { 2, false, 6, 0 }} },
  2911. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  2912. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  2913. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  2914. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  2915. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  2916. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  2917. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  2918. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  2919. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  2920. {{ 1, false, 4, 0 }} },
  2921. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  2922. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  2923. {{ 1, false, 4, 0 }} },
  2924. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  2925. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  2926. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  2927. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  2928. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  2929. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  2930. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  2931. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  2932. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  2933. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  2934. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  2935. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  2936. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  2937. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  2938. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  2939. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  2940. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  2941. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  2942. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  2943. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  2944. {{ 3, false, 1, 0 }} },
  2945. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  2946. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  2947. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  2948. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  2949. {{ 3, false, 1, 0 }} },
  2950. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  2951. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  2952. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  2953. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  2954. {{ 3, false, 1, 0 }} },
  2955. };
  2956. // Use a dynamically initialized static to sort the table exactly once on
  2957. // first run.
  2958. static const bool SortOnce =
  2959. (llvm::sort(Infos,
  2960. [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
  2961. return LHS.BuiltinID < RHS.BuiltinID;
  2962. }),
  2963. true);
  2964. (void)SortOnce;
  2965. const BuiltinInfo *F = llvm::partition_point(
  2966. Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
  2967. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  2968. return false;
  2969. bool Error = false;
  2970. for (const ArgInfo &A : F->Infos) {
  2971. // Ignore empty ArgInfo elements.
  2972. if (A.BitWidth == 0)
  2973. continue;
  2974. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  2975. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  2976. if (!A.Align) {
  2977. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2978. } else {
  2979. unsigned M = 1 << A.Align;
  2980. Min *= M;
  2981. Max *= M;
  2982. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2983. Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2984. }
  2985. }
  2986. return Error;
  2987. }
  2988. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2989. CallExpr *TheCall) {
  2990. return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2991. }
  2992. bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
  2993. unsigned BuiltinID, CallExpr *TheCall) {
  2994. return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
  2995. CheckMipsBuiltinArgument(BuiltinID, TheCall);
  2996. }
  2997. bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
  2998. CallExpr *TheCall) {
  2999. if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
  3000. BuiltinID <= Mips::BI__builtin_mips_lwx) {
  3001. if (!TI.hasFeature("dsp"))
  3002. return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
  3003. }
  3004. if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
  3005. BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
  3006. if (!TI.hasFeature("dspr2"))
  3007. return Diag(TheCall->getBeginLoc(),
  3008. diag::err_mips_builtin_requires_dspr2);
  3009. }
  3010. if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
  3011. BuiltinID <= Mips::BI__builtin_msa_xori_b) {
  3012. if (!TI.hasFeature("msa"))
  3013. return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
  3014. }
  3015. return false;
  3016. }
  3017. // CheckMipsBuiltinArgument - Checks the constant value passed to the
  3018. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  3019. // ordering for DSP is unspecified. MSA is ordered by the data format used
  3020. // by the underlying instruction i.e., df/m, df/n and then by size.
  3021. //
  3022. // FIXME: The size tests here should instead be tablegen'd along with the
  3023. // definitions from include/clang/Basic/BuiltinsMips.def.
  3024. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  3025. // be too.
  3026. bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  3027. unsigned i = 0, l = 0, u = 0, m = 0;
  3028. switch (BuiltinID) {
  3029. default: return false;
  3030. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  3031. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  3032. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  3033. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  3034. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  3035. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  3036. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  3037. // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
  3038. // df/m field.
  3039. // These intrinsics take an unsigned 3 bit immediate.
  3040. case Mips::BI__builtin_msa_bclri_b:
  3041. case Mips::BI__builtin_msa_bnegi_b:
  3042. case Mips::BI__builtin_msa_bseti_b:
  3043. case Mips::BI__builtin_msa_sat_s_b:
  3044. case Mips::BI__builtin_msa_sat_u_b:
  3045. case Mips::BI__builtin_msa_slli_b:
  3046. case Mips::BI__builtin_msa_srai_b:
  3047. case Mips::BI__builtin_msa_srari_b:
  3048. case Mips::BI__builtin_msa_srli_b:
  3049. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  3050. case Mips::BI__builtin_msa_binsli_b:
  3051. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  3052. // These intrinsics take an unsigned 4 bit immediate.
  3053. case Mips::BI__builtin_msa_bclri_h:
  3054. case Mips::BI__builtin_msa_bnegi_h:
  3055. case Mips::BI__builtin_msa_bseti_h:
  3056. case Mips::BI__builtin_msa_sat_s_h:
  3057. case Mips::BI__builtin_msa_sat_u_h:
  3058. case Mips::BI__builtin_msa_slli_h:
  3059. case Mips::BI__builtin_msa_srai_h:
  3060. case Mips::BI__builtin_msa_srari_h:
  3061. case Mips::BI__builtin_msa_srli_h:
  3062. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  3063. case Mips::BI__builtin_msa_binsli_h:
  3064. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  3065. // These intrinsics take an unsigned 5 bit immediate.
  3066. // The first block of intrinsics actually have an unsigned 5 bit field,
  3067. // not a df/n field.
  3068. case Mips::BI__builtin_msa_cfcmsa:
  3069. case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
  3070. case Mips::BI__builtin_msa_clei_u_b:
  3071. case Mips::BI__builtin_msa_clei_u_h:
  3072. case Mips::BI__builtin_msa_clei_u_w:
  3073. case Mips::BI__builtin_msa_clei_u_d:
  3074. case Mips::BI__builtin_msa_clti_u_b:
  3075. case Mips::BI__builtin_msa_clti_u_h:
  3076. case Mips::BI__builtin_msa_clti_u_w:
  3077. case Mips::BI__builtin_msa_clti_u_d:
  3078. case Mips::BI__builtin_msa_maxi_u_b:
  3079. case Mips::BI__builtin_msa_maxi_u_h:
  3080. case Mips::BI__builtin_msa_maxi_u_w:
  3081. case Mips::BI__builtin_msa_maxi_u_d:
  3082. case Mips::BI__builtin_msa_mini_u_b:
  3083. case Mips::BI__builtin_msa_mini_u_h:
  3084. case Mips::BI__builtin_msa_mini_u_w:
  3085. case Mips::BI__builtin_msa_mini_u_d:
  3086. case Mips::BI__builtin_msa_addvi_b:
  3087. case Mips::BI__builtin_msa_addvi_h:
  3088. case Mips::BI__builtin_msa_addvi_w:
  3089. case Mips::BI__builtin_msa_addvi_d:
  3090. case Mips::BI__builtin_msa_bclri_w:
  3091. case Mips::BI__builtin_msa_bnegi_w:
  3092. case Mips::BI__builtin_msa_bseti_w:
  3093. case Mips::BI__builtin_msa_sat_s_w:
  3094. case Mips::BI__builtin_msa_sat_u_w:
  3095. case Mips::BI__builtin_msa_slli_w:
  3096. case Mips::BI__builtin_msa_srai_w:
  3097. case Mips::BI__builtin_msa_srari_w:
  3098. case Mips::BI__builtin_msa_srli_w:
  3099. case Mips::BI__builtin_msa_srlri_w:
  3100. case Mips::BI__builtin_msa_subvi_b:
  3101. case Mips::BI__builtin_msa_subvi_h:
  3102. case Mips::BI__builtin_msa_subvi_w:
  3103. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  3104. case Mips::BI__builtin_msa_binsli_w:
  3105. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  3106. // These intrinsics take an unsigned 6 bit immediate.
  3107. case Mips::BI__builtin_msa_bclri_d:
  3108. case Mips::BI__builtin_msa_bnegi_d:
  3109. case Mips::BI__builtin_msa_bseti_d:
  3110. case Mips::BI__builtin_msa_sat_s_d:
  3111. case Mips::BI__builtin_msa_sat_u_d:
  3112. case Mips::BI__builtin_msa_slli_d:
  3113. case Mips::BI__builtin_msa_srai_d:
  3114. case Mips::BI__builtin_msa_srari_d:
  3115. case Mips::BI__builtin_msa_srli_d:
  3116. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  3117. case Mips::BI__builtin_msa_binsli_d:
  3118. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  3119. // These intrinsics take a signed 5 bit immediate.
  3120. case Mips::BI__builtin_msa_ceqi_b:
  3121. case Mips::BI__builtin_msa_ceqi_h:
  3122. case Mips::BI__builtin_msa_ceqi_w:
  3123. case Mips::BI__builtin_msa_ceqi_d:
  3124. case Mips::BI__builtin_msa_clti_s_b:
  3125. case Mips::BI__builtin_msa_clti_s_h:
  3126. case Mips::BI__builtin_msa_clti_s_w:
  3127. case Mips::BI__builtin_msa_clti_s_d:
  3128. case Mips::BI__builtin_msa_clei_s_b:
  3129. case Mips::BI__builtin_msa_clei_s_h:
  3130. case Mips::BI__builtin_msa_clei_s_w:
  3131. case Mips::BI__builtin_msa_clei_s_d:
  3132. case Mips::BI__builtin_msa_maxi_s_b:
  3133. case Mips::BI__builtin_msa_maxi_s_h:
  3134. case Mips::BI__builtin_msa_maxi_s_w:
  3135. case Mips::BI__builtin_msa_maxi_s_d:
  3136. case Mips::BI__builtin_msa_mini_s_b:
  3137. case Mips::BI__builtin_msa_mini_s_h:
  3138. case Mips::BI__builtin_msa_mini_s_w:
  3139. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  3140. // These intrinsics take an unsigned 8 bit immediate.
  3141. case Mips::BI__builtin_msa_andi_b:
  3142. case Mips::BI__builtin_msa_nori_b:
  3143. case Mips::BI__builtin_msa_ori_b:
  3144. case Mips::BI__builtin_msa_shf_b:
  3145. case Mips::BI__builtin_msa_shf_h:
  3146. case Mips::BI__builtin_msa_shf_w:
  3147. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  3148. case Mips::BI__builtin_msa_bseli_b:
  3149. case Mips::BI__builtin_msa_bmnzi_b:
  3150. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  3151. // df/n format
  3152. // These intrinsics take an unsigned 4 bit immediate.
  3153. case Mips::BI__builtin_msa_copy_s_b:
  3154. case Mips::BI__builtin_msa_copy_u_b:
  3155. case Mips::BI__builtin_msa_insve_b:
  3156. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  3157. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  3158. // These intrinsics take an unsigned 3 bit immediate.
  3159. case Mips::BI__builtin_msa_copy_s_h:
  3160. case Mips::BI__builtin_msa_copy_u_h:
  3161. case Mips::BI__builtin_msa_insve_h:
  3162. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  3163. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  3164. // These intrinsics take an unsigned 2 bit immediate.
  3165. case Mips::BI__builtin_msa_copy_s_w:
  3166. case Mips::BI__builtin_msa_copy_u_w:
  3167. case Mips::BI__builtin_msa_insve_w:
  3168. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  3169. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  3170. // These intrinsics take an unsigned 1 bit immediate.
  3171. case Mips::BI__builtin_msa_copy_s_d:
  3172. case Mips::BI__builtin_msa_copy_u_d:
  3173. case Mips::BI__builtin_msa_insve_d:
  3174. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  3175. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  3176. // Memory offsets and immediate loads.
  3177. // These intrinsics take a signed 10 bit immediate.
  3178. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  3179. case Mips::BI__builtin_msa_ldi_h:
  3180. case Mips::BI__builtin_msa_ldi_w:
  3181. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  3182. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  3183. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  3184. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  3185. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  3186. case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
  3187. case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
  3188. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  3189. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  3190. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  3191. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  3192. case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
  3193. case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
  3194. }
  3195. if (!m)
  3196. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3197. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  3198. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  3199. }
  3200. /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
  3201. /// advancing the pointer over the consumed characters. The decoded type is
  3202. /// returned. If the decoded type represents a constant integer with a
  3203. /// constraint on its value then Mask is set to that value. The type descriptors
  3204. /// used in Str are specific to PPC MMA builtins and are documented in the file
  3205. /// defining the PPC builtins.
  3206. static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
  3207. unsigned &Mask) {
  3208. bool RequireICE = false;
  3209. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  3210. switch (*Str++) {
  3211. case 'V':
  3212. return Context.getVectorType(Context.UnsignedCharTy, 16,
  3213. VectorType::VectorKind::AltiVecVector);
  3214. case 'i': {
  3215. char *End;
  3216. unsigned size = strtoul(Str, &End, 10);
  3217. assert(End != Str && "Missing constant parameter constraint");
  3218. Str = End;
  3219. Mask = size;
  3220. return Context.IntTy;
  3221. }
  3222. case 'W': {
  3223. char *End;
  3224. unsigned size = strtoul(Str, &End, 10);
  3225. assert(End != Str && "Missing PowerPC MMA type size");
  3226. Str = End;
  3227. QualType Type;
  3228. switch (size) {
  3229. #define PPC_VECTOR_TYPE(typeName, Id, size) \
  3230. case size: Type = Context.Id##Ty; break;
  3231. #include "clang/Basic/PPCTypes.def"
  3232. default: llvm_unreachable("Invalid PowerPC MMA vector type");
  3233. }
  3234. bool CheckVectorArgs = false;
  3235. while (!CheckVectorArgs) {
  3236. switch (*Str++) {
  3237. case '*':
  3238. Type = Context.getPointerType(Type);
  3239. break;
  3240. case 'C':
  3241. Type = Type.withConst();
  3242. break;
  3243. default:
  3244. CheckVectorArgs = true;
  3245. --Str;
  3246. break;
  3247. }
  3248. }
  3249. return Type;
  3250. }
  3251. default:
  3252. return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
  3253. }
  3254. }
  3255. static bool isPPC_64Builtin(unsigned BuiltinID) {
  3256. // These builtins only work on PPC 64bit targets.
  3257. switch (BuiltinID) {
  3258. case PPC::BI__builtin_divde:
  3259. case PPC::BI__builtin_divdeu:
  3260. case PPC::BI__builtin_bpermd:
  3261. case PPC::BI__builtin_ppc_ldarx:
  3262. case PPC::BI__builtin_ppc_stdcx:
  3263. case PPC::BI__builtin_ppc_tdw:
  3264. case PPC::BI__builtin_ppc_trapd:
  3265. case PPC::BI__builtin_ppc_cmpeqb:
  3266. case PPC::BI__builtin_ppc_setb:
  3267. case PPC::BI__builtin_ppc_mulhd:
  3268. case PPC::BI__builtin_ppc_mulhdu:
  3269. case PPC::BI__builtin_ppc_maddhd:
  3270. case PPC::BI__builtin_ppc_maddhdu:
  3271. case PPC::BI__builtin_ppc_maddld:
  3272. case PPC::BI__builtin_ppc_load8r:
  3273. case PPC::BI__builtin_ppc_store8r:
  3274. case PPC::BI__builtin_ppc_insert_exp:
  3275. case PPC::BI__builtin_ppc_extract_sig:
  3276. case PPC::BI__builtin_ppc_addex:
  3277. case PPC::BI__builtin_darn:
  3278. case PPC::BI__builtin_darn_raw:
  3279. case PPC::BI__builtin_ppc_compare_and_swaplp:
  3280. case PPC::BI__builtin_ppc_fetch_and_addlp:
  3281. case PPC::BI__builtin_ppc_fetch_and_andlp:
  3282. case PPC::BI__builtin_ppc_fetch_and_orlp:
  3283. case PPC::BI__builtin_ppc_fetch_and_swaplp:
  3284. return true;
  3285. }
  3286. return false;
  3287. }
  3288. static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
  3289. StringRef FeatureToCheck, unsigned DiagID,
  3290. StringRef DiagArg = "") {
  3291. if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
  3292. return false;
  3293. if (DiagArg.empty())
  3294. S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
  3295. else
  3296. S.Diag(TheCall->getBeginLoc(), DiagID)
  3297. << DiagArg << TheCall->getSourceRange();
  3298. return true;
  3299. }
  3300. /// Returns true if the argument consists of one contiguous run of 1s with any
  3301. /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
  3302. /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
  3303. /// since all 1s are not contiguous.
  3304. bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
  3305. llvm::APSInt Result;
  3306. // We can't check the value of a dependent argument.
  3307. Expr *Arg = TheCall->getArg(ArgNum);
  3308. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3309. return false;
  3310. // Check constant-ness first.
  3311. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3312. return true;
  3313. // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
  3314. if (Result.isShiftedMask() || (~Result).isShiftedMask())
  3315. return false;
  3316. return Diag(TheCall->getBeginLoc(),
  3317. diag::err_argument_not_contiguous_bit_field)
  3318. << ArgNum << Arg->getSourceRange();
  3319. }
  3320. bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  3321. CallExpr *TheCall) {
  3322. unsigned i = 0, l = 0, u = 0;
  3323. bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
  3324. llvm::APSInt Result;
  3325. if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
  3326. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  3327. << TheCall->getSourceRange();
  3328. switch (BuiltinID) {
  3329. default: return false;
  3330. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  3331. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  3332. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  3333. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3334. case PPC::BI__builtin_altivec_dss:
  3335. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
  3336. case PPC::BI__builtin_tbegin:
  3337. case PPC::BI__builtin_tend:
  3338. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
  3339. SemaFeatureCheck(*this, TheCall, "htm",
  3340. diag::err_ppc_builtin_requires_htm);
  3341. case PPC::BI__builtin_tsr:
  3342. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
  3343. SemaFeatureCheck(*this, TheCall, "htm",
  3344. diag::err_ppc_builtin_requires_htm);
  3345. case PPC::BI__builtin_tabortwc:
  3346. case PPC::BI__builtin_tabortdc:
  3347. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3348. SemaFeatureCheck(*this, TheCall, "htm",
  3349. diag::err_ppc_builtin_requires_htm);
  3350. case PPC::BI__builtin_tabortwci:
  3351. case PPC::BI__builtin_tabortdci:
  3352. return SemaFeatureCheck(*this, TheCall, "htm",
  3353. diag::err_ppc_builtin_requires_htm) ||
  3354. (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3355. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
  3356. case PPC::BI__builtin_tabort:
  3357. case PPC::BI__builtin_tcheck:
  3358. case PPC::BI__builtin_treclaim:
  3359. case PPC::BI__builtin_trechkpt:
  3360. case PPC::BI__builtin_tendall:
  3361. case PPC::BI__builtin_tresume:
  3362. case PPC::BI__builtin_tsuspend:
  3363. case PPC::BI__builtin_get_texasr:
  3364. case PPC::BI__builtin_get_texasru:
  3365. case PPC::BI__builtin_get_tfhar:
  3366. case PPC::BI__builtin_get_tfiar:
  3367. case PPC::BI__builtin_set_texasr:
  3368. case PPC::BI__builtin_set_texasru:
  3369. case PPC::BI__builtin_set_tfhar:
  3370. case PPC::BI__builtin_set_tfiar:
  3371. case PPC::BI__builtin_ttest:
  3372. return SemaFeatureCheck(*this, TheCall, "htm",
  3373. diag::err_ppc_builtin_requires_htm);
  3374. // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
  3375. // __builtin_(un)pack_longdouble are available only if long double uses IBM
  3376. // extended double representation.
  3377. case PPC::BI__builtin_unpack_longdouble:
  3378. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
  3379. return true;
  3380. LLVM_FALLTHROUGH;
  3381. case PPC::BI__builtin_pack_longdouble:
  3382. if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
  3383. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
  3384. << "ibmlongdouble";
  3385. return false;
  3386. case PPC::BI__builtin_altivec_dst:
  3387. case PPC::BI__builtin_altivec_dstt:
  3388. case PPC::BI__builtin_altivec_dstst:
  3389. case PPC::BI__builtin_altivec_dststt:
  3390. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
  3391. case PPC::BI__builtin_vsx_xxpermdi:
  3392. case PPC::BI__builtin_vsx_xxsldwi:
  3393. return SemaBuiltinVSX(TheCall);
  3394. case PPC::BI__builtin_divwe:
  3395. case PPC::BI__builtin_divweu:
  3396. case PPC::BI__builtin_divde:
  3397. case PPC::BI__builtin_divdeu:
  3398. return SemaFeatureCheck(*this, TheCall, "extdiv",
  3399. diag::err_ppc_builtin_only_on_arch, "7");
  3400. case PPC::BI__builtin_bpermd:
  3401. return SemaFeatureCheck(*this, TheCall, "bpermd",
  3402. diag::err_ppc_builtin_only_on_arch, "7");
  3403. case PPC::BI__builtin_unpack_vector_int128:
  3404. return SemaFeatureCheck(*this, TheCall, "vsx",
  3405. diag::err_ppc_builtin_only_on_arch, "7") ||
  3406. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3407. case PPC::BI__builtin_pack_vector_int128:
  3408. return SemaFeatureCheck(*this, TheCall, "vsx",
  3409. diag::err_ppc_builtin_only_on_arch, "7");
  3410. case PPC::BI__builtin_altivec_vgnb:
  3411. return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
  3412. case PPC::BI__builtin_altivec_vec_replace_elt:
  3413. case PPC::BI__builtin_altivec_vec_replace_unaligned: {
  3414. QualType VecTy = TheCall->getArg(0)->getType();
  3415. QualType EltTy = TheCall->getArg(1)->getType();
  3416. unsigned Width = Context.getIntWidth(EltTy);
  3417. return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
  3418. !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
  3419. }
  3420. case PPC::BI__builtin_vsx_xxeval:
  3421. return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
  3422. case PPC::BI__builtin_altivec_vsldbi:
  3423. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
  3424. case PPC::BI__builtin_altivec_vsrdbi:
  3425. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
  3426. case PPC::BI__builtin_vsx_xxpermx:
  3427. return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
  3428. case PPC::BI__builtin_ppc_tw:
  3429. case PPC::BI__builtin_ppc_tdw:
  3430. return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
  3431. case PPC::BI__builtin_ppc_cmpeqb:
  3432. case PPC::BI__builtin_ppc_setb:
  3433. case PPC::BI__builtin_ppc_maddhd:
  3434. case PPC::BI__builtin_ppc_maddhdu:
  3435. case PPC::BI__builtin_ppc_maddld:
  3436. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3437. diag::err_ppc_builtin_only_on_arch, "9");
  3438. case PPC::BI__builtin_ppc_cmprb:
  3439. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3440. diag::err_ppc_builtin_only_on_arch, "9") ||
  3441. SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
  3442. // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
  3443. // be a constant that represents a contiguous bit field.
  3444. case PPC::BI__builtin_ppc_rlwnm:
  3445. return SemaValueIsRunOfOnes(TheCall, 2);
  3446. case PPC::BI__builtin_ppc_rlwimi:
  3447. case PPC::BI__builtin_ppc_rldimi:
  3448. return SemaBuiltinConstantArg(TheCall, 2, Result) ||
  3449. SemaValueIsRunOfOnes(TheCall, 3);
  3450. case PPC::BI__builtin_ppc_extract_exp:
  3451. case PPC::BI__builtin_ppc_extract_sig:
  3452. case PPC::BI__builtin_ppc_insert_exp:
  3453. return SemaFeatureCheck(*this, TheCall, "power9-vector",
  3454. diag::err_ppc_builtin_only_on_arch, "9");
  3455. case PPC::BI__builtin_ppc_addex: {
  3456. if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3457. diag::err_ppc_builtin_only_on_arch, "9") ||
  3458. SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
  3459. return true;
  3460. // Output warning for reserved values 1 to 3.
  3461. int ArgValue =
  3462. TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
  3463. if (ArgValue != 0)
  3464. Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
  3465. << ArgValue;
  3466. return false;
  3467. }
  3468. case PPC::BI__builtin_ppc_mtfsb0:
  3469. case PPC::BI__builtin_ppc_mtfsb1:
  3470. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  3471. case PPC::BI__builtin_ppc_mtfsf:
  3472. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
  3473. case PPC::BI__builtin_ppc_mtfsfi:
  3474. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
  3475. SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  3476. case PPC::BI__builtin_ppc_alignx:
  3477. return SemaBuiltinConstantArgPower2(TheCall, 0);
  3478. case PPC::BI__builtin_ppc_rdlam:
  3479. return SemaValueIsRunOfOnes(TheCall, 2);
  3480. case PPC::BI__builtin_ppc_icbt:
  3481. case PPC::BI__builtin_ppc_sthcx:
  3482. case PPC::BI__builtin_ppc_stbcx:
  3483. case PPC::BI__builtin_ppc_lharx:
  3484. case PPC::BI__builtin_ppc_lbarx:
  3485. return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
  3486. diag::err_ppc_builtin_only_on_arch, "8");
  3487. case PPC::BI__builtin_vsx_ldrmb:
  3488. case PPC::BI__builtin_vsx_strmb:
  3489. return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
  3490. diag::err_ppc_builtin_only_on_arch, "8") ||
  3491. SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  3492. case PPC::BI__builtin_altivec_vcntmbb:
  3493. case PPC::BI__builtin_altivec_vcntmbh:
  3494. case PPC::BI__builtin_altivec_vcntmbw:
  3495. case PPC::BI__builtin_altivec_vcntmbd:
  3496. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3497. case PPC::BI__builtin_darn:
  3498. case PPC::BI__builtin_darn_raw:
  3499. case PPC::BI__builtin_darn_32:
  3500. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3501. diag::err_ppc_builtin_only_on_arch, "9");
  3502. case PPC::BI__builtin_vsx_xxgenpcvbm:
  3503. case PPC::BI__builtin_vsx_xxgenpcvhm:
  3504. case PPC::BI__builtin_vsx_xxgenpcvwm:
  3505. case PPC::BI__builtin_vsx_xxgenpcvdm:
  3506. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
  3507. case PPC::BI__builtin_ppc_compare_exp_uo:
  3508. case PPC::BI__builtin_ppc_compare_exp_lt:
  3509. case PPC::BI__builtin_ppc_compare_exp_gt:
  3510. case PPC::BI__builtin_ppc_compare_exp_eq:
  3511. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3512. diag::err_ppc_builtin_only_on_arch, "9") ||
  3513. SemaFeatureCheck(*this, TheCall, "vsx",
  3514. diag::err_ppc_builtin_requires_vsx);
  3515. case PPC::BI__builtin_ppc_test_data_class: {
  3516. // Check if the first argument of the __builtin_ppc_test_data_class call is
  3517. // valid. The argument must be either a 'float' or a 'double'.
  3518. QualType ArgType = TheCall->getArg(0)->getType();
  3519. if (ArgType != QualType(Context.FloatTy) &&
  3520. ArgType != QualType(Context.DoubleTy))
  3521. return Diag(TheCall->getBeginLoc(),
  3522. diag::err_ppc_invalid_test_data_class_type);
  3523. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3524. diag::err_ppc_builtin_only_on_arch, "9") ||
  3525. SemaFeatureCheck(*this, TheCall, "vsx",
  3526. diag::err_ppc_builtin_requires_vsx) ||
  3527. SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
  3528. }
  3529. case PPC::BI__builtin_ppc_load8r:
  3530. case PPC::BI__builtin_ppc_store8r:
  3531. return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
  3532. diag::err_ppc_builtin_only_on_arch, "7");
  3533. #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
  3534. case PPC::BI__builtin_##Name: \
  3535. return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
  3536. #include "clang/Basic/BuiltinsPPC.def"
  3537. }
  3538. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3539. }
  3540. // Check if the given type is a non-pointer PPC MMA type. This function is used
  3541. // in Sema to prevent invalid uses of restricted PPC MMA types.
  3542. bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
  3543. if (Type->isPointerType() || Type->isArrayType())
  3544. return false;
  3545. QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
  3546. #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
  3547. if (false
  3548. #include "clang/Basic/PPCTypes.def"
  3549. ) {
  3550. Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
  3551. return true;
  3552. }
  3553. return false;
  3554. }
  3555. bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
  3556. CallExpr *TheCall) {
  3557. // position of memory order and scope arguments in the builtin
  3558. unsigned OrderIndex, ScopeIndex;
  3559. switch (BuiltinID) {
  3560. case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
  3561. case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
  3562. case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
  3563. case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
  3564. OrderIndex = 2;
  3565. ScopeIndex = 3;
  3566. break;
  3567. case AMDGPU::BI__builtin_amdgcn_fence:
  3568. OrderIndex = 0;
  3569. ScopeIndex = 1;
  3570. break;
  3571. default:
  3572. return false;
  3573. }
  3574. ExprResult Arg = TheCall->getArg(OrderIndex);
  3575. auto ArgExpr = Arg.get();
  3576. Expr::EvalResult ArgResult;
  3577. if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
  3578. return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
  3579. << ArgExpr->getType();
  3580. auto Ord = ArgResult.Val.getInt().getZExtValue();
  3581. // Check validity of memory ordering as per C11 / C++11's memody model.
  3582. // Only fence needs check. Atomic dec/inc allow all memory orders.
  3583. if (!llvm::isValidAtomicOrderingCABI(Ord))
  3584. return Diag(ArgExpr->getBeginLoc(),
  3585. diag::warn_atomic_op_has_invalid_memory_order)
  3586. << ArgExpr->getSourceRange();
  3587. switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
  3588. case llvm::AtomicOrderingCABI::relaxed:
  3589. case llvm::AtomicOrderingCABI::consume:
  3590. if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
  3591. return Diag(ArgExpr->getBeginLoc(),
  3592. diag::warn_atomic_op_has_invalid_memory_order)
  3593. << ArgExpr->getSourceRange();
  3594. break;
  3595. case llvm::AtomicOrderingCABI::acquire:
  3596. case llvm::AtomicOrderingCABI::release:
  3597. case llvm::AtomicOrderingCABI::acq_rel:
  3598. case llvm::AtomicOrderingCABI::seq_cst:
  3599. break;
  3600. }
  3601. Arg = TheCall->getArg(ScopeIndex);
  3602. ArgExpr = Arg.get();
  3603. Expr::EvalResult ArgResult1;
  3604. // Check that sync scope is a constant literal
  3605. if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
  3606. return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
  3607. << ArgExpr->getType();
  3608. return false;
  3609. }
  3610. bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
  3611. llvm::APSInt Result;
  3612. // We can't check the value of a dependent argument.
  3613. Expr *Arg = TheCall->getArg(ArgNum);
  3614. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3615. return false;
  3616. // Check constant-ness first.
  3617. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3618. return true;
  3619. int64_t Val = Result.getSExtValue();
  3620. if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
  3621. return false;
  3622. return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
  3623. << Arg->getSourceRange();
  3624. }
  3625. bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
  3626. unsigned BuiltinID,
  3627. CallExpr *TheCall) {
  3628. // CodeGenFunction can also detect this, but this gives a better error
  3629. // message.
  3630. bool FeatureMissing = false;
  3631. SmallVector<StringRef> ReqFeatures;
  3632. StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
  3633. Features.split(ReqFeatures, ',');
  3634. // Check if each required feature is included
  3635. for (StringRef F : ReqFeatures) {
  3636. SmallVector<StringRef> ReqOpFeatures;
  3637. F.split(ReqOpFeatures, '|');
  3638. bool HasFeature = false;
  3639. for (StringRef OF : ReqOpFeatures) {
  3640. if (TI.hasFeature(OF)) {
  3641. HasFeature = true;
  3642. continue;
  3643. }
  3644. }
  3645. if (!HasFeature) {
  3646. std::string FeatureStrs;
  3647. for (StringRef OF : ReqOpFeatures) {
  3648. // If the feature is 64bit, alter the string so it will print better in
  3649. // the diagnostic.
  3650. if (OF == "64bit")
  3651. OF = "RV64";
  3652. // Convert features like "zbr" and "experimental-zbr" to "Zbr".
  3653. OF.consume_front("experimental-");
  3654. std::string FeatureStr = OF.str();
  3655. FeatureStr[0] = std::toupper(FeatureStr[0]);
  3656. // Combine strings.
  3657. FeatureStrs += FeatureStrs == "" ? "" : ", ";
  3658. FeatureStrs += "'";
  3659. FeatureStrs += FeatureStr;
  3660. FeatureStrs += "'";
  3661. }
  3662. // Error message
  3663. FeatureMissing = true;
  3664. Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
  3665. << TheCall->getSourceRange() << StringRef(FeatureStrs);
  3666. }
  3667. }
  3668. if (FeatureMissing)
  3669. return true;
  3670. switch (BuiltinID) {
  3671. case RISCVVector::BI__builtin_rvv_vsetvli:
  3672. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
  3673. CheckRISCVLMUL(TheCall, 2);
  3674. case RISCVVector::BI__builtin_rvv_vsetvlimax:
  3675. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
  3676. CheckRISCVLMUL(TheCall, 1);
  3677. }
  3678. return false;
  3679. }
  3680. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  3681. CallExpr *TheCall) {
  3682. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  3683. Expr *Arg = TheCall->getArg(0);
  3684. if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
  3685. if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
  3686. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  3687. << Arg->getSourceRange();
  3688. }
  3689. // For intrinsics which take an immediate value as part of the instruction,
  3690. // range check them here.
  3691. unsigned i = 0, l = 0, u = 0;
  3692. switch (BuiltinID) {
  3693. default: return false;
  3694. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  3695. case SystemZ::BI__builtin_s390_verimb:
  3696. case SystemZ::BI__builtin_s390_verimh:
  3697. case SystemZ::BI__builtin_s390_verimf:
  3698. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  3699. case SystemZ::BI__builtin_s390_vfaeb:
  3700. case SystemZ::BI__builtin_s390_vfaeh:
  3701. case SystemZ::BI__builtin_s390_vfaef:
  3702. case SystemZ::BI__builtin_s390_vfaebs:
  3703. case SystemZ::BI__builtin_s390_vfaehs:
  3704. case SystemZ::BI__builtin_s390_vfaefs:
  3705. case SystemZ::BI__builtin_s390_vfaezb:
  3706. case SystemZ::BI__builtin_s390_vfaezh:
  3707. case SystemZ::BI__builtin_s390_vfaezf:
  3708. case SystemZ::BI__builtin_s390_vfaezbs:
  3709. case SystemZ::BI__builtin_s390_vfaezhs:
  3710. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  3711. case SystemZ::BI__builtin_s390_vfisb:
  3712. case SystemZ::BI__builtin_s390_vfidb:
  3713. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  3714. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3715. case SystemZ::BI__builtin_s390_vftcisb:
  3716. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  3717. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  3718. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  3719. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  3720. case SystemZ::BI__builtin_s390_vstrcb:
  3721. case SystemZ::BI__builtin_s390_vstrch:
  3722. case SystemZ::BI__builtin_s390_vstrcf:
  3723. case SystemZ::BI__builtin_s390_vstrczb:
  3724. case SystemZ::BI__builtin_s390_vstrczh:
  3725. case SystemZ::BI__builtin_s390_vstrczf:
  3726. case SystemZ::BI__builtin_s390_vstrcbs:
  3727. case SystemZ::BI__builtin_s390_vstrchs:
  3728. case SystemZ::BI__builtin_s390_vstrcfs:
  3729. case SystemZ::BI__builtin_s390_vstrczbs:
  3730. case SystemZ::BI__builtin_s390_vstrczhs:
  3731. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  3732. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  3733. case SystemZ::BI__builtin_s390_vfminsb:
  3734. case SystemZ::BI__builtin_s390_vfmaxsb:
  3735. case SystemZ::BI__builtin_s390_vfmindb:
  3736. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  3737. case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
  3738. case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
  3739. case SystemZ::BI__builtin_s390_vclfnhs:
  3740. case SystemZ::BI__builtin_s390_vclfnls:
  3741. case SystemZ::BI__builtin_s390_vcfn:
  3742. case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
  3743. case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
  3744. }
  3745. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3746. }
  3747. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  3748. /// This checks that the target supports __builtin_cpu_supports and
  3749. /// that the string argument is constant and valid.
  3750. static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
  3751. CallExpr *TheCall) {
  3752. Expr *Arg = TheCall->getArg(0);
  3753. // Check if the argument is a string literal.
  3754. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3755. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3756. << Arg->getSourceRange();
  3757. // Check the contents of the string.
  3758. StringRef Feature =
  3759. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3760. if (!TI.validateCpuSupports(Feature))
  3761. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  3762. << Arg->getSourceRange();
  3763. return false;
  3764. }
  3765. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  3766. /// This checks that the target supports __builtin_cpu_is and
  3767. /// that the string argument is constant and valid.
  3768. static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
  3769. Expr *Arg = TheCall->getArg(0);
  3770. // Check if the argument is a string literal.
  3771. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3772. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3773. << Arg->getSourceRange();
  3774. // Check the contents of the string.
  3775. StringRef Feature =
  3776. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3777. if (!TI.validateCpuIs(Feature))
  3778. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  3779. << Arg->getSourceRange();
  3780. return false;
  3781. }
  3782. // Check if the rounding mode is legal.
  3783. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  3784. // Indicates if this instruction has rounding control or just SAE.
  3785. bool HasRC = false;
  3786. unsigned ArgNum = 0;
  3787. switch (BuiltinID) {
  3788. default:
  3789. return false;
  3790. case X86::BI__builtin_ia32_vcvttsd2si32:
  3791. case X86::BI__builtin_ia32_vcvttsd2si64:
  3792. case X86::BI__builtin_ia32_vcvttsd2usi32:
  3793. case X86::BI__builtin_ia32_vcvttsd2usi64:
  3794. case X86::BI__builtin_ia32_vcvttss2si32:
  3795. case X86::BI__builtin_ia32_vcvttss2si64:
  3796. case X86::BI__builtin_ia32_vcvttss2usi32:
  3797. case X86::BI__builtin_ia32_vcvttss2usi64:
  3798. case X86::BI__builtin_ia32_vcvttsh2si32:
  3799. case X86::BI__builtin_ia32_vcvttsh2si64:
  3800. case X86::BI__builtin_ia32_vcvttsh2usi32:
  3801. case X86::BI__builtin_ia32_vcvttsh2usi64:
  3802. ArgNum = 1;
  3803. break;
  3804. case X86::BI__builtin_ia32_maxpd512:
  3805. case X86::BI__builtin_ia32_maxps512:
  3806. case X86::BI__builtin_ia32_minpd512:
  3807. case X86::BI__builtin_ia32_minps512:
  3808. case X86::BI__builtin_ia32_maxph512:
  3809. case X86::BI__builtin_ia32_minph512:
  3810. ArgNum = 2;
  3811. break;
  3812. case X86::BI__builtin_ia32_vcvtph2pd512_mask:
  3813. case X86::BI__builtin_ia32_vcvtph2psx512_mask:
  3814. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3815. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3816. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3817. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3818. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3819. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3820. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3821. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3822. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3823. case X86::BI__builtin_ia32_vcvttph2w512_mask:
  3824. case X86::BI__builtin_ia32_vcvttph2uw512_mask:
  3825. case X86::BI__builtin_ia32_vcvttph2dq512_mask:
  3826. case X86::BI__builtin_ia32_vcvttph2udq512_mask:
  3827. case X86::BI__builtin_ia32_vcvttph2qq512_mask:
  3828. case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
  3829. case X86::BI__builtin_ia32_exp2pd_mask:
  3830. case X86::BI__builtin_ia32_exp2ps_mask:
  3831. case X86::BI__builtin_ia32_getexppd512_mask:
  3832. case X86::BI__builtin_ia32_getexpps512_mask:
  3833. case X86::BI__builtin_ia32_getexpph512_mask:
  3834. case X86::BI__builtin_ia32_rcp28pd_mask:
  3835. case X86::BI__builtin_ia32_rcp28ps_mask:
  3836. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3837. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3838. case X86::BI__builtin_ia32_vcomisd:
  3839. case X86::BI__builtin_ia32_vcomiss:
  3840. case X86::BI__builtin_ia32_vcomish:
  3841. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3842. ArgNum = 3;
  3843. break;
  3844. case X86::BI__builtin_ia32_cmppd512_mask:
  3845. case X86::BI__builtin_ia32_cmpps512_mask:
  3846. case X86::BI__builtin_ia32_cmpsd_mask:
  3847. case X86::BI__builtin_ia32_cmpss_mask:
  3848. case X86::BI__builtin_ia32_cmpsh_mask:
  3849. case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
  3850. case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
  3851. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3852. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3853. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3854. case X86::BI__builtin_ia32_getexpsh128_round_mask:
  3855. case X86::BI__builtin_ia32_getmantpd512_mask:
  3856. case X86::BI__builtin_ia32_getmantps512_mask:
  3857. case X86::BI__builtin_ia32_getmantph512_mask:
  3858. case X86::BI__builtin_ia32_maxsd_round_mask:
  3859. case X86::BI__builtin_ia32_maxss_round_mask:
  3860. case X86::BI__builtin_ia32_maxsh_round_mask:
  3861. case X86::BI__builtin_ia32_minsd_round_mask:
  3862. case X86::BI__builtin_ia32_minss_round_mask:
  3863. case X86::BI__builtin_ia32_minsh_round_mask:
  3864. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3865. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3866. case X86::BI__builtin_ia32_reducepd512_mask:
  3867. case X86::BI__builtin_ia32_reduceps512_mask:
  3868. case X86::BI__builtin_ia32_reduceph512_mask:
  3869. case X86::BI__builtin_ia32_rndscalepd_mask:
  3870. case X86::BI__builtin_ia32_rndscaleps_mask:
  3871. case X86::BI__builtin_ia32_rndscaleph_mask:
  3872. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3873. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3874. ArgNum = 4;
  3875. break;
  3876. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3877. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3878. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3879. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3880. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3881. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3882. case X86::BI__builtin_ia32_fixupimmss_mask:
  3883. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3884. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3885. case X86::BI__builtin_ia32_getmantss_round_mask:
  3886. case X86::BI__builtin_ia32_getmantsh_round_mask:
  3887. case X86::BI__builtin_ia32_rangepd512_mask:
  3888. case X86::BI__builtin_ia32_rangeps512_mask:
  3889. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3890. case X86::BI__builtin_ia32_rangess128_round_mask:
  3891. case X86::BI__builtin_ia32_reducesd_mask:
  3892. case X86::BI__builtin_ia32_reducess_mask:
  3893. case X86::BI__builtin_ia32_reducesh_mask:
  3894. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3895. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3896. case X86::BI__builtin_ia32_rndscalesh_round_mask:
  3897. ArgNum = 5;
  3898. break;
  3899. case X86::BI__builtin_ia32_vcvtsd2si64:
  3900. case X86::BI__builtin_ia32_vcvtsd2si32:
  3901. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3902. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3903. case X86::BI__builtin_ia32_vcvtss2si32:
  3904. case X86::BI__builtin_ia32_vcvtss2si64:
  3905. case X86::BI__builtin_ia32_vcvtss2usi32:
  3906. case X86::BI__builtin_ia32_vcvtss2usi64:
  3907. case X86::BI__builtin_ia32_vcvtsh2si32:
  3908. case X86::BI__builtin_ia32_vcvtsh2si64:
  3909. case X86::BI__builtin_ia32_vcvtsh2usi32:
  3910. case X86::BI__builtin_ia32_vcvtsh2usi64:
  3911. case X86::BI__builtin_ia32_sqrtpd512:
  3912. case X86::BI__builtin_ia32_sqrtps512:
  3913. case X86::BI__builtin_ia32_sqrtph512:
  3914. ArgNum = 1;
  3915. HasRC = true;
  3916. break;
  3917. case X86::BI__builtin_ia32_addph512:
  3918. case X86::BI__builtin_ia32_divph512:
  3919. case X86::BI__builtin_ia32_mulph512:
  3920. case X86::BI__builtin_ia32_subph512:
  3921. case X86::BI__builtin_ia32_addpd512:
  3922. case X86::BI__builtin_ia32_addps512:
  3923. case X86::BI__builtin_ia32_divpd512:
  3924. case X86::BI__builtin_ia32_divps512:
  3925. case X86::BI__builtin_ia32_mulpd512:
  3926. case X86::BI__builtin_ia32_mulps512:
  3927. case X86::BI__builtin_ia32_subpd512:
  3928. case X86::BI__builtin_ia32_subps512:
  3929. case X86::BI__builtin_ia32_cvtsi2sd64:
  3930. case X86::BI__builtin_ia32_cvtsi2ss32:
  3931. case X86::BI__builtin_ia32_cvtsi2ss64:
  3932. case X86::BI__builtin_ia32_cvtusi2sd64:
  3933. case X86::BI__builtin_ia32_cvtusi2ss32:
  3934. case X86::BI__builtin_ia32_cvtusi2ss64:
  3935. case X86::BI__builtin_ia32_vcvtusi2sh:
  3936. case X86::BI__builtin_ia32_vcvtusi642sh:
  3937. case X86::BI__builtin_ia32_vcvtsi2sh:
  3938. case X86::BI__builtin_ia32_vcvtsi642sh:
  3939. ArgNum = 2;
  3940. HasRC = true;
  3941. break;
  3942. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3943. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3944. case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
  3945. case X86::BI__builtin_ia32_vcvtps2phx512_mask:
  3946. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3947. case X86::BI__builtin_ia32_cvtpd2dq512_mask:
  3948. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3949. case X86::BI__builtin_ia32_cvtpd2udq512_mask:
  3950. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3951. case X86::BI__builtin_ia32_cvtps2dq512_mask:
  3952. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3953. case X86::BI__builtin_ia32_cvtps2udq512_mask:
  3954. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3955. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3956. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3957. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3958. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3959. case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
  3960. case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
  3961. case X86::BI__builtin_ia32_vcvtw2ph512_mask:
  3962. case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
  3963. case X86::BI__builtin_ia32_vcvtph2w512_mask:
  3964. case X86::BI__builtin_ia32_vcvtph2uw512_mask:
  3965. case X86::BI__builtin_ia32_vcvtph2dq512_mask:
  3966. case X86::BI__builtin_ia32_vcvtph2udq512_mask:
  3967. case X86::BI__builtin_ia32_vcvtph2qq512_mask:
  3968. case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
  3969. case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
  3970. case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
  3971. ArgNum = 3;
  3972. HasRC = true;
  3973. break;
  3974. case X86::BI__builtin_ia32_addsh_round_mask:
  3975. case X86::BI__builtin_ia32_addss_round_mask:
  3976. case X86::BI__builtin_ia32_addsd_round_mask:
  3977. case X86::BI__builtin_ia32_divsh_round_mask:
  3978. case X86::BI__builtin_ia32_divss_round_mask:
  3979. case X86::BI__builtin_ia32_divsd_round_mask:
  3980. case X86::BI__builtin_ia32_mulsh_round_mask:
  3981. case X86::BI__builtin_ia32_mulss_round_mask:
  3982. case X86::BI__builtin_ia32_mulsd_round_mask:
  3983. case X86::BI__builtin_ia32_subsh_round_mask:
  3984. case X86::BI__builtin_ia32_subss_round_mask:
  3985. case X86::BI__builtin_ia32_subsd_round_mask:
  3986. case X86::BI__builtin_ia32_scalefph512_mask:
  3987. case X86::BI__builtin_ia32_scalefpd512_mask:
  3988. case X86::BI__builtin_ia32_scalefps512_mask:
  3989. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3990. case X86::BI__builtin_ia32_scalefss_round_mask:
  3991. case X86::BI__builtin_ia32_scalefsh_round_mask:
  3992. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3993. case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
  3994. case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
  3995. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3996. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3997. case X86::BI__builtin_ia32_sqrtsh_round_mask:
  3998. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3999. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  4000. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  4001. case X86::BI__builtin_ia32_vfmaddss3_mask:
  4002. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  4003. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  4004. case X86::BI__builtin_ia32_vfmaddsh3_mask:
  4005. case X86::BI__builtin_ia32_vfmaddsh3_maskz:
  4006. case X86::BI__builtin_ia32_vfmaddsh3_mask3:
  4007. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  4008. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  4009. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  4010. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  4011. case X86::BI__builtin_ia32_vfmaddps512_mask:
  4012. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  4013. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  4014. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  4015. case X86::BI__builtin_ia32_vfmaddph512_mask:
  4016. case X86::BI__builtin_ia32_vfmaddph512_maskz:
  4017. case X86::BI__builtin_ia32_vfmaddph512_mask3:
  4018. case X86::BI__builtin_ia32_vfmsubph512_mask3:
  4019. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  4020. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  4021. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  4022. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  4023. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  4024. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  4025. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  4026. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  4027. case X86::BI__builtin_ia32_vfmaddsubph512_mask:
  4028. case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
  4029. case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
  4030. case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
  4031. case X86::BI__builtin_ia32_vfmaddcsh_mask:
  4032. case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
  4033. case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
  4034. case X86::BI__builtin_ia32_vfmaddcph512_mask:
  4035. case X86::BI__builtin_ia32_vfmaddcph512_maskz:
  4036. case X86::BI__builtin_ia32_vfmaddcph512_mask3:
  4037. case X86::BI__builtin_ia32_vfcmaddcsh_mask:
  4038. case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
  4039. case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
  4040. case X86::BI__builtin_ia32_vfcmaddcph512_mask:
  4041. case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
  4042. case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
  4043. case X86::BI__builtin_ia32_vfmulcsh_mask:
  4044. case X86::BI__builtin_ia32_vfmulcph512_mask:
  4045. case X86::BI__builtin_ia32_vfcmulcsh_mask:
  4046. case X86::BI__builtin_ia32_vfcmulcph512_mask:
  4047. ArgNum = 4;
  4048. HasRC = true;
  4049. break;
  4050. }
  4051. llvm::APSInt Result;
  4052. // We can't check the value of a dependent argument.
  4053. Expr *Arg = TheCall->getArg(ArgNum);
  4054. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4055. return false;
  4056. // Check constant-ness first.
  4057. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4058. return true;
  4059. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  4060. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  4061. // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
  4062. // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
  4063. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  4064. Result == 8/*ROUND_NO_EXC*/ ||
  4065. (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
  4066. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  4067. return false;
  4068. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  4069. << Arg->getSourceRange();
  4070. }
  4071. // Check if the gather/scatter scale is legal.
  4072. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  4073. CallExpr *TheCall) {
  4074. unsigned ArgNum = 0;
  4075. switch (BuiltinID) {
  4076. default:
  4077. return false;
  4078. case X86::BI__builtin_ia32_gatherpfdpd:
  4079. case X86::BI__builtin_ia32_gatherpfdps:
  4080. case X86::BI__builtin_ia32_gatherpfqpd:
  4081. case X86::BI__builtin_ia32_gatherpfqps:
  4082. case X86::BI__builtin_ia32_scatterpfdpd:
  4083. case X86::BI__builtin_ia32_scatterpfdps:
  4084. case X86::BI__builtin_ia32_scatterpfqpd:
  4085. case X86::BI__builtin_ia32_scatterpfqps:
  4086. ArgNum = 3;
  4087. break;
  4088. case X86::BI__builtin_ia32_gatherd_pd:
  4089. case X86::BI__builtin_ia32_gatherd_pd256:
  4090. case X86::BI__builtin_ia32_gatherq_pd:
  4091. case X86::BI__builtin_ia32_gatherq_pd256:
  4092. case X86::BI__builtin_ia32_gatherd_ps:
  4093. case X86::BI__builtin_ia32_gatherd_ps256:
  4094. case X86::BI__builtin_ia32_gatherq_ps:
  4095. case X86::BI__builtin_ia32_gatherq_ps256:
  4096. case X86::BI__builtin_ia32_gatherd_q:
  4097. case X86::BI__builtin_ia32_gatherd_q256:
  4098. case X86::BI__builtin_ia32_gatherq_q:
  4099. case X86::BI__builtin_ia32_gatherq_q256:
  4100. case X86::BI__builtin_ia32_gatherd_d:
  4101. case X86::BI__builtin_ia32_gatherd_d256:
  4102. case X86::BI__builtin_ia32_gatherq_d:
  4103. case X86::BI__builtin_ia32_gatherq_d256:
  4104. case X86::BI__builtin_ia32_gather3div2df:
  4105. case X86::BI__builtin_ia32_gather3div2di:
  4106. case X86::BI__builtin_ia32_gather3div4df:
  4107. case X86::BI__builtin_ia32_gather3div4di:
  4108. case X86::BI__builtin_ia32_gather3div4sf:
  4109. case X86::BI__builtin_ia32_gather3div4si:
  4110. case X86::BI__builtin_ia32_gather3div8sf:
  4111. case X86::BI__builtin_ia32_gather3div8si:
  4112. case X86::BI__builtin_ia32_gather3siv2df:
  4113. case X86::BI__builtin_ia32_gather3siv2di:
  4114. case X86::BI__builtin_ia32_gather3siv4df:
  4115. case X86::BI__builtin_ia32_gather3siv4di:
  4116. case X86::BI__builtin_ia32_gather3siv4sf:
  4117. case X86::BI__builtin_ia32_gather3siv4si:
  4118. case X86::BI__builtin_ia32_gather3siv8sf:
  4119. case X86::BI__builtin_ia32_gather3siv8si:
  4120. case X86::BI__builtin_ia32_gathersiv8df:
  4121. case X86::BI__builtin_ia32_gathersiv16sf:
  4122. case X86::BI__builtin_ia32_gatherdiv8df:
  4123. case X86::BI__builtin_ia32_gatherdiv16sf:
  4124. case X86::BI__builtin_ia32_gathersiv8di:
  4125. case X86::BI__builtin_ia32_gathersiv16si:
  4126. case X86::BI__builtin_ia32_gatherdiv8di:
  4127. case X86::BI__builtin_ia32_gatherdiv16si:
  4128. case X86::BI__builtin_ia32_scatterdiv2df:
  4129. case X86::BI__builtin_ia32_scatterdiv2di:
  4130. case X86::BI__builtin_ia32_scatterdiv4df:
  4131. case X86::BI__builtin_ia32_scatterdiv4di:
  4132. case X86::BI__builtin_ia32_scatterdiv4sf:
  4133. case X86::BI__builtin_ia32_scatterdiv4si:
  4134. case X86::BI__builtin_ia32_scatterdiv8sf:
  4135. case X86::BI__builtin_ia32_scatterdiv8si:
  4136. case X86::BI__builtin_ia32_scattersiv2df:
  4137. case X86::BI__builtin_ia32_scattersiv2di:
  4138. case X86::BI__builtin_ia32_scattersiv4df:
  4139. case X86::BI__builtin_ia32_scattersiv4di:
  4140. case X86::BI__builtin_ia32_scattersiv4sf:
  4141. case X86::BI__builtin_ia32_scattersiv4si:
  4142. case X86::BI__builtin_ia32_scattersiv8sf:
  4143. case X86::BI__builtin_ia32_scattersiv8si:
  4144. case X86::BI__builtin_ia32_scattersiv8df:
  4145. case X86::BI__builtin_ia32_scattersiv16sf:
  4146. case X86::BI__builtin_ia32_scatterdiv8df:
  4147. case X86::BI__builtin_ia32_scatterdiv16sf:
  4148. case X86::BI__builtin_ia32_scattersiv8di:
  4149. case X86::BI__builtin_ia32_scattersiv16si:
  4150. case X86::BI__builtin_ia32_scatterdiv8di:
  4151. case X86::BI__builtin_ia32_scatterdiv16si:
  4152. ArgNum = 4;
  4153. break;
  4154. }
  4155. llvm::APSInt Result;
  4156. // We can't check the value of a dependent argument.
  4157. Expr *Arg = TheCall->getArg(ArgNum);
  4158. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4159. return false;
  4160. // Check constant-ness first.
  4161. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4162. return true;
  4163. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  4164. return false;
  4165. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  4166. << Arg->getSourceRange();
  4167. }
  4168. enum { TileRegLow = 0, TileRegHigh = 7 };
  4169. bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
  4170. ArrayRef<int> ArgNums) {
  4171. for (int ArgNum : ArgNums) {
  4172. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
  4173. return true;
  4174. }
  4175. return false;
  4176. }
  4177. bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
  4178. ArrayRef<int> ArgNums) {
  4179. // Because the max number of tile register is TileRegHigh + 1, so here we use
  4180. // each bit to represent the usage of them in bitset.
  4181. std::bitset<TileRegHigh + 1> ArgValues;
  4182. for (int ArgNum : ArgNums) {
  4183. Expr *Arg = TheCall->getArg(ArgNum);
  4184. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4185. continue;
  4186. llvm::APSInt Result;
  4187. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4188. return true;
  4189. int ArgExtValue = Result.getExtValue();
  4190. assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
  4191. "Incorrect tile register num.");
  4192. if (ArgValues.test(ArgExtValue))
  4193. return Diag(TheCall->getBeginLoc(),
  4194. diag::err_x86_builtin_tile_arg_duplicate)
  4195. << TheCall->getArg(ArgNum)->getSourceRange();
  4196. ArgValues.set(ArgExtValue);
  4197. }
  4198. return false;
  4199. }
  4200. bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
  4201. ArrayRef<int> ArgNums) {
  4202. return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
  4203. CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
  4204. }
  4205. bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
  4206. switch (BuiltinID) {
  4207. default:
  4208. return false;
  4209. case X86::BI__builtin_ia32_tileloadd64:
  4210. case X86::BI__builtin_ia32_tileloaddt164:
  4211. case X86::BI__builtin_ia32_tilestored64:
  4212. case X86::BI__builtin_ia32_tilezero:
  4213. return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
  4214. case X86::BI__builtin_ia32_tdpbssd:
  4215. case X86::BI__builtin_ia32_tdpbsud:
  4216. case X86::BI__builtin_ia32_tdpbusd:
  4217. case X86::BI__builtin_ia32_tdpbuud:
  4218. case X86::BI__builtin_ia32_tdpbf16ps:
  4219. return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
  4220. }
  4221. }
  4222. static bool isX86_32Builtin(unsigned BuiltinID) {
  4223. // These builtins only work on x86-32 targets.
  4224. switch (BuiltinID) {
  4225. case X86::BI__builtin_ia32_readeflags_u32:
  4226. case X86::BI__builtin_ia32_writeeflags_u32:
  4227. return true;
  4228. }
  4229. return false;
  4230. }
  4231. bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  4232. CallExpr *TheCall) {
  4233. if (BuiltinID == X86::BI__builtin_cpu_supports)
  4234. return SemaBuiltinCpuSupports(*this, TI, TheCall);
  4235. if (BuiltinID == X86::BI__builtin_cpu_is)
  4236. return SemaBuiltinCpuIs(*this, TI, TheCall);
  4237. // Check for 32-bit only builtins on a 64-bit target.
  4238. const llvm::Triple &TT = TI.getTriple();
  4239. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  4240. return Diag(TheCall->getCallee()->getBeginLoc(),
  4241. diag::err_32_bit_builtin_64_bit_tgt);
  4242. // If the intrinsic has rounding or SAE make sure its valid.
  4243. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  4244. return true;
  4245. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  4246. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  4247. return true;
  4248. // If the intrinsic has a tile arguments, make sure they are valid.
  4249. if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
  4250. return true;
  4251. // For intrinsics which take an immediate value as part of the instruction,
  4252. // range check them here.
  4253. int i = 0, l = 0, u = 0;
  4254. switch (BuiltinID) {
  4255. default:
  4256. return false;
  4257. case X86::BI__builtin_ia32_vec_ext_v2si:
  4258. case X86::BI__builtin_ia32_vec_ext_v2di:
  4259. case X86::BI__builtin_ia32_vextractf128_pd256:
  4260. case X86::BI__builtin_ia32_vextractf128_ps256:
  4261. case X86::BI__builtin_ia32_vextractf128_si256:
  4262. case X86::BI__builtin_ia32_extract128i256:
  4263. case X86::BI__builtin_ia32_extractf64x4_mask:
  4264. case X86::BI__builtin_ia32_extracti64x4_mask:
  4265. case X86::BI__builtin_ia32_extractf32x8_mask:
  4266. case X86::BI__builtin_ia32_extracti32x8_mask:
  4267. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  4268. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  4269. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  4270. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  4271. i = 1; l = 0; u = 1;
  4272. break;
  4273. case X86::BI__builtin_ia32_vec_set_v2di:
  4274. case X86::BI__builtin_ia32_vinsertf128_pd256:
  4275. case X86::BI__builtin_ia32_vinsertf128_ps256:
  4276. case X86::BI__builtin_ia32_vinsertf128_si256:
  4277. case X86::BI__builtin_ia32_insert128i256:
  4278. case X86::BI__builtin_ia32_insertf32x8:
  4279. case X86::BI__builtin_ia32_inserti32x8:
  4280. case X86::BI__builtin_ia32_insertf64x4:
  4281. case X86::BI__builtin_ia32_inserti64x4:
  4282. case X86::BI__builtin_ia32_insertf64x2_256:
  4283. case X86::BI__builtin_ia32_inserti64x2_256:
  4284. case X86::BI__builtin_ia32_insertf32x4_256:
  4285. case X86::BI__builtin_ia32_inserti32x4_256:
  4286. i = 2; l = 0; u = 1;
  4287. break;
  4288. case X86::BI__builtin_ia32_vpermilpd:
  4289. case X86::BI__builtin_ia32_vec_ext_v4hi:
  4290. case X86::BI__builtin_ia32_vec_ext_v4si:
  4291. case X86::BI__builtin_ia32_vec_ext_v4sf:
  4292. case X86::BI__builtin_ia32_vec_ext_v4di:
  4293. case X86::BI__builtin_ia32_extractf32x4_mask:
  4294. case X86::BI__builtin_ia32_extracti32x4_mask:
  4295. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  4296. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  4297. i = 1; l = 0; u = 3;
  4298. break;
  4299. case X86::BI_mm_prefetch:
  4300. case X86::BI__builtin_ia32_vec_ext_v8hi:
  4301. case X86::BI__builtin_ia32_vec_ext_v8si:
  4302. i = 1; l = 0; u = 7;
  4303. break;
  4304. case X86::BI__builtin_ia32_sha1rnds4:
  4305. case X86::BI__builtin_ia32_blendpd:
  4306. case X86::BI__builtin_ia32_shufpd:
  4307. case X86::BI__builtin_ia32_vec_set_v4hi:
  4308. case X86::BI__builtin_ia32_vec_set_v4si:
  4309. case X86::BI__builtin_ia32_vec_set_v4di:
  4310. case X86::BI__builtin_ia32_shuf_f32x4_256:
  4311. case X86::BI__builtin_ia32_shuf_f64x2_256:
  4312. case X86::BI__builtin_ia32_shuf_i32x4_256:
  4313. case X86::BI__builtin_ia32_shuf_i64x2_256:
  4314. case X86::BI__builtin_ia32_insertf64x2_512:
  4315. case X86::BI__builtin_ia32_inserti64x2_512:
  4316. case X86::BI__builtin_ia32_insertf32x4:
  4317. case X86::BI__builtin_ia32_inserti32x4:
  4318. i = 2; l = 0; u = 3;
  4319. break;
  4320. case X86::BI__builtin_ia32_vpermil2pd:
  4321. case X86::BI__builtin_ia32_vpermil2pd256:
  4322. case X86::BI__builtin_ia32_vpermil2ps:
  4323. case X86::BI__builtin_ia32_vpermil2ps256:
  4324. i = 3; l = 0; u = 3;
  4325. break;
  4326. case X86::BI__builtin_ia32_cmpb128_mask:
  4327. case X86::BI__builtin_ia32_cmpw128_mask:
  4328. case X86::BI__builtin_ia32_cmpd128_mask:
  4329. case X86::BI__builtin_ia32_cmpq128_mask:
  4330. case X86::BI__builtin_ia32_cmpb256_mask:
  4331. case X86::BI__builtin_ia32_cmpw256_mask:
  4332. case X86::BI__builtin_ia32_cmpd256_mask:
  4333. case X86::BI__builtin_ia32_cmpq256_mask:
  4334. case X86::BI__builtin_ia32_cmpb512_mask:
  4335. case X86::BI__builtin_ia32_cmpw512_mask:
  4336. case X86::BI__builtin_ia32_cmpd512_mask:
  4337. case X86::BI__builtin_ia32_cmpq512_mask:
  4338. case X86::BI__builtin_ia32_ucmpb128_mask:
  4339. case X86::BI__builtin_ia32_ucmpw128_mask:
  4340. case X86::BI__builtin_ia32_ucmpd128_mask:
  4341. case X86::BI__builtin_ia32_ucmpq128_mask:
  4342. case X86::BI__builtin_ia32_ucmpb256_mask:
  4343. case X86::BI__builtin_ia32_ucmpw256_mask:
  4344. case X86::BI__builtin_ia32_ucmpd256_mask:
  4345. case X86::BI__builtin_ia32_ucmpq256_mask:
  4346. case X86::BI__builtin_ia32_ucmpb512_mask:
  4347. case X86::BI__builtin_ia32_ucmpw512_mask:
  4348. case X86::BI__builtin_ia32_ucmpd512_mask:
  4349. case X86::BI__builtin_ia32_ucmpq512_mask:
  4350. case X86::BI__builtin_ia32_vpcomub:
  4351. case X86::BI__builtin_ia32_vpcomuw:
  4352. case X86::BI__builtin_ia32_vpcomud:
  4353. case X86::BI__builtin_ia32_vpcomuq:
  4354. case X86::BI__builtin_ia32_vpcomb:
  4355. case X86::BI__builtin_ia32_vpcomw:
  4356. case X86::BI__builtin_ia32_vpcomd:
  4357. case X86::BI__builtin_ia32_vpcomq:
  4358. case X86::BI__builtin_ia32_vec_set_v8hi:
  4359. case X86::BI__builtin_ia32_vec_set_v8si:
  4360. i = 2; l = 0; u = 7;
  4361. break;
  4362. case X86::BI__builtin_ia32_vpermilpd256:
  4363. case X86::BI__builtin_ia32_roundps:
  4364. case X86::BI__builtin_ia32_roundpd:
  4365. case X86::BI__builtin_ia32_roundps256:
  4366. case X86::BI__builtin_ia32_roundpd256:
  4367. case X86::BI__builtin_ia32_getmantpd128_mask:
  4368. case X86::BI__builtin_ia32_getmantpd256_mask:
  4369. case X86::BI__builtin_ia32_getmantps128_mask:
  4370. case X86::BI__builtin_ia32_getmantps256_mask:
  4371. case X86::BI__builtin_ia32_getmantpd512_mask:
  4372. case X86::BI__builtin_ia32_getmantps512_mask:
  4373. case X86::BI__builtin_ia32_getmantph128_mask:
  4374. case X86::BI__builtin_ia32_getmantph256_mask:
  4375. case X86::BI__builtin_ia32_getmantph512_mask:
  4376. case X86::BI__builtin_ia32_vec_ext_v16qi:
  4377. case X86::BI__builtin_ia32_vec_ext_v16hi:
  4378. i = 1; l = 0; u = 15;
  4379. break;
  4380. case X86::BI__builtin_ia32_pblendd128:
  4381. case X86::BI__builtin_ia32_blendps:
  4382. case X86::BI__builtin_ia32_blendpd256:
  4383. case X86::BI__builtin_ia32_shufpd256:
  4384. case X86::BI__builtin_ia32_roundss:
  4385. case X86::BI__builtin_ia32_roundsd:
  4386. case X86::BI__builtin_ia32_rangepd128_mask:
  4387. case X86::BI__builtin_ia32_rangepd256_mask:
  4388. case X86::BI__builtin_ia32_rangepd512_mask:
  4389. case X86::BI__builtin_ia32_rangeps128_mask:
  4390. case X86::BI__builtin_ia32_rangeps256_mask:
  4391. case X86::BI__builtin_ia32_rangeps512_mask:
  4392. case X86::BI__builtin_ia32_getmantsd_round_mask:
  4393. case X86::BI__builtin_ia32_getmantss_round_mask:
  4394. case X86::BI__builtin_ia32_getmantsh_round_mask:
  4395. case X86::BI__builtin_ia32_vec_set_v16qi:
  4396. case X86::BI__builtin_ia32_vec_set_v16hi:
  4397. i = 2; l = 0; u = 15;
  4398. break;
  4399. case X86::BI__builtin_ia32_vec_ext_v32qi:
  4400. i = 1; l = 0; u = 31;
  4401. break;
  4402. case X86::BI__builtin_ia32_cmpps:
  4403. case X86::BI__builtin_ia32_cmpss:
  4404. case X86::BI__builtin_ia32_cmppd:
  4405. case X86::BI__builtin_ia32_cmpsd:
  4406. case X86::BI__builtin_ia32_cmpps256:
  4407. case X86::BI__builtin_ia32_cmppd256:
  4408. case X86::BI__builtin_ia32_cmpps128_mask:
  4409. case X86::BI__builtin_ia32_cmppd128_mask:
  4410. case X86::BI__builtin_ia32_cmpps256_mask:
  4411. case X86::BI__builtin_ia32_cmppd256_mask:
  4412. case X86::BI__builtin_ia32_cmpps512_mask:
  4413. case X86::BI__builtin_ia32_cmppd512_mask:
  4414. case X86::BI__builtin_ia32_cmpsd_mask:
  4415. case X86::BI__builtin_ia32_cmpss_mask:
  4416. case X86::BI__builtin_ia32_vec_set_v32qi:
  4417. i = 2; l = 0; u = 31;
  4418. break;
  4419. case X86::BI__builtin_ia32_permdf256:
  4420. case X86::BI__builtin_ia32_permdi256:
  4421. case X86::BI__builtin_ia32_permdf512:
  4422. case X86::BI__builtin_ia32_permdi512:
  4423. case X86::BI__builtin_ia32_vpermilps:
  4424. case X86::BI__builtin_ia32_vpermilps256:
  4425. case X86::BI__builtin_ia32_vpermilpd512:
  4426. case X86::BI__builtin_ia32_vpermilps512:
  4427. case X86::BI__builtin_ia32_pshufd:
  4428. case X86::BI__builtin_ia32_pshufd256:
  4429. case X86::BI__builtin_ia32_pshufd512:
  4430. case X86::BI__builtin_ia32_pshufhw:
  4431. case X86::BI__builtin_ia32_pshufhw256:
  4432. case X86::BI__builtin_ia32_pshufhw512:
  4433. case X86::BI__builtin_ia32_pshuflw:
  4434. case X86::BI__builtin_ia32_pshuflw256:
  4435. case X86::BI__builtin_ia32_pshuflw512:
  4436. case X86::BI__builtin_ia32_vcvtps2ph:
  4437. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  4438. case X86::BI__builtin_ia32_vcvtps2ph256:
  4439. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  4440. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  4441. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  4442. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  4443. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  4444. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  4445. case X86::BI__builtin_ia32_rndscaleps_mask:
  4446. case X86::BI__builtin_ia32_rndscalepd_mask:
  4447. case X86::BI__builtin_ia32_rndscaleph_mask:
  4448. case X86::BI__builtin_ia32_reducepd128_mask:
  4449. case X86::BI__builtin_ia32_reducepd256_mask:
  4450. case X86::BI__builtin_ia32_reducepd512_mask:
  4451. case X86::BI__builtin_ia32_reduceps128_mask:
  4452. case X86::BI__builtin_ia32_reduceps256_mask:
  4453. case X86::BI__builtin_ia32_reduceps512_mask:
  4454. case X86::BI__builtin_ia32_reduceph128_mask:
  4455. case X86::BI__builtin_ia32_reduceph256_mask:
  4456. case X86::BI__builtin_ia32_reduceph512_mask:
  4457. case X86::BI__builtin_ia32_prold512:
  4458. case X86::BI__builtin_ia32_prolq512:
  4459. case X86::BI__builtin_ia32_prold128:
  4460. case X86::BI__builtin_ia32_prold256:
  4461. case X86::BI__builtin_ia32_prolq128:
  4462. case X86::BI__builtin_ia32_prolq256:
  4463. case X86::BI__builtin_ia32_prord512:
  4464. case X86::BI__builtin_ia32_prorq512:
  4465. case X86::BI__builtin_ia32_prord128:
  4466. case X86::BI__builtin_ia32_prord256:
  4467. case X86::BI__builtin_ia32_prorq128:
  4468. case X86::BI__builtin_ia32_prorq256:
  4469. case X86::BI__builtin_ia32_fpclasspd128_mask:
  4470. case X86::BI__builtin_ia32_fpclasspd256_mask:
  4471. case X86::BI__builtin_ia32_fpclassps128_mask:
  4472. case X86::BI__builtin_ia32_fpclassps256_mask:
  4473. case X86::BI__builtin_ia32_fpclassps512_mask:
  4474. case X86::BI__builtin_ia32_fpclasspd512_mask:
  4475. case X86::BI__builtin_ia32_fpclassph128_mask:
  4476. case X86::BI__builtin_ia32_fpclassph256_mask:
  4477. case X86::BI__builtin_ia32_fpclassph512_mask:
  4478. case X86::BI__builtin_ia32_fpclasssd_mask:
  4479. case X86::BI__builtin_ia32_fpclassss_mask:
  4480. case X86::BI__builtin_ia32_fpclasssh_mask:
  4481. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  4482. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  4483. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  4484. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  4485. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  4486. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  4487. case X86::BI__builtin_ia32_kshiftliqi:
  4488. case X86::BI__builtin_ia32_kshiftlihi:
  4489. case X86::BI__builtin_ia32_kshiftlisi:
  4490. case X86::BI__builtin_ia32_kshiftlidi:
  4491. case X86::BI__builtin_ia32_kshiftriqi:
  4492. case X86::BI__builtin_ia32_kshiftrihi:
  4493. case X86::BI__builtin_ia32_kshiftrisi:
  4494. case X86::BI__builtin_ia32_kshiftridi:
  4495. i = 1; l = 0; u = 255;
  4496. break;
  4497. case X86::BI__builtin_ia32_vperm2f128_pd256:
  4498. case X86::BI__builtin_ia32_vperm2f128_ps256:
  4499. case X86::BI__builtin_ia32_vperm2f128_si256:
  4500. case X86::BI__builtin_ia32_permti256:
  4501. case X86::BI__builtin_ia32_pblendw128:
  4502. case X86::BI__builtin_ia32_pblendw256:
  4503. case X86::BI__builtin_ia32_blendps256:
  4504. case X86::BI__builtin_ia32_pblendd256:
  4505. case X86::BI__builtin_ia32_palignr128:
  4506. case X86::BI__builtin_ia32_palignr256:
  4507. case X86::BI__builtin_ia32_palignr512:
  4508. case X86::BI__builtin_ia32_alignq512:
  4509. case X86::BI__builtin_ia32_alignd512:
  4510. case X86::BI__builtin_ia32_alignd128:
  4511. case X86::BI__builtin_ia32_alignd256:
  4512. case X86::BI__builtin_ia32_alignq128:
  4513. case X86::BI__builtin_ia32_alignq256:
  4514. case X86::BI__builtin_ia32_vcomisd:
  4515. case X86::BI__builtin_ia32_vcomiss:
  4516. case X86::BI__builtin_ia32_shuf_f32x4:
  4517. case X86::BI__builtin_ia32_shuf_f64x2:
  4518. case X86::BI__builtin_ia32_shuf_i32x4:
  4519. case X86::BI__builtin_ia32_shuf_i64x2:
  4520. case X86::BI__builtin_ia32_shufpd512:
  4521. case X86::BI__builtin_ia32_shufps:
  4522. case X86::BI__builtin_ia32_shufps256:
  4523. case X86::BI__builtin_ia32_shufps512:
  4524. case X86::BI__builtin_ia32_dbpsadbw128:
  4525. case X86::BI__builtin_ia32_dbpsadbw256:
  4526. case X86::BI__builtin_ia32_dbpsadbw512:
  4527. case X86::BI__builtin_ia32_vpshldd128:
  4528. case X86::BI__builtin_ia32_vpshldd256:
  4529. case X86::BI__builtin_ia32_vpshldd512:
  4530. case X86::BI__builtin_ia32_vpshldq128:
  4531. case X86::BI__builtin_ia32_vpshldq256:
  4532. case X86::BI__builtin_ia32_vpshldq512:
  4533. case X86::BI__builtin_ia32_vpshldw128:
  4534. case X86::BI__builtin_ia32_vpshldw256:
  4535. case X86::BI__builtin_ia32_vpshldw512:
  4536. case X86::BI__builtin_ia32_vpshrdd128:
  4537. case X86::BI__builtin_ia32_vpshrdd256:
  4538. case X86::BI__builtin_ia32_vpshrdd512:
  4539. case X86::BI__builtin_ia32_vpshrdq128:
  4540. case X86::BI__builtin_ia32_vpshrdq256:
  4541. case X86::BI__builtin_ia32_vpshrdq512:
  4542. case X86::BI__builtin_ia32_vpshrdw128:
  4543. case X86::BI__builtin_ia32_vpshrdw256:
  4544. case X86::BI__builtin_ia32_vpshrdw512:
  4545. i = 2; l = 0; u = 255;
  4546. break;
  4547. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  4548. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  4549. case X86::BI__builtin_ia32_fixupimmps512_mask:
  4550. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  4551. case X86::BI__builtin_ia32_fixupimmsd_mask:
  4552. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  4553. case X86::BI__builtin_ia32_fixupimmss_mask:
  4554. case X86::BI__builtin_ia32_fixupimmss_maskz:
  4555. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  4556. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  4557. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  4558. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  4559. case X86::BI__builtin_ia32_fixupimmps128_mask:
  4560. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  4561. case X86::BI__builtin_ia32_fixupimmps256_mask:
  4562. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  4563. case X86::BI__builtin_ia32_pternlogd512_mask:
  4564. case X86::BI__builtin_ia32_pternlogd512_maskz:
  4565. case X86::BI__builtin_ia32_pternlogq512_mask:
  4566. case X86::BI__builtin_ia32_pternlogq512_maskz:
  4567. case X86::BI__builtin_ia32_pternlogd128_mask:
  4568. case X86::BI__builtin_ia32_pternlogd128_maskz:
  4569. case X86::BI__builtin_ia32_pternlogd256_mask:
  4570. case X86::BI__builtin_ia32_pternlogd256_maskz:
  4571. case X86::BI__builtin_ia32_pternlogq128_mask:
  4572. case X86::BI__builtin_ia32_pternlogq128_maskz:
  4573. case X86::BI__builtin_ia32_pternlogq256_mask:
  4574. case X86::BI__builtin_ia32_pternlogq256_maskz:
  4575. i = 3; l = 0; u = 255;
  4576. break;
  4577. case X86::BI__builtin_ia32_gatherpfdpd:
  4578. case X86::BI__builtin_ia32_gatherpfdps:
  4579. case X86::BI__builtin_ia32_gatherpfqpd:
  4580. case X86::BI__builtin_ia32_gatherpfqps:
  4581. case X86::BI__builtin_ia32_scatterpfdpd:
  4582. case X86::BI__builtin_ia32_scatterpfdps:
  4583. case X86::BI__builtin_ia32_scatterpfqpd:
  4584. case X86::BI__builtin_ia32_scatterpfqps:
  4585. i = 4; l = 2; u = 3;
  4586. break;
  4587. case X86::BI__builtin_ia32_reducesd_mask:
  4588. case X86::BI__builtin_ia32_reducess_mask:
  4589. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  4590. case X86::BI__builtin_ia32_rndscaless_round_mask:
  4591. case X86::BI__builtin_ia32_rndscalesh_round_mask:
  4592. case X86::BI__builtin_ia32_reducesh_mask:
  4593. i = 4; l = 0; u = 255;
  4594. break;
  4595. }
  4596. // Note that we don't force a hard error on the range check here, allowing
  4597. // template-generated or macro-generated dead code to potentially have out-of-
  4598. // range values. These need to code generate, but don't need to necessarily
  4599. // make any sense. We use a warning that defaults to an error.
  4600. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  4601. }
  4602. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  4603. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  4604. /// Returns true when the format fits the function and the FormatStringInfo has
  4605. /// been populated.
  4606. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  4607. FormatStringInfo *FSI) {
  4608. FSI->HasVAListArg = Format->getFirstArg() == 0;
  4609. FSI->FormatIdx = Format->getFormatIdx() - 1;
  4610. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  4611. // The way the format attribute works in GCC, the implicit this argument
  4612. // of member functions is counted. However, it doesn't appear in our own
  4613. // lists, so decrement format_idx in that case.
  4614. if (IsCXXMember) {
  4615. if(FSI->FormatIdx == 0)
  4616. return false;
  4617. --FSI->FormatIdx;
  4618. if (FSI->FirstDataArg != 0)
  4619. --FSI->FirstDataArg;
  4620. }
  4621. return true;
  4622. }
  4623. /// Checks if a the given expression evaluates to null.
  4624. ///
  4625. /// Returns true if the value evaluates to null.
  4626. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  4627. // If the expression has non-null type, it doesn't evaluate to null.
  4628. if (auto nullability
  4629. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  4630. if (*nullability == NullabilityKind::NonNull)
  4631. return false;
  4632. }
  4633. // As a special case, transparent unions initialized with zero are
  4634. // considered null for the purposes of the nonnull attribute.
  4635. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  4636. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  4637. if (const CompoundLiteralExpr *CLE =
  4638. dyn_cast<CompoundLiteralExpr>(Expr))
  4639. if (const InitListExpr *ILE =
  4640. dyn_cast<InitListExpr>(CLE->getInitializer()))
  4641. Expr = ILE->getInit(0);
  4642. }
  4643. bool Result;
  4644. return (!Expr->isValueDependent() &&
  4645. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  4646. !Result);
  4647. }
  4648. static void CheckNonNullArgument(Sema &S,
  4649. const Expr *ArgExpr,
  4650. SourceLocation CallSiteLoc) {
  4651. if (CheckNonNullExpr(S, ArgExpr))
  4652. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  4653. S.PDiag(diag::warn_null_arg)
  4654. << ArgExpr->getSourceRange());
  4655. }
  4656. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  4657. FormatStringInfo FSI;
  4658. if ((GetFormatStringType(Format) == FST_NSString) &&
  4659. getFormatStringInfo(Format, false, &FSI)) {
  4660. Idx = FSI.FormatIdx;
  4661. return true;
  4662. }
  4663. return false;
  4664. }
  4665. /// Diagnose use of %s directive in an NSString which is being passed
  4666. /// as formatting string to formatting method.
  4667. static void
  4668. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  4669. const NamedDecl *FDecl,
  4670. Expr **Args,
  4671. unsigned NumArgs) {
  4672. unsigned Idx = 0;
  4673. bool Format = false;
  4674. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  4675. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  4676. Idx = 2;
  4677. Format = true;
  4678. }
  4679. else
  4680. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  4681. if (S.GetFormatNSStringIdx(I, Idx)) {
  4682. Format = true;
  4683. break;
  4684. }
  4685. }
  4686. if (!Format || NumArgs <= Idx)
  4687. return;
  4688. const Expr *FormatExpr = Args[Idx];
  4689. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  4690. FormatExpr = CSCE->getSubExpr();
  4691. const StringLiteral *FormatString;
  4692. if (const ObjCStringLiteral *OSL =
  4693. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  4694. FormatString = OSL->getString();
  4695. else
  4696. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  4697. if (!FormatString)
  4698. return;
  4699. if (S.FormatStringHasSArg(FormatString)) {
  4700. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  4701. << "%s" << 1 << 1;
  4702. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  4703. << FDecl->getDeclName();
  4704. }
  4705. }
  4706. /// Determine whether the given type has a non-null nullability annotation.
  4707. static bool isNonNullType(ASTContext &ctx, QualType type) {
  4708. if (auto nullability = type->getNullability(ctx))
  4709. return *nullability == NullabilityKind::NonNull;
  4710. return false;
  4711. }
  4712. static void CheckNonNullArguments(Sema &S,
  4713. const NamedDecl *FDecl,
  4714. const FunctionProtoType *Proto,
  4715. ArrayRef<const Expr *> Args,
  4716. SourceLocation CallSiteLoc) {
  4717. assert((FDecl || Proto) && "Need a function declaration or prototype");
  4718. // Already checked by by constant evaluator.
  4719. if (S.isConstantEvaluated())
  4720. return;
  4721. // Check the attributes attached to the method/function itself.
  4722. llvm::SmallBitVector NonNullArgs;
  4723. if (FDecl) {
  4724. // Handle the nonnull attribute on the function/method declaration itself.
  4725. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  4726. if (!NonNull->args_size()) {
  4727. // Easy case: all pointer arguments are nonnull.
  4728. for (const auto *Arg : Args)
  4729. if (S.isValidPointerAttrType(Arg->getType()))
  4730. CheckNonNullArgument(S, Arg, CallSiteLoc);
  4731. return;
  4732. }
  4733. for (const ParamIdx &Idx : NonNull->args()) {
  4734. unsigned IdxAST = Idx.getASTIndex();
  4735. if (IdxAST >= Args.size())
  4736. continue;
  4737. if (NonNullArgs.empty())
  4738. NonNullArgs.resize(Args.size());
  4739. NonNullArgs.set(IdxAST);
  4740. }
  4741. }
  4742. }
  4743. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  4744. // Handle the nonnull attribute on the parameters of the
  4745. // function/method.
  4746. ArrayRef<ParmVarDecl*> parms;
  4747. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  4748. parms = FD->parameters();
  4749. else
  4750. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  4751. unsigned ParamIndex = 0;
  4752. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  4753. I != E; ++I, ++ParamIndex) {
  4754. const ParmVarDecl *PVD = *I;
  4755. if (PVD->hasAttr<NonNullAttr>() ||
  4756. isNonNullType(S.Context, PVD->getType())) {
  4757. if (NonNullArgs.empty())
  4758. NonNullArgs.resize(Args.size());
  4759. NonNullArgs.set(ParamIndex);
  4760. }
  4761. }
  4762. } else {
  4763. // If we have a non-function, non-method declaration but no
  4764. // function prototype, try to dig out the function prototype.
  4765. if (!Proto) {
  4766. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  4767. QualType type = VD->getType().getNonReferenceType();
  4768. if (auto pointerType = type->getAs<PointerType>())
  4769. type = pointerType->getPointeeType();
  4770. else if (auto blockType = type->getAs<BlockPointerType>())
  4771. type = blockType->getPointeeType();
  4772. // FIXME: data member pointers?
  4773. // Dig out the function prototype, if there is one.
  4774. Proto = type->getAs<FunctionProtoType>();
  4775. }
  4776. }
  4777. // Fill in non-null argument information from the nullability
  4778. // information on the parameter types (if we have them).
  4779. if (Proto) {
  4780. unsigned Index = 0;
  4781. for (auto paramType : Proto->getParamTypes()) {
  4782. if (isNonNullType(S.Context, paramType)) {
  4783. if (NonNullArgs.empty())
  4784. NonNullArgs.resize(Args.size());
  4785. NonNullArgs.set(Index);
  4786. }
  4787. ++Index;
  4788. }
  4789. }
  4790. }
  4791. // Check for non-null arguments.
  4792. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  4793. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  4794. if (NonNullArgs[ArgIndex])
  4795. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  4796. }
  4797. }
  4798. /// Warn if a pointer or reference argument passed to a function points to an
  4799. /// object that is less aligned than the parameter. This can happen when
  4800. /// creating a typedef with a lower alignment than the original type and then
  4801. /// calling functions defined in terms of the original type.
  4802. void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
  4803. StringRef ParamName, QualType ArgTy,
  4804. QualType ParamTy) {
  4805. // If a function accepts a pointer or reference type
  4806. if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
  4807. return;
  4808. // If the parameter is a pointer type, get the pointee type for the
  4809. // argument too. If the parameter is a reference type, don't try to get
  4810. // the pointee type for the argument.
  4811. if (ParamTy->isPointerType())
  4812. ArgTy = ArgTy->getPointeeType();
  4813. // Remove reference or pointer
  4814. ParamTy = ParamTy->getPointeeType();
  4815. // Find expected alignment, and the actual alignment of the passed object.
  4816. // getTypeAlignInChars requires complete types
  4817. if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
  4818. ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
  4819. ArgTy->isUndeducedType())
  4820. return;
  4821. CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
  4822. CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
  4823. // If the argument is less aligned than the parameter, there is a
  4824. // potential alignment issue.
  4825. if (ArgAlign < ParamAlign)
  4826. Diag(Loc, diag::warn_param_mismatched_alignment)
  4827. << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
  4828. << ParamName << (FDecl != nullptr) << FDecl;
  4829. }
  4830. /// Handles the checks for format strings, non-POD arguments to vararg
  4831. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  4832. /// attributes.
  4833. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  4834. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  4835. bool IsMemberFunction, SourceLocation Loc,
  4836. SourceRange Range, VariadicCallType CallType) {
  4837. // FIXME: We should check as much as we can in the template definition.
  4838. if (CurContext->isDependentContext())
  4839. return;
  4840. // Printf and scanf checking.
  4841. llvm::SmallBitVector CheckedVarArgs;
  4842. if (FDecl) {
  4843. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  4844. // Only create vector if there are format attributes.
  4845. CheckedVarArgs.resize(Args.size());
  4846. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  4847. CheckedVarArgs);
  4848. }
  4849. }
  4850. // Refuse POD arguments that weren't caught by the format string
  4851. // checks above.
  4852. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  4853. if (CallType != VariadicDoesNotApply &&
  4854. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  4855. unsigned NumParams = Proto ? Proto->getNumParams()
  4856. : FDecl && isa<FunctionDecl>(FDecl)
  4857. ? cast<FunctionDecl>(FDecl)->getNumParams()
  4858. : FDecl && isa<ObjCMethodDecl>(FDecl)
  4859. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  4860. : 0;
  4861. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  4862. // Args[ArgIdx] can be null in malformed code.
  4863. if (const Expr *Arg = Args[ArgIdx]) {
  4864. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  4865. checkVariadicArgument(Arg, CallType);
  4866. }
  4867. }
  4868. }
  4869. if (FDecl || Proto) {
  4870. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  4871. // Type safety checking.
  4872. if (FDecl) {
  4873. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  4874. CheckArgumentWithTypeTag(I, Args, Loc);
  4875. }
  4876. }
  4877. // Check that passed arguments match the alignment of original arguments.
  4878. // Try to get the missing prototype from the declaration.
  4879. if (!Proto && FDecl) {
  4880. const auto *FT = FDecl->getFunctionType();
  4881. if (isa_and_nonnull<FunctionProtoType>(FT))
  4882. Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
  4883. }
  4884. if (Proto) {
  4885. // For variadic functions, we may have more args than parameters.
  4886. // For some K&R functions, we may have less args than parameters.
  4887. const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
  4888. for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
  4889. // Args[ArgIdx] can be null in malformed code.
  4890. if (const Expr *Arg = Args[ArgIdx]) {
  4891. if (Arg->containsErrors())
  4892. continue;
  4893. QualType ParamTy = Proto->getParamType(ArgIdx);
  4894. QualType ArgTy = Arg->getType();
  4895. CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
  4896. ArgTy, ParamTy);
  4897. }
  4898. }
  4899. }
  4900. if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
  4901. auto *AA = FDecl->getAttr<AllocAlignAttr>();
  4902. const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
  4903. if (!Arg->isValueDependent()) {
  4904. Expr::EvalResult Align;
  4905. if (Arg->EvaluateAsInt(Align, Context)) {
  4906. const llvm::APSInt &I = Align.Val.getInt();
  4907. if (!I.isPowerOf2())
  4908. Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
  4909. << Arg->getSourceRange();
  4910. if (I > Sema::MaximumAlignment)
  4911. Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
  4912. << Arg->getSourceRange() << Sema::MaximumAlignment;
  4913. }
  4914. }
  4915. }
  4916. if (FD)
  4917. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  4918. }
  4919. /// CheckConstructorCall - Check a constructor call for correctness and safety
  4920. /// properties not enforced by the C type system.
  4921. void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
  4922. ArrayRef<const Expr *> Args,
  4923. const FunctionProtoType *Proto,
  4924. SourceLocation Loc) {
  4925. VariadicCallType CallType =
  4926. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  4927. auto *Ctor = cast<CXXConstructorDecl>(FDecl);
  4928. CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
  4929. Context.getPointerType(Ctor->getThisObjectType()));
  4930. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  4931. Loc, SourceRange(), CallType);
  4932. }
  4933. /// CheckFunctionCall - Check a direct function call for various correctness
  4934. /// and safety properties not strictly enforced by the C type system.
  4935. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  4936. const FunctionProtoType *Proto) {
  4937. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  4938. isa<CXXMethodDecl>(FDecl);
  4939. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  4940. IsMemberOperatorCall;
  4941. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  4942. TheCall->getCallee());
  4943. Expr** Args = TheCall->getArgs();
  4944. unsigned NumArgs = TheCall->getNumArgs();
  4945. Expr *ImplicitThis = nullptr;
  4946. if (IsMemberOperatorCall) {
  4947. // If this is a call to a member operator, hide the first argument
  4948. // from checkCall.
  4949. // FIXME: Our choice of AST representation here is less than ideal.
  4950. ImplicitThis = Args[0];
  4951. ++Args;
  4952. --NumArgs;
  4953. } else if (IsMemberFunction)
  4954. ImplicitThis =
  4955. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  4956. if (ImplicitThis) {
  4957. // ImplicitThis may or may not be a pointer, depending on whether . or -> is
  4958. // used.
  4959. QualType ThisType = ImplicitThis->getType();
  4960. if (!ThisType->isPointerType()) {
  4961. assert(!ThisType->isReferenceType());
  4962. ThisType = Context.getPointerType(ThisType);
  4963. }
  4964. QualType ThisTypeFromDecl =
  4965. Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
  4966. CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
  4967. ThisTypeFromDecl);
  4968. }
  4969. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  4970. IsMemberFunction, TheCall->getRParenLoc(),
  4971. TheCall->getCallee()->getSourceRange(), CallType);
  4972. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4973. // None of the checks below are needed for functions that don't have
  4974. // simple names (e.g., C++ conversion functions).
  4975. if (!FnInfo)
  4976. return false;
  4977. CheckTCBEnforcement(TheCall, FDecl);
  4978. CheckAbsoluteValueFunction(TheCall, FDecl);
  4979. CheckMaxUnsignedZero(TheCall, FDecl);
  4980. if (getLangOpts().ObjC)
  4981. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  4982. unsigned CMId = FDecl->getMemoryFunctionKind();
  4983. // Handle memory setting and copying functions.
  4984. switch (CMId) {
  4985. case 0:
  4986. return false;
  4987. case Builtin::BIstrlcpy: // fallthrough
  4988. case Builtin::BIstrlcat:
  4989. CheckStrlcpycatArguments(TheCall, FnInfo);
  4990. break;
  4991. case Builtin::BIstrncat:
  4992. CheckStrncatArguments(TheCall, FnInfo);
  4993. break;
  4994. case Builtin::BIfree:
  4995. CheckFreeArguments(TheCall);
  4996. break;
  4997. default:
  4998. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  4999. }
  5000. return false;
  5001. }
  5002. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  5003. ArrayRef<const Expr *> Args) {
  5004. VariadicCallType CallType =
  5005. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  5006. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  5007. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  5008. CallType);
  5009. return false;
  5010. }
  5011. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  5012. const FunctionProtoType *Proto) {
  5013. QualType Ty;
  5014. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  5015. Ty = V->getType().getNonReferenceType();
  5016. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  5017. Ty = F->getType().getNonReferenceType();
  5018. else
  5019. return false;
  5020. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  5021. !Ty->isFunctionProtoType())
  5022. return false;
  5023. VariadicCallType CallType;
  5024. if (!Proto || !Proto->isVariadic()) {
  5025. CallType = VariadicDoesNotApply;
  5026. } else if (Ty->isBlockPointerType()) {
  5027. CallType = VariadicBlock;
  5028. } else { // Ty->isFunctionPointerType()
  5029. CallType = VariadicFunction;
  5030. }
  5031. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  5032. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  5033. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  5034. TheCall->getCallee()->getSourceRange(), CallType);
  5035. return false;
  5036. }
  5037. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  5038. /// such as function pointers returned from functions.
  5039. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  5040. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  5041. TheCall->getCallee());
  5042. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  5043. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  5044. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  5045. TheCall->getCallee()->getSourceRange(), CallType);
  5046. return false;
  5047. }
  5048. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  5049. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  5050. return false;
  5051. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  5052. switch (Op) {
  5053. case AtomicExpr::AO__c11_atomic_init:
  5054. case AtomicExpr::AO__opencl_atomic_init:
  5055. llvm_unreachable("There is no ordering argument for an init");
  5056. case AtomicExpr::AO__c11_atomic_load:
  5057. case AtomicExpr::AO__opencl_atomic_load:
  5058. case AtomicExpr::AO__hip_atomic_load:
  5059. case AtomicExpr::AO__atomic_load_n:
  5060. case AtomicExpr::AO__atomic_load:
  5061. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  5062. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  5063. case AtomicExpr::AO__c11_atomic_store:
  5064. case AtomicExpr::AO__opencl_atomic_store:
  5065. case AtomicExpr::AO__hip_atomic_store:
  5066. case AtomicExpr::AO__atomic_store:
  5067. case AtomicExpr::AO__atomic_store_n:
  5068. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  5069. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  5070. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  5071. default:
  5072. return true;
  5073. }
  5074. }
  5075. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  5076. AtomicExpr::AtomicOp Op) {
  5077. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  5078. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5079. MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
  5080. return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
  5081. DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
  5082. Op);
  5083. }
  5084. ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
  5085. SourceLocation RParenLoc, MultiExprArg Args,
  5086. AtomicExpr::AtomicOp Op,
  5087. AtomicArgumentOrder ArgOrder) {
  5088. // All the non-OpenCL operations take one of the following forms.
  5089. // The OpenCL operations take the __c11 forms with one extra argument for
  5090. // synchronization scope.
  5091. enum {
  5092. // C __c11_atomic_init(A *, C)
  5093. Init,
  5094. // C __c11_atomic_load(A *, int)
  5095. Load,
  5096. // void __atomic_load(A *, CP, int)
  5097. LoadCopy,
  5098. // void __atomic_store(A *, CP, int)
  5099. Copy,
  5100. // C __c11_atomic_add(A *, M, int)
  5101. Arithmetic,
  5102. // C __atomic_exchange_n(A *, CP, int)
  5103. Xchg,
  5104. // void __atomic_exchange(A *, C *, CP, int)
  5105. GNUXchg,
  5106. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  5107. C11CmpXchg,
  5108. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  5109. GNUCmpXchg
  5110. } Form = Init;
  5111. const unsigned NumForm = GNUCmpXchg + 1;
  5112. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  5113. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  5114. // where:
  5115. // C is an appropriate type,
  5116. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  5117. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  5118. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  5119. // the int parameters are for orderings.
  5120. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  5121. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  5122. "need to update code for modified forms");
  5123. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  5124. AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
  5125. AtomicExpr::AO__atomic_load,
  5126. "need to update code for modified C11 atomics");
  5127. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  5128. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  5129. bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
  5130. Op <= AtomicExpr::AO__hip_atomic_fetch_max;
  5131. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  5132. Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
  5133. IsOpenCL;
  5134. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  5135. Op == AtomicExpr::AO__atomic_store_n ||
  5136. Op == AtomicExpr::AO__atomic_exchange_n ||
  5137. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  5138. bool IsAddSub = false;
  5139. switch (Op) {
  5140. case AtomicExpr::AO__c11_atomic_init:
  5141. case AtomicExpr::AO__opencl_atomic_init:
  5142. Form = Init;
  5143. break;
  5144. case AtomicExpr::AO__c11_atomic_load:
  5145. case AtomicExpr::AO__opencl_atomic_load:
  5146. case AtomicExpr::AO__hip_atomic_load:
  5147. case AtomicExpr::AO__atomic_load_n:
  5148. Form = Load;
  5149. break;
  5150. case AtomicExpr::AO__atomic_load:
  5151. Form = LoadCopy;
  5152. break;
  5153. case AtomicExpr::AO__c11_atomic_store:
  5154. case AtomicExpr::AO__opencl_atomic_store:
  5155. case AtomicExpr::AO__hip_atomic_store:
  5156. case AtomicExpr::AO__atomic_store:
  5157. case AtomicExpr::AO__atomic_store_n:
  5158. Form = Copy;
  5159. break;
  5160. case AtomicExpr::AO__hip_atomic_fetch_add:
  5161. case AtomicExpr::AO__hip_atomic_fetch_min:
  5162. case AtomicExpr::AO__hip_atomic_fetch_max:
  5163. case AtomicExpr::AO__c11_atomic_fetch_add:
  5164. case AtomicExpr::AO__c11_atomic_fetch_sub:
  5165. case AtomicExpr::AO__opencl_atomic_fetch_add:
  5166. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  5167. case AtomicExpr::AO__atomic_fetch_add:
  5168. case AtomicExpr::AO__atomic_fetch_sub:
  5169. case AtomicExpr::AO__atomic_add_fetch:
  5170. case AtomicExpr::AO__atomic_sub_fetch:
  5171. IsAddSub = true;
  5172. Form = Arithmetic;
  5173. break;
  5174. case AtomicExpr::AO__c11_atomic_fetch_and:
  5175. case AtomicExpr::AO__c11_atomic_fetch_or:
  5176. case AtomicExpr::AO__c11_atomic_fetch_xor:
  5177. case AtomicExpr::AO__hip_atomic_fetch_and:
  5178. case AtomicExpr::AO__hip_atomic_fetch_or:
  5179. case AtomicExpr::AO__hip_atomic_fetch_xor:
  5180. case AtomicExpr::AO__c11_atomic_fetch_nand:
  5181. case AtomicExpr::AO__opencl_atomic_fetch_and:
  5182. case AtomicExpr::AO__opencl_atomic_fetch_or:
  5183. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  5184. case AtomicExpr::AO__atomic_fetch_and:
  5185. case AtomicExpr::AO__atomic_fetch_or:
  5186. case AtomicExpr::AO__atomic_fetch_xor:
  5187. case AtomicExpr::AO__atomic_fetch_nand:
  5188. case AtomicExpr::AO__atomic_and_fetch:
  5189. case AtomicExpr::AO__atomic_or_fetch:
  5190. case AtomicExpr::AO__atomic_xor_fetch:
  5191. case AtomicExpr::AO__atomic_nand_fetch:
  5192. Form = Arithmetic;
  5193. break;
  5194. case AtomicExpr::AO__c11_atomic_fetch_min:
  5195. case AtomicExpr::AO__c11_atomic_fetch_max:
  5196. case AtomicExpr::AO__opencl_atomic_fetch_min:
  5197. case AtomicExpr::AO__opencl_atomic_fetch_max:
  5198. case AtomicExpr::AO__atomic_min_fetch:
  5199. case AtomicExpr::AO__atomic_max_fetch:
  5200. case AtomicExpr::AO__atomic_fetch_min:
  5201. case AtomicExpr::AO__atomic_fetch_max:
  5202. Form = Arithmetic;
  5203. break;
  5204. case AtomicExpr::AO__c11_atomic_exchange:
  5205. case AtomicExpr::AO__hip_atomic_exchange:
  5206. case AtomicExpr::AO__opencl_atomic_exchange:
  5207. case AtomicExpr::AO__atomic_exchange_n:
  5208. Form = Xchg;
  5209. break;
  5210. case AtomicExpr::AO__atomic_exchange:
  5211. Form = GNUXchg;
  5212. break;
  5213. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  5214. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  5215. case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
  5216. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  5217. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  5218. case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
  5219. Form = C11CmpXchg;
  5220. break;
  5221. case AtomicExpr::AO__atomic_compare_exchange:
  5222. case AtomicExpr::AO__atomic_compare_exchange_n:
  5223. Form = GNUCmpXchg;
  5224. break;
  5225. }
  5226. unsigned AdjustedNumArgs = NumArgs[Form];
  5227. if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
  5228. ++AdjustedNumArgs;
  5229. // Check we have the right number of arguments.
  5230. if (Args.size() < AdjustedNumArgs) {
  5231. Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
  5232. << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
  5233. << ExprRange;
  5234. return ExprError();
  5235. } else if (Args.size() > AdjustedNumArgs) {
  5236. Diag(Args[AdjustedNumArgs]->getBeginLoc(),
  5237. diag::err_typecheck_call_too_many_args)
  5238. << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
  5239. << ExprRange;
  5240. return ExprError();
  5241. }
  5242. // Inspect the first argument of the atomic operation.
  5243. Expr *Ptr = Args[0];
  5244. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  5245. if (ConvertedPtr.isInvalid())
  5246. return ExprError();
  5247. Ptr = ConvertedPtr.get();
  5248. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  5249. if (!pointerType) {
  5250. Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
  5251. << Ptr->getType() << Ptr->getSourceRange();
  5252. return ExprError();
  5253. }
  5254. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  5255. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  5256. QualType ValType = AtomTy; // 'C'
  5257. if (IsC11) {
  5258. if (!AtomTy->isAtomicType()) {
  5259. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
  5260. << Ptr->getType() << Ptr->getSourceRange();
  5261. return ExprError();
  5262. }
  5263. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  5264. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  5265. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
  5266. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  5267. << Ptr->getSourceRange();
  5268. return ExprError();
  5269. }
  5270. ValType = AtomTy->castAs<AtomicType>()->getValueType();
  5271. } else if (Form != Load && Form != LoadCopy) {
  5272. if (ValType.isConstQualified()) {
  5273. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
  5274. << Ptr->getType() << Ptr->getSourceRange();
  5275. return ExprError();
  5276. }
  5277. }
  5278. // For an arithmetic operation, the implied arithmetic must be well-formed.
  5279. if (Form == Arithmetic) {
  5280. // GCC does not enforce these rules for GNU atomics, but we do to help catch
  5281. // trivial type errors.
  5282. auto IsAllowedValueType = [&](QualType ValType) {
  5283. if (ValType->isIntegerType())
  5284. return true;
  5285. if (ValType->isPointerType())
  5286. return true;
  5287. if (!ValType->isFloatingType())
  5288. return false;
  5289. // LLVM Parser does not allow atomicrmw with x86_fp80 type.
  5290. if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
  5291. &Context.getTargetInfo().getLongDoubleFormat() ==
  5292. &llvm::APFloat::x87DoubleExtended())
  5293. return false;
  5294. return true;
  5295. };
  5296. if (IsAddSub && !IsAllowedValueType(ValType)) {
  5297. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
  5298. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  5299. return ExprError();
  5300. }
  5301. if (!IsAddSub && !ValType->isIntegerType()) {
  5302. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
  5303. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  5304. return ExprError();
  5305. }
  5306. if (IsC11 && ValType->isPointerType() &&
  5307. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  5308. diag::err_incomplete_type)) {
  5309. return ExprError();
  5310. }
  5311. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  5312. // For __atomic_*_n operations, the value type must be a scalar integral or
  5313. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  5314. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  5315. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  5316. return ExprError();
  5317. }
  5318. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  5319. !AtomTy->isScalarType()) {
  5320. // For GNU atomics, require a trivially-copyable type. This is not part of
  5321. // the GNU atomics specification but we enforce it for consistency with
  5322. // other atomics which generally all require a trivially-copyable type. This
  5323. // is because atomics just copy bits.
  5324. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
  5325. << Ptr->getType() << Ptr->getSourceRange();
  5326. return ExprError();
  5327. }
  5328. switch (ValType.getObjCLifetime()) {
  5329. case Qualifiers::OCL_None:
  5330. case Qualifiers::OCL_ExplicitNone:
  5331. // okay
  5332. break;
  5333. case Qualifiers::OCL_Weak:
  5334. case Qualifiers::OCL_Strong:
  5335. case Qualifiers::OCL_Autoreleasing:
  5336. // FIXME: Can this happen? By this point, ValType should be known
  5337. // to be trivially copyable.
  5338. Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
  5339. << ValType << Ptr->getSourceRange();
  5340. return ExprError();
  5341. }
  5342. // All atomic operations have an overload which takes a pointer to a volatile
  5343. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  5344. // into the result or the other operands. Similarly atomic_load takes a
  5345. // pointer to a const 'A'.
  5346. ValType.removeLocalVolatile();
  5347. ValType.removeLocalConst();
  5348. QualType ResultType = ValType;
  5349. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  5350. Form == Init)
  5351. ResultType = Context.VoidTy;
  5352. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  5353. ResultType = Context.BoolTy;
  5354. // The type of a parameter passed 'by value'. In the GNU atomics, such
  5355. // arguments are actually passed as pointers.
  5356. QualType ByValType = ValType; // 'CP'
  5357. bool IsPassedByAddress = false;
  5358. if (!IsC11 && !IsHIP && !IsN) {
  5359. ByValType = Ptr->getType();
  5360. IsPassedByAddress = true;
  5361. }
  5362. SmallVector<Expr *, 5> APIOrderedArgs;
  5363. if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
  5364. APIOrderedArgs.push_back(Args[0]);
  5365. switch (Form) {
  5366. case Init:
  5367. case Load:
  5368. APIOrderedArgs.push_back(Args[1]); // Val1/Order
  5369. break;
  5370. case LoadCopy:
  5371. case Copy:
  5372. case Arithmetic:
  5373. case Xchg:
  5374. APIOrderedArgs.push_back(Args[2]); // Val1
  5375. APIOrderedArgs.push_back(Args[1]); // Order
  5376. break;
  5377. case GNUXchg:
  5378. APIOrderedArgs.push_back(Args[2]); // Val1
  5379. APIOrderedArgs.push_back(Args[3]); // Val2
  5380. APIOrderedArgs.push_back(Args[1]); // Order
  5381. break;
  5382. case C11CmpXchg:
  5383. APIOrderedArgs.push_back(Args[2]); // Val1
  5384. APIOrderedArgs.push_back(Args[4]); // Val2
  5385. APIOrderedArgs.push_back(Args[1]); // Order
  5386. APIOrderedArgs.push_back(Args[3]); // OrderFail
  5387. break;
  5388. case GNUCmpXchg:
  5389. APIOrderedArgs.push_back(Args[2]); // Val1
  5390. APIOrderedArgs.push_back(Args[4]); // Val2
  5391. APIOrderedArgs.push_back(Args[5]); // Weak
  5392. APIOrderedArgs.push_back(Args[1]); // Order
  5393. APIOrderedArgs.push_back(Args[3]); // OrderFail
  5394. break;
  5395. }
  5396. } else
  5397. APIOrderedArgs.append(Args.begin(), Args.end());
  5398. // The first argument's non-CV pointer type is used to deduce the type of
  5399. // subsequent arguments, except for:
  5400. // - weak flag (always converted to bool)
  5401. // - memory order (always converted to int)
  5402. // - scope (always converted to int)
  5403. for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
  5404. QualType Ty;
  5405. if (i < NumVals[Form] + 1) {
  5406. switch (i) {
  5407. case 0:
  5408. // The first argument is always a pointer. It has a fixed type.
  5409. // It is always dereferenced, a nullptr is undefined.
  5410. CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
  5411. // Nothing else to do: we already know all we want about this pointer.
  5412. continue;
  5413. case 1:
  5414. // The second argument is the non-atomic operand. For arithmetic, this
  5415. // is always passed by value, and for a compare_exchange it is always
  5416. // passed by address. For the rest, GNU uses by-address and C11 uses
  5417. // by-value.
  5418. assert(Form != Load);
  5419. if (Form == Arithmetic && ValType->isPointerType())
  5420. Ty = Context.getPointerDiffType();
  5421. else if (Form == Init || Form == Arithmetic)
  5422. Ty = ValType;
  5423. else if (Form == Copy || Form == Xchg) {
  5424. if (IsPassedByAddress) {
  5425. // The value pointer is always dereferenced, a nullptr is undefined.
  5426. CheckNonNullArgument(*this, APIOrderedArgs[i],
  5427. ExprRange.getBegin());
  5428. }
  5429. Ty = ByValType;
  5430. } else {
  5431. Expr *ValArg = APIOrderedArgs[i];
  5432. // The value pointer is always dereferenced, a nullptr is undefined.
  5433. CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
  5434. LangAS AS = LangAS::Default;
  5435. // Keep address space of non-atomic pointer type.
  5436. if (const PointerType *PtrTy =
  5437. ValArg->getType()->getAs<PointerType>()) {
  5438. AS = PtrTy->getPointeeType().getAddressSpace();
  5439. }
  5440. Ty = Context.getPointerType(
  5441. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  5442. }
  5443. break;
  5444. case 2:
  5445. // The third argument to compare_exchange / GNU exchange is the desired
  5446. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  5447. if (IsPassedByAddress)
  5448. CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
  5449. Ty = ByValType;
  5450. break;
  5451. case 3:
  5452. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  5453. Ty = Context.BoolTy;
  5454. break;
  5455. }
  5456. } else {
  5457. // The order(s) and scope are always converted to int.
  5458. Ty = Context.IntTy;
  5459. }
  5460. InitializedEntity Entity =
  5461. InitializedEntity::InitializeParameter(Context, Ty, false);
  5462. ExprResult Arg = APIOrderedArgs[i];
  5463. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5464. if (Arg.isInvalid())
  5465. return true;
  5466. APIOrderedArgs[i] = Arg.get();
  5467. }
  5468. // Permute the arguments into a 'consistent' order.
  5469. SmallVector<Expr*, 5> SubExprs;
  5470. SubExprs.push_back(Ptr);
  5471. switch (Form) {
  5472. case Init:
  5473. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  5474. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  5475. break;
  5476. case Load:
  5477. SubExprs.push_back(APIOrderedArgs[1]); // Order
  5478. break;
  5479. case LoadCopy:
  5480. case Copy:
  5481. case Arithmetic:
  5482. case Xchg:
  5483. SubExprs.push_back(APIOrderedArgs[2]); // Order
  5484. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  5485. break;
  5486. case GNUXchg:
  5487. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  5488. SubExprs.push_back(APIOrderedArgs[3]); // Order
  5489. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  5490. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  5491. break;
  5492. case C11CmpXchg:
  5493. SubExprs.push_back(APIOrderedArgs[3]); // Order
  5494. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  5495. SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
  5496. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  5497. break;
  5498. case GNUCmpXchg:
  5499. SubExprs.push_back(APIOrderedArgs[4]); // Order
  5500. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  5501. SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
  5502. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  5503. SubExprs.push_back(APIOrderedArgs[3]); // Weak
  5504. break;
  5505. }
  5506. if (SubExprs.size() >= 2 && Form != Init) {
  5507. if (Optional<llvm::APSInt> Result =
  5508. SubExprs[1]->getIntegerConstantExpr(Context))
  5509. if (!isValidOrderingForOp(Result->getSExtValue(), Op))
  5510. Diag(SubExprs[1]->getBeginLoc(),
  5511. diag::warn_atomic_op_has_invalid_memory_order)
  5512. << SubExprs[1]->getSourceRange();
  5513. }
  5514. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  5515. auto *Scope = Args[Args.size() - 1];
  5516. if (Optional<llvm::APSInt> Result =
  5517. Scope->getIntegerConstantExpr(Context)) {
  5518. if (!ScopeModel->isValid(Result->getZExtValue()))
  5519. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  5520. << Scope->getSourceRange();
  5521. }
  5522. SubExprs.push_back(Scope);
  5523. }
  5524. AtomicExpr *AE = new (Context)
  5525. AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
  5526. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  5527. Op == AtomicExpr::AO__c11_atomic_store ||
  5528. Op == AtomicExpr::AO__opencl_atomic_load ||
  5529. Op == AtomicExpr::AO__hip_atomic_load ||
  5530. Op == AtomicExpr::AO__opencl_atomic_store ||
  5531. Op == AtomicExpr::AO__hip_atomic_store) &&
  5532. Context.AtomicUsesUnsupportedLibcall(AE))
  5533. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  5534. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  5535. Op == AtomicExpr::AO__opencl_atomic_load ||
  5536. Op == AtomicExpr::AO__hip_atomic_load)
  5537. ? 0
  5538. : 1);
  5539. if (ValType->isBitIntType()) {
  5540. Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
  5541. return ExprError();
  5542. }
  5543. return AE;
  5544. }
  5545. /// checkBuiltinArgument - Given a call to a builtin function, perform
  5546. /// normal type-checking on the given argument, updating the call in
  5547. /// place. This is useful when a builtin function requires custom
  5548. /// type-checking for some of its arguments but not necessarily all of
  5549. /// them.
  5550. ///
  5551. /// Returns true on error.
  5552. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  5553. FunctionDecl *Fn = E->getDirectCallee();
  5554. assert(Fn && "builtin call without direct callee!");
  5555. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  5556. InitializedEntity Entity =
  5557. InitializedEntity::InitializeParameter(S.Context, Param);
  5558. ExprResult Arg = E->getArg(0);
  5559. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5560. if (Arg.isInvalid())
  5561. return true;
  5562. E->setArg(ArgIndex, Arg.get());
  5563. return false;
  5564. }
  5565. /// We have a call to a function like __sync_fetch_and_add, which is an
  5566. /// overloaded function based on the pointer type of its first argument.
  5567. /// The main BuildCallExpr routines have already promoted the types of
  5568. /// arguments because all of these calls are prototyped as void(...).
  5569. ///
  5570. /// This function goes through and does final semantic checking for these
  5571. /// builtins, as well as generating any warnings.
  5572. ExprResult
  5573. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  5574. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  5575. Expr *Callee = TheCall->getCallee();
  5576. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  5577. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5578. // Ensure that we have at least one argument to do type inference from.
  5579. if (TheCall->getNumArgs() < 1) {
  5580. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  5581. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  5582. return ExprError();
  5583. }
  5584. // Inspect the first argument of the atomic builtin. This should always be
  5585. // a pointer type, whose element is an integral scalar or pointer type.
  5586. // Because it is a pointer type, we don't have to worry about any implicit
  5587. // casts here.
  5588. // FIXME: We don't allow floating point scalars as input.
  5589. Expr *FirstArg = TheCall->getArg(0);
  5590. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  5591. if (FirstArgResult.isInvalid())
  5592. return ExprError();
  5593. FirstArg = FirstArgResult.get();
  5594. TheCall->setArg(0, FirstArg);
  5595. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  5596. if (!pointerType) {
  5597. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  5598. << FirstArg->getType() << FirstArg->getSourceRange();
  5599. return ExprError();
  5600. }
  5601. QualType ValType = pointerType->getPointeeType();
  5602. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  5603. !ValType->isBlockPointerType()) {
  5604. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  5605. << FirstArg->getType() << FirstArg->getSourceRange();
  5606. return ExprError();
  5607. }
  5608. if (ValType.isConstQualified()) {
  5609. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  5610. << FirstArg->getType() << FirstArg->getSourceRange();
  5611. return ExprError();
  5612. }
  5613. switch (ValType.getObjCLifetime()) {
  5614. case Qualifiers::OCL_None:
  5615. case Qualifiers::OCL_ExplicitNone:
  5616. // okay
  5617. break;
  5618. case Qualifiers::OCL_Weak:
  5619. case Qualifiers::OCL_Strong:
  5620. case Qualifiers::OCL_Autoreleasing:
  5621. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  5622. << ValType << FirstArg->getSourceRange();
  5623. return ExprError();
  5624. }
  5625. // Strip any qualifiers off ValType.
  5626. ValType = ValType.getUnqualifiedType();
  5627. // The majority of builtins return a value, but a few have special return
  5628. // types, so allow them to override appropriately below.
  5629. QualType ResultType = ValType;
  5630. // We need to figure out which concrete builtin this maps onto. For example,
  5631. // __sync_fetch_and_add with a 2 byte object turns into
  5632. // __sync_fetch_and_add_2.
  5633. #define BUILTIN_ROW(x) \
  5634. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  5635. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  5636. static const unsigned BuiltinIndices[][5] = {
  5637. BUILTIN_ROW(__sync_fetch_and_add),
  5638. BUILTIN_ROW(__sync_fetch_and_sub),
  5639. BUILTIN_ROW(__sync_fetch_and_or),
  5640. BUILTIN_ROW(__sync_fetch_and_and),
  5641. BUILTIN_ROW(__sync_fetch_and_xor),
  5642. BUILTIN_ROW(__sync_fetch_and_nand),
  5643. BUILTIN_ROW(__sync_add_and_fetch),
  5644. BUILTIN_ROW(__sync_sub_and_fetch),
  5645. BUILTIN_ROW(__sync_and_and_fetch),
  5646. BUILTIN_ROW(__sync_or_and_fetch),
  5647. BUILTIN_ROW(__sync_xor_and_fetch),
  5648. BUILTIN_ROW(__sync_nand_and_fetch),
  5649. BUILTIN_ROW(__sync_val_compare_and_swap),
  5650. BUILTIN_ROW(__sync_bool_compare_and_swap),
  5651. BUILTIN_ROW(__sync_lock_test_and_set),
  5652. BUILTIN_ROW(__sync_lock_release),
  5653. BUILTIN_ROW(__sync_swap)
  5654. };
  5655. #undef BUILTIN_ROW
  5656. // Determine the index of the size.
  5657. unsigned SizeIndex;
  5658. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  5659. case 1: SizeIndex = 0; break;
  5660. case 2: SizeIndex = 1; break;
  5661. case 4: SizeIndex = 2; break;
  5662. case 8: SizeIndex = 3; break;
  5663. case 16: SizeIndex = 4; break;
  5664. default:
  5665. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  5666. << FirstArg->getType() << FirstArg->getSourceRange();
  5667. return ExprError();
  5668. }
  5669. // Each of these builtins has one pointer argument, followed by some number of
  5670. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  5671. // that we ignore. Find out which row of BuiltinIndices to read from as well
  5672. // as the number of fixed args.
  5673. unsigned BuiltinID = FDecl->getBuiltinID();
  5674. unsigned BuiltinIndex, NumFixed = 1;
  5675. bool WarnAboutSemanticsChange = false;
  5676. switch (BuiltinID) {
  5677. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  5678. case Builtin::BI__sync_fetch_and_add:
  5679. case Builtin::BI__sync_fetch_and_add_1:
  5680. case Builtin::BI__sync_fetch_and_add_2:
  5681. case Builtin::BI__sync_fetch_and_add_4:
  5682. case Builtin::BI__sync_fetch_and_add_8:
  5683. case Builtin::BI__sync_fetch_and_add_16:
  5684. BuiltinIndex = 0;
  5685. break;
  5686. case Builtin::BI__sync_fetch_and_sub:
  5687. case Builtin::BI__sync_fetch_and_sub_1:
  5688. case Builtin::BI__sync_fetch_and_sub_2:
  5689. case Builtin::BI__sync_fetch_and_sub_4:
  5690. case Builtin::BI__sync_fetch_and_sub_8:
  5691. case Builtin::BI__sync_fetch_and_sub_16:
  5692. BuiltinIndex = 1;
  5693. break;
  5694. case Builtin::BI__sync_fetch_and_or:
  5695. case Builtin::BI__sync_fetch_and_or_1:
  5696. case Builtin::BI__sync_fetch_and_or_2:
  5697. case Builtin::BI__sync_fetch_and_or_4:
  5698. case Builtin::BI__sync_fetch_and_or_8:
  5699. case Builtin::BI__sync_fetch_and_or_16:
  5700. BuiltinIndex = 2;
  5701. break;
  5702. case Builtin::BI__sync_fetch_and_and:
  5703. case Builtin::BI__sync_fetch_and_and_1:
  5704. case Builtin::BI__sync_fetch_and_and_2:
  5705. case Builtin::BI__sync_fetch_and_and_4:
  5706. case Builtin::BI__sync_fetch_and_and_8:
  5707. case Builtin::BI__sync_fetch_and_and_16:
  5708. BuiltinIndex = 3;
  5709. break;
  5710. case Builtin::BI__sync_fetch_and_xor:
  5711. case Builtin::BI__sync_fetch_and_xor_1:
  5712. case Builtin::BI__sync_fetch_and_xor_2:
  5713. case Builtin::BI__sync_fetch_and_xor_4:
  5714. case Builtin::BI__sync_fetch_and_xor_8:
  5715. case Builtin::BI__sync_fetch_and_xor_16:
  5716. BuiltinIndex = 4;
  5717. break;
  5718. case Builtin::BI__sync_fetch_and_nand:
  5719. case Builtin::BI__sync_fetch_and_nand_1:
  5720. case Builtin::BI__sync_fetch_and_nand_2:
  5721. case Builtin::BI__sync_fetch_and_nand_4:
  5722. case Builtin::BI__sync_fetch_and_nand_8:
  5723. case Builtin::BI__sync_fetch_and_nand_16:
  5724. BuiltinIndex = 5;
  5725. WarnAboutSemanticsChange = true;
  5726. break;
  5727. case Builtin::BI__sync_add_and_fetch:
  5728. case Builtin::BI__sync_add_and_fetch_1:
  5729. case Builtin::BI__sync_add_and_fetch_2:
  5730. case Builtin::BI__sync_add_and_fetch_4:
  5731. case Builtin::BI__sync_add_and_fetch_8:
  5732. case Builtin::BI__sync_add_and_fetch_16:
  5733. BuiltinIndex = 6;
  5734. break;
  5735. case Builtin::BI__sync_sub_and_fetch:
  5736. case Builtin::BI__sync_sub_and_fetch_1:
  5737. case Builtin::BI__sync_sub_and_fetch_2:
  5738. case Builtin::BI__sync_sub_and_fetch_4:
  5739. case Builtin::BI__sync_sub_and_fetch_8:
  5740. case Builtin::BI__sync_sub_and_fetch_16:
  5741. BuiltinIndex = 7;
  5742. break;
  5743. case Builtin::BI__sync_and_and_fetch:
  5744. case Builtin::BI__sync_and_and_fetch_1:
  5745. case Builtin::BI__sync_and_and_fetch_2:
  5746. case Builtin::BI__sync_and_and_fetch_4:
  5747. case Builtin::BI__sync_and_and_fetch_8:
  5748. case Builtin::BI__sync_and_and_fetch_16:
  5749. BuiltinIndex = 8;
  5750. break;
  5751. case Builtin::BI__sync_or_and_fetch:
  5752. case Builtin::BI__sync_or_and_fetch_1:
  5753. case Builtin::BI__sync_or_and_fetch_2:
  5754. case Builtin::BI__sync_or_and_fetch_4:
  5755. case Builtin::BI__sync_or_and_fetch_8:
  5756. case Builtin::BI__sync_or_and_fetch_16:
  5757. BuiltinIndex = 9;
  5758. break;
  5759. case Builtin::BI__sync_xor_and_fetch:
  5760. case Builtin::BI__sync_xor_and_fetch_1:
  5761. case Builtin::BI__sync_xor_and_fetch_2:
  5762. case Builtin::BI__sync_xor_and_fetch_4:
  5763. case Builtin::BI__sync_xor_and_fetch_8:
  5764. case Builtin::BI__sync_xor_and_fetch_16:
  5765. BuiltinIndex = 10;
  5766. break;
  5767. case Builtin::BI__sync_nand_and_fetch:
  5768. case Builtin::BI__sync_nand_and_fetch_1:
  5769. case Builtin::BI__sync_nand_and_fetch_2:
  5770. case Builtin::BI__sync_nand_and_fetch_4:
  5771. case Builtin::BI__sync_nand_and_fetch_8:
  5772. case Builtin::BI__sync_nand_and_fetch_16:
  5773. BuiltinIndex = 11;
  5774. WarnAboutSemanticsChange = true;
  5775. break;
  5776. case Builtin::BI__sync_val_compare_and_swap:
  5777. case Builtin::BI__sync_val_compare_and_swap_1:
  5778. case Builtin::BI__sync_val_compare_and_swap_2:
  5779. case Builtin::BI__sync_val_compare_and_swap_4:
  5780. case Builtin::BI__sync_val_compare_and_swap_8:
  5781. case Builtin::BI__sync_val_compare_and_swap_16:
  5782. BuiltinIndex = 12;
  5783. NumFixed = 2;
  5784. break;
  5785. case Builtin::BI__sync_bool_compare_and_swap:
  5786. case Builtin::BI__sync_bool_compare_and_swap_1:
  5787. case Builtin::BI__sync_bool_compare_and_swap_2:
  5788. case Builtin::BI__sync_bool_compare_and_swap_4:
  5789. case Builtin::BI__sync_bool_compare_and_swap_8:
  5790. case Builtin::BI__sync_bool_compare_and_swap_16:
  5791. BuiltinIndex = 13;
  5792. NumFixed = 2;
  5793. ResultType = Context.BoolTy;
  5794. break;
  5795. case Builtin::BI__sync_lock_test_and_set:
  5796. case Builtin::BI__sync_lock_test_and_set_1:
  5797. case Builtin::BI__sync_lock_test_and_set_2:
  5798. case Builtin::BI__sync_lock_test_and_set_4:
  5799. case Builtin::BI__sync_lock_test_and_set_8:
  5800. case Builtin::BI__sync_lock_test_and_set_16:
  5801. BuiltinIndex = 14;
  5802. break;
  5803. case Builtin::BI__sync_lock_release:
  5804. case Builtin::BI__sync_lock_release_1:
  5805. case Builtin::BI__sync_lock_release_2:
  5806. case Builtin::BI__sync_lock_release_4:
  5807. case Builtin::BI__sync_lock_release_8:
  5808. case Builtin::BI__sync_lock_release_16:
  5809. BuiltinIndex = 15;
  5810. NumFixed = 0;
  5811. ResultType = Context.VoidTy;
  5812. break;
  5813. case Builtin::BI__sync_swap:
  5814. case Builtin::BI__sync_swap_1:
  5815. case Builtin::BI__sync_swap_2:
  5816. case Builtin::BI__sync_swap_4:
  5817. case Builtin::BI__sync_swap_8:
  5818. case Builtin::BI__sync_swap_16:
  5819. BuiltinIndex = 16;
  5820. break;
  5821. }
  5822. // Now that we know how many fixed arguments we expect, first check that we
  5823. // have at least that many.
  5824. if (TheCall->getNumArgs() < 1+NumFixed) {
  5825. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  5826. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  5827. << Callee->getSourceRange();
  5828. return ExprError();
  5829. }
  5830. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  5831. << Callee->getSourceRange();
  5832. if (WarnAboutSemanticsChange) {
  5833. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  5834. << Callee->getSourceRange();
  5835. }
  5836. // Get the decl for the concrete builtin from this, we can tell what the
  5837. // concrete integer type we should convert to is.
  5838. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  5839. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  5840. FunctionDecl *NewBuiltinDecl;
  5841. if (NewBuiltinID == BuiltinID)
  5842. NewBuiltinDecl = FDecl;
  5843. else {
  5844. // Perform builtin lookup to avoid redeclaring it.
  5845. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  5846. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  5847. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  5848. assert(Res.getFoundDecl());
  5849. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  5850. if (!NewBuiltinDecl)
  5851. return ExprError();
  5852. }
  5853. // The first argument --- the pointer --- has a fixed type; we
  5854. // deduce the types of the rest of the arguments accordingly. Walk
  5855. // the remaining arguments, converting them to the deduced value type.
  5856. for (unsigned i = 0; i != NumFixed; ++i) {
  5857. ExprResult Arg = TheCall->getArg(i+1);
  5858. // GCC does an implicit conversion to the pointer or integer ValType. This
  5859. // can fail in some cases (1i -> int**), check for this error case now.
  5860. // Initialize the argument.
  5861. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5862. ValType, /*consume*/ false);
  5863. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5864. if (Arg.isInvalid())
  5865. return ExprError();
  5866. // Okay, we have something that *can* be converted to the right type. Check
  5867. // to see if there is a potentially weird extension going on here. This can
  5868. // happen when you do an atomic operation on something like an char* and
  5869. // pass in 42. The 42 gets converted to char. This is even more strange
  5870. // for things like 45.123 -> char, etc.
  5871. // FIXME: Do this check.
  5872. TheCall->setArg(i+1, Arg.get());
  5873. }
  5874. // Create a new DeclRefExpr to refer to the new decl.
  5875. DeclRefExpr *NewDRE = DeclRefExpr::Create(
  5876. Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
  5877. /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
  5878. DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
  5879. // Set the callee in the CallExpr.
  5880. // FIXME: This loses syntactic information.
  5881. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  5882. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  5883. CK_BuiltinFnToFnPtr);
  5884. TheCall->setCallee(PromotedCall.get());
  5885. // Change the result type of the call to match the original value type. This
  5886. // is arbitrary, but the codegen for these builtins ins design to handle it
  5887. // gracefully.
  5888. TheCall->setType(ResultType);
  5889. // Prohibit problematic uses of bit-precise integer types with atomic
  5890. // builtins. The arguments would have already been converted to the first
  5891. // argument's type, so only need to check the first argument.
  5892. const auto *BitIntValType = ValType->getAs<BitIntType>();
  5893. if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
  5894. Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
  5895. return ExprError();
  5896. }
  5897. return TheCallResult;
  5898. }
  5899. /// SemaBuiltinNontemporalOverloaded - We have a call to
  5900. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  5901. /// overloaded function based on the pointer type of its last argument.
  5902. ///
  5903. /// This function goes through and does final semantic checking for these
  5904. /// builtins.
  5905. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  5906. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  5907. DeclRefExpr *DRE =
  5908. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5909. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5910. unsigned BuiltinID = FDecl->getBuiltinID();
  5911. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  5912. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  5913. "Unexpected nontemporal load/store builtin!");
  5914. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  5915. unsigned numArgs = isStore ? 2 : 1;
  5916. // Ensure that we have the proper number of arguments.
  5917. if (checkArgCount(*this, TheCall, numArgs))
  5918. return ExprError();
  5919. // Inspect the last argument of the nontemporal builtin. This should always
  5920. // be a pointer type, from which we imply the type of the memory access.
  5921. // Because it is a pointer type, we don't have to worry about any implicit
  5922. // casts here.
  5923. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  5924. ExprResult PointerArgResult =
  5925. DefaultFunctionArrayLvalueConversion(PointerArg);
  5926. if (PointerArgResult.isInvalid())
  5927. return ExprError();
  5928. PointerArg = PointerArgResult.get();
  5929. TheCall->setArg(numArgs - 1, PointerArg);
  5930. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  5931. if (!pointerType) {
  5932. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  5933. << PointerArg->getType() << PointerArg->getSourceRange();
  5934. return ExprError();
  5935. }
  5936. QualType ValType = pointerType->getPointeeType();
  5937. // Strip any qualifiers off ValType.
  5938. ValType = ValType.getUnqualifiedType();
  5939. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  5940. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  5941. !ValType->isVectorType()) {
  5942. Diag(DRE->getBeginLoc(),
  5943. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  5944. << PointerArg->getType() << PointerArg->getSourceRange();
  5945. return ExprError();
  5946. }
  5947. if (!isStore) {
  5948. TheCall->setType(ValType);
  5949. return TheCallResult;
  5950. }
  5951. ExprResult ValArg = TheCall->getArg(0);
  5952. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5953. Context, ValType, /*consume*/ false);
  5954. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  5955. if (ValArg.isInvalid())
  5956. return ExprError();
  5957. TheCall->setArg(0, ValArg.get());
  5958. TheCall->setType(Context.VoidTy);
  5959. return TheCallResult;
  5960. }
  5961. /// CheckObjCString - Checks that the argument to the builtin
  5962. /// CFString constructor is correct
  5963. /// Note: It might also make sense to do the UTF-16 conversion here (would
  5964. /// simplify the backend).
  5965. bool Sema::CheckObjCString(Expr *Arg) {
  5966. Arg = Arg->IgnoreParenCasts();
  5967. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  5968. if (!Literal || !Literal->isAscii()) {
  5969. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  5970. << Arg->getSourceRange();
  5971. return true;
  5972. }
  5973. if (Literal->containsNonAsciiOrNull()) {
  5974. StringRef String = Literal->getString();
  5975. unsigned NumBytes = String.size();
  5976. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  5977. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  5978. llvm::UTF16 *ToPtr = &ToBuf[0];
  5979. llvm::ConversionResult Result =
  5980. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  5981. ToPtr + NumBytes, llvm::strictConversion);
  5982. // Check for conversion failure.
  5983. if (Result != llvm::conversionOK)
  5984. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  5985. << Arg->getSourceRange();
  5986. }
  5987. return false;
  5988. }
  5989. /// CheckObjCString - Checks that the format string argument to the os_log()
  5990. /// and os_trace() functions is correct, and converts it to const char *.
  5991. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  5992. Arg = Arg->IgnoreParenCasts();
  5993. auto *Literal = dyn_cast<StringLiteral>(Arg);
  5994. if (!Literal) {
  5995. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  5996. Literal = ObjcLiteral->getString();
  5997. }
  5998. }
  5999. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  6000. return ExprError(
  6001. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  6002. << Arg->getSourceRange());
  6003. }
  6004. ExprResult Result(Literal);
  6005. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  6006. InitializedEntity Entity =
  6007. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  6008. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  6009. return Result;
  6010. }
  6011. /// Check that the user is calling the appropriate va_start builtin for the
  6012. /// target and calling convention.
  6013. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  6014. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  6015. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  6016. bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
  6017. TT.getArch() == llvm::Triple::aarch64_32);
  6018. bool IsWindows = TT.isOSWindows();
  6019. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  6020. if (IsX64 || IsAArch64) {
  6021. CallingConv CC = CC_C;
  6022. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  6023. CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  6024. if (IsMSVAStart) {
  6025. // Don't allow this in System V ABI functions.
  6026. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  6027. return S.Diag(Fn->getBeginLoc(),
  6028. diag::err_ms_va_start_used_in_sysv_function);
  6029. } else {
  6030. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  6031. // On x64 Windows, don't allow this in System V ABI functions.
  6032. // (Yes, that means there's no corresponding way to support variadic
  6033. // System V ABI functions on Windows.)
  6034. if ((IsWindows && CC == CC_X86_64SysV) ||
  6035. (!IsWindows && CC == CC_Win64))
  6036. return S.Diag(Fn->getBeginLoc(),
  6037. diag::err_va_start_used_in_wrong_abi_function)
  6038. << !IsWindows;
  6039. }
  6040. return false;
  6041. }
  6042. if (IsMSVAStart)
  6043. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  6044. return false;
  6045. }
  6046. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  6047. ParmVarDecl **LastParam = nullptr) {
  6048. // Determine whether the current function, block, or obj-c method is variadic
  6049. // and get its parameter list.
  6050. bool IsVariadic = false;
  6051. ArrayRef<ParmVarDecl *> Params;
  6052. DeclContext *Caller = S.CurContext;
  6053. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  6054. IsVariadic = Block->isVariadic();
  6055. Params = Block->parameters();
  6056. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  6057. IsVariadic = FD->isVariadic();
  6058. Params = FD->parameters();
  6059. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  6060. IsVariadic = MD->isVariadic();
  6061. // FIXME: This isn't correct for methods (results in bogus warning).
  6062. Params = MD->parameters();
  6063. } else if (isa<CapturedDecl>(Caller)) {
  6064. // We don't support va_start in a CapturedDecl.
  6065. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  6066. return true;
  6067. } else {
  6068. // This must be some other declcontext that parses exprs.
  6069. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  6070. return true;
  6071. }
  6072. if (!IsVariadic) {
  6073. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  6074. return true;
  6075. }
  6076. if (LastParam)
  6077. *LastParam = Params.empty() ? nullptr : Params.back();
  6078. return false;
  6079. }
  6080. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  6081. /// for validity. Emit an error and return true on failure; return false
  6082. /// on success.
  6083. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  6084. Expr *Fn = TheCall->getCallee();
  6085. if (checkVAStartABI(*this, BuiltinID, Fn))
  6086. return true;
  6087. if (checkArgCount(*this, TheCall, 2))
  6088. return true;
  6089. // Type-check the first argument normally.
  6090. if (checkBuiltinArgument(*this, TheCall, 0))
  6091. return true;
  6092. // Check that the current function is variadic, and get its last parameter.
  6093. ParmVarDecl *LastParam;
  6094. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  6095. return true;
  6096. // Verify that the second argument to the builtin is the last argument of the
  6097. // current function or method.
  6098. bool SecondArgIsLastNamedArgument = false;
  6099. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  6100. // These are valid if SecondArgIsLastNamedArgument is false after the next
  6101. // block.
  6102. QualType Type;
  6103. SourceLocation ParamLoc;
  6104. bool IsCRegister = false;
  6105. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  6106. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  6107. SecondArgIsLastNamedArgument = PV == LastParam;
  6108. Type = PV->getType();
  6109. ParamLoc = PV->getLocation();
  6110. IsCRegister =
  6111. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  6112. }
  6113. }
  6114. if (!SecondArgIsLastNamedArgument)
  6115. Diag(TheCall->getArg(1)->getBeginLoc(),
  6116. diag::warn_second_arg_of_va_start_not_last_named_param);
  6117. else if (IsCRegister || Type->isReferenceType() ||
  6118. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  6119. // Promotable integers are UB, but enumerations need a bit of
  6120. // extra checking to see what their promotable type actually is.
  6121. if (!Type->isPromotableIntegerType())
  6122. return false;
  6123. if (!Type->isEnumeralType())
  6124. return true;
  6125. const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
  6126. return !(ED &&
  6127. Context.typesAreCompatible(ED->getPromotionType(), Type));
  6128. }()) {
  6129. unsigned Reason = 0;
  6130. if (Type->isReferenceType()) Reason = 1;
  6131. else if (IsCRegister) Reason = 2;
  6132. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  6133. Diag(ParamLoc, diag::note_parameter_type) << Type;
  6134. }
  6135. TheCall->setType(Context.VoidTy);
  6136. return false;
  6137. }
  6138. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  6139. auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
  6140. const LangOptions &LO = getLangOpts();
  6141. if (LO.CPlusPlus)
  6142. return Arg->getType()
  6143. .getCanonicalType()
  6144. .getTypePtr()
  6145. ->getPointeeType()
  6146. .withoutLocalFastQualifiers() == Context.CharTy;
  6147. // In C, allow aliasing through `char *`, this is required for AArch64 at
  6148. // least.
  6149. return true;
  6150. };
  6151. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  6152. // const char *named_addr);
  6153. Expr *Func = Call->getCallee();
  6154. if (Call->getNumArgs() < 3)
  6155. return Diag(Call->getEndLoc(),
  6156. diag::err_typecheck_call_too_few_args_at_least)
  6157. << 0 /*function call*/ << 3 << Call->getNumArgs();
  6158. // Type-check the first argument normally.
  6159. if (checkBuiltinArgument(*this, Call, 0))
  6160. return true;
  6161. // Check that the current function is variadic.
  6162. if (checkVAStartIsInVariadicFunction(*this, Func))
  6163. return true;
  6164. // __va_start on Windows does not validate the parameter qualifiers
  6165. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  6166. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  6167. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  6168. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  6169. const QualType &ConstCharPtrTy =
  6170. Context.getPointerType(Context.CharTy.withConst());
  6171. if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
  6172. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  6173. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  6174. << 0 /* qualifier difference */
  6175. << 3 /* parameter mismatch */
  6176. << 2 << Arg1->getType() << ConstCharPtrTy;
  6177. const QualType SizeTy = Context.getSizeType();
  6178. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  6179. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  6180. << Arg2->getType() << SizeTy << 1 /* different class */
  6181. << 0 /* qualifier difference */
  6182. << 3 /* parameter mismatch */
  6183. << 3 << Arg2->getType() << SizeTy;
  6184. return false;
  6185. }
  6186. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  6187. /// friends. This is declared to take (...), so we have to check everything.
  6188. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  6189. if (checkArgCount(*this, TheCall, 2))
  6190. return true;
  6191. ExprResult OrigArg0 = TheCall->getArg(0);
  6192. ExprResult OrigArg1 = TheCall->getArg(1);
  6193. // Do standard promotions between the two arguments, returning their common
  6194. // type.
  6195. QualType Res = UsualArithmeticConversions(
  6196. OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
  6197. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  6198. return true;
  6199. // Make sure any conversions are pushed back into the call; this is
  6200. // type safe since unordered compare builtins are declared as "_Bool
  6201. // foo(...)".
  6202. TheCall->setArg(0, OrigArg0.get());
  6203. TheCall->setArg(1, OrigArg1.get());
  6204. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  6205. return false;
  6206. // If the common type isn't a real floating type, then the arguments were
  6207. // invalid for this operation.
  6208. if (Res.isNull() || !Res->isRealFloatingType())
  6209. return Diag(OrigArg0.get()->getBeginLoc(),
  6210. diag::err_typecheck_call_invalid_ordered_compare)
  6211. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  6212. << SourceRange(OrigArg0.get()->getBeginLoc(),
  6213. OrigArg1.get()->getEndLoc());
  6214. return false;
  6215. }
  6216. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  6217. /// __builtin_isnan and friends. This is declared to take (...), so we have
  6218. /// to check everything. We expect the last argument to be a floating point
  6219. /// value.
  6220. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  6221. if (checkArgCount(*this, TheCall, NumArgs))
  6222. return true;
  6223. // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
  6224. // on all preceding parameters just being int. Try all of those.
  6225. for (unsigned i = 0; i < NumArgs - 1; ++i) {
  6226. Expr *Arg = TheCall->getArg(i);
  6227. if (Arg->isTypeDependent())
  6228. return false;
  6229. ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
  6230. if (Res.isInvalid())
  6231. return true;
  6232. TheCall->setArg(i, Res.get());
  6233. }
  6234. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  6235. if (OrigArg->isTypeDependent())
  6236. return false;
  6237. // Usual Unary Conversions will convert half to float, which we want for
  6238. // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
  6239. // type how it is, but do normal L->Rvalue conversions.
  6240. if (Context.getTargetInfo().useFP16ConversionIntrinsics())
  6241. OrigArg = UsualUnaryConversions(OrigArg).get();
  6242. else
  6243. OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
  6244. TheCall->setArg(NumArgs - 1, OrigArg);
  6245. // This operation requires a non-_Complex floating-point number.
  6246. if (!OrigArg->getType()->isRealFloatingType())
  6247. return Diag(OrigArg->getBeginLoc(),
  6248. diag::err_typecheck_call_invalid_unary_fp)
  6249. << OrigArg->getType() << OrigArg->getSourceRange();
  6250. return false;
  6251. }
  6252. /// Perform semantic analysis for a call to __builtin_complex.
  6253. bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
  6254. if (checkArgCount(*this, TheCall, 2))
  6255. return true;
  6256. bool Dependent = false;
  6257. for (unsigned I = 0; I != 2; ++I) {
  6258. Expr *Arg = TheCall->getArg(I);
  6259. QualType T = Arg->getType();
  6260. if (T->isDependentType()) {
  6261. Dependent = true;
  6262. continue;
  6263. }
  6264. // Despite supporting _Complex int, GCC requires a real floating point type
  6265. // for the operands of __builtin_complex.
  6266. if (!T->isRealFloatingType()) {
  6267. return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
  6268. << Arg->getType() << Arg->getSourceRange();
  6269. }
  6270. ExprResult Converted = DefaultLvalueConversion(Arg);
  6271. if (Converted.isInvalid())
  6272. return true;
  6273. TheCall->setArg(I, Converted.get());
  6274. }
  6275. if (Dependent) {
  6276. TheCall->setType(Context.DependentTy);
  6277. return false;
  6278. }
  6279. Expr *Real = TheCall->getArg(0);
  6280. Expr *Imag = TheCall->getArg(1);
  6281. if (!Context.hasSameType(Real->getType(), Imag->getType())) {
  6282. return Diag(Real->getBeginLoc(),
  6283. diag::err_typecheck_call_different_arg_types)
  6284. << Real->getType() << Imag->getType()
  6285. << Real->getSourceRange() << Imag->getSourceRange();
  6286. }
  6287. // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
  6288. // don't allow this builtin to form those types either.
  6289. // FIXME: Should we allow these types?
  6290. if (Real->getType()->isFloat16Type())
  6291. return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
  6292. << "_Float16";
  6293. if (Real->getType()->isHalfType())
  6294. return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
  6295. << "half";
  6296. TheCall->setType(Context.getComplexType(Real->getType()));
  6297. return false;
  6298. }
  6299. // Customized Sema Checking for VSX builtins that have the following signature:
  6300. // vector [...] builtinName(vector [...], vector [...], const int);
  6301. // Which takes the same type of vectors (any legal vector type) for the first
  6302. // two arguments and takes compile time constant for the third argument.
  6303. // Example builtins are :
  6304. // vector double vec_xxpermdi(vector double, vector double, int);
  6305. // vector short vec_xxsldwi(vector short, vector short, int);
  6306. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  6307. unsigned ExpectedNumArgs = 3;
  6308. if (checkArgCount(*this, TheCall, ExpectedNumArgs))
  6309. return true;
  6310. // Check the third argument is a compile time constant
  6311. if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
  6312. return Diag(TheCall->getBeginLoc(),
  6313. diag::err_vsx_builtin_nonconstant_argument)
  6314. << 3 /* argument index */ << TheCall->getDirectCallee()
  6315. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  6316. TheCall->getArg(2)->getEndLoc());
  6317. QualType Arg1Ty = TheCall->getArg(0)->getType();
  6318. QualType Arg2Ty = TheCall->getArg(1)->getType();
  6319. // Check the type of argument 1 and argument 2 are vectors.
  6320. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  6321. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  6322. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  6323. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  6324. << TheCall->getDirectCallee()
  6325. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  6326. TheCall->getArg(1)->getEndLoc());
  6327. }
  6328. // Check the first two arguments are the same type.
  6329. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  6330. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  6331. << TheCall->getDirectCallee()
  6332. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  6333. TheCall->getArg(1)->getEndLoc());
  6334. }
  6335. // When default clang type checking is turned off and the customized type
  6336. // checking is used, the returning type of the function must be explicitly
  6337. // set. Otherwise it is _Bool by default.
  6338. TheCall->setType(Arg1Ty);
  6339. return false;
  6340. }
  6341. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  6342. // This is declared to take (...), so we have to check everything.
  6343. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  6344. if (TheCall->getNumArgs() < 2)
  6345. return ExprError(Diag(TheCall->getEndLoc(),
  6346. diag::err_typecheck_call_too_few_args_at_least)
  6347. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  6348. << TheCall->getSourceRange());
  6349. // Determine which of the following types of shufflevector we're checking:
  6350. // 1) unary, vector mask: (lhs, mask)
  6351. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  6352. QualType resType = TheCall->getArg(0)->getType();
  6353. unsigned numElements = 0;
  6354. if (!TheCall->getArg(0)->isTypeDependent() &&
  6355. !TheCall->getArg(1)->isTypeDependent()) {
  6356. QualType LHSType = TheCall->getArg(0)->getType();
  6357. QualType RHSType = TheCall->getArg(1)->getType();
  6358. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  6359. return ExprError(
  6360. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  6361. << TheCall->getDirectCallee()
  6362. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  6363. TheCall->getArg(1)->getEndLoc()));
  6364. numElements = LHSType->castAs<VectorType>()->getNumElements();
  6365. unsigned numResElements = TheCall->getNumArgs() - 2;
  6366. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  6367. // with mask. If so, verify that RHS is an integer vector type with the
  6368. // same number of elts as lhs.
  6369. if (TheCall->getNumArgs() == 2) {
  6370. if (!RHSType->hasIntegerRepresentation() ||
  6371. RHSType->castAs<VectorType>()->getNumElements() != numElements)
  6372. return ExprError(Diag(TheCall->getBeginLoc(),
  6373. diag::err_vec_builtin_incompatible_vector)
  6374. << TheCall->getDirectCallee()
  6375. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  6376. TheCall->getArg(1)->getEndLoc()));
  6377. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  6378. return ExprError(Diag(TheCall->getBeginLoc(),
  6379. diag::err_vec_builtin_incompatible_vector)
  6380. << TheCall->getDirectCallee()
  6381. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  6382. TheCall->getArg(1)->getEndLoc()));
  6383. } else if (numElements != numResElements) {
  6384. QualType eltType = LHSType->castAs<VectorType>()->getElementType();
  6385. resType = Context.getVectorType(eltType, numResElements,
  6386. VectorType::GenericVector);
  6387. }
  6388. }
  6389. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  6390. if (TheCall->getArg(i)->isTypeDependent() ||
  6391. TheCall->getArg(i)->isValueDependent())
  6392. continue;
  6393. Optional<llvm::APSInt> Result;
  6394. if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
  6395. return ExprError(Diag(TheCall->getBeginLoc(),
  6396. diag::err_shufflevector_nonconstant_argument)
  6397. << TheCall->getArg(i)->getSourceRange());
  6398. // Allow -1 which will be translated to undef in the IR.
  6399. if (Result->isSigned() && Result->isAllOnes())
  6400. continue;
  6401. if (Result->getActiveBits() > 64 ||
  6402. Result->getZExtValue() >= numElements * 2)
  6403. return ExprError(Diag(TheCall->getBeginLoc(),
  6404. diag::err_shufflevector_argument_too_large)
  6405. << TheCall->getArg(i)->getSourceRange());
  6406. }
  6407. SmallVector<Expr*, 32> exprs;
  6408. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  6409. exprs.push_back(TheCall->getArg(i));
  6410. TheCall->setArg(i, nullptr);
  6411. }
  6412. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  6413. TheCall->getCallee()->getBeginLoc(),
  6414. TheCall->getRParenLoc());
  6415. }
  6416. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  6417. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  6418. SourceLocation BuiltinLoc,
  6419. SourceLocation RParenLoc) {
  6420. ExprValueKind VK = VK_PRValue;
  6421. ExprObjectKind OK = OK_Ordinary;
  6422. QualType DstTy = TInfo->getType();
  6423. QualType SrcTy = E->getType();
  6424. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  6425. return ExprError(Diag(BuiltinLoc,
  6426. diag::err_convertvector_non_vector)
  6427. << E->getSourceRange());
  6428. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  6429. return ExprError(Diag(BuiltinLoc,
  6430. diag::err_convertvector_non_vector_type));
  6431. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  6432. unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
  6433. unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
  6434. if (SrcElts != DstElts)
  6435. return ExprError(Diag(BuiltinLoc,
  6436. diag::err_convertvector_incompatible_vector)
  6437. << E->getSourceRange());
  6438. }
  6439. return new (Context)
  6440. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  6441. }
  6442. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  6443. // This is declared to take (const void*, ...) and can take two
  6444. // optional constant int args.
  6445. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  6446. unsigned NumArgs = TheCall->getNumArgs();
  6447. if (NumArgs > 3)
  6448. return Diag(TheCall->getEndLoc(),
  6449. diag::err_typecheck_call_too_many_args_at_most)
  6450. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  6451. // Argument 0 is checked for us and the remaining arguments must be
  6452. // constant integers.
  6453. for (unsigned i = 1; i != NumArgs; ++i)
  6454. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  6455. return true;
  6456. return false;
  6457. }
  6458. /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
  6459. bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
  6460. if (!Context.getTargetInfo().checkArithmeticFenceSupported())
  6461. return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  6462. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  6463. if (checkArgCount(*this, TheCall, 1))
  6464. return true;
  6465. Expr *Arg = TheCall->getArg(0);
  6466. if (Arg->isInstantiationDependent())
  6467. return false;
  6468. QualType ArgTy = Arg->getType();
  6469. if (!ArgTy->hasFloatingRepresentation())
  6470. return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
  6471. << ArgTy;
  6472. if (Arg->isLValue()) {
  6473. ExprResult FirstArg = DefaultLvalueConversion(Arg);
  6474. TheCall->setArg(0, FirstArg.get());
  6475. }
  6476. TheCall->setType(TheCall->getArg(0)->getType());
  6477. return false;
  6478. }
  6479. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  6480. // __assume does not evaluate its arguments, and should warn if its argument
  6481. // has side effects.
  6482. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  6483. Expr *Arg = TheCall->getArg(0);
  6484. if (Arg->isInstantiationDependent()) return false;
  6485. if (Arg->HasSideEffects(Context))
  6486. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  6487. << Arg->getSourceRange()
  6488. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  6489. return false;
  6490. }
  6491. /// Handle __builtin_alloca_with_align. This is declared
  6492. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  6493. /// than 8.
  6494. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  6495. // The alignment must be a constant integer.
  6496. Expr *Arg = TheCall->getArg(1);
  6497. // We can't check the value of a dependent argument.
  6498. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  6499. if (const auto *UE =
  6500. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  6501. if (UE->getKind() == UETT_AlignOf ||
  6502. UE->getKind() == UETT_PreferredAlignOf)
  6503. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  6504. << Arg->getSourceRange();
  6505. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  6506. if (!Result.isPowerOf2())
  6507. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  6508. << Arg->getSourceRange();
  6509. if (Result < Context.getCharWidth())
  6510. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  6511. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  6512. if (Result > std::numeric_limits<int32_t>::max())
  6513. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  6514. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  6515. }
  6516. return false;
  6517. }
  6518. /// Handle __builtin_assume_aligned. This is declared
  6519. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  6520. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  6521. unsigned NumArgs = TheCall->getNumArgs();
  6522. if (NumArgs > 3)
  6523. return Diag(TheCall->getEndLoc(),
  6524. diag::err_typecheck_call_too_many_args_at_most)
  6525. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  6526. // The alignment must be a constant integer.
  6527. Expr *Arg = TheCall->getArg(1);
  6528. // We can't check the value of a dependent argument.
  6529. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  6530. llvm::APSInt Result;
  6531. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  6532. return true;
  6533. if (!Result.isPowerOf2())
  6534. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  6535. << Arg->getSourceRange();
  6536. if (Result > Sema::MaximumAlignment)
  6537. Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
  6538. << Arg->getSourceRange() << Sema::MaximumAlignment;
  6539. }
  6540. if (NumArgs > 2) {
  6541. ExprResult Arg(TheCall->getArg(2));
  6542. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  6543. Context.getSizeType(), false);
  6544. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  6545. if (Arg.isInvalid()) return true;
  6546. TheCall->setArg(2, Arg.get());
  6547. }
  6548. return false;
  6549. }
  6550. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  6551. unsigned BuiltinID =
  6552. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  6553. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  6554. unsigned NumArgs = TheCall->getNumArgs();
  6555. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  6556. if (NumArgs < NumRequiredArgs) {
  6557. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  6558. << 0 /* function call */ << NumRequiredArgs << NumArgs
  6559. << TheCall->getSourceRange();
  6560. }
  6561. if (NumArgs >= NumRequiredArgs + 0x100) {
  6562. return Diag(TheCall->getEndLoc(),
  6563. diag::err_typecheck_call_too_many_args_at_most)
  6564. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  6565. << TheCall->getSourceRange();
  6566. }
  6567. unsigned i = 0;
  6568. // For formatting call, check buffer arg.
  6569. if (!IsSizeCall) {
  6570. ExprResult Arg(TheCall->getArg(i));
  6571. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  6572. Context, Context.VoidPtrTy, false);
  6573. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  6574. if (Arg.isInvalid())
  6575. return true;
  6576. TheCall->setArg(i, Arg.get());
  6577. i++;
  6578. }
  6579. // Check string literal arg.
  6580. unsigned FormatIdx = i;
  6581. {
  6582. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  6583. if (Arg.isInvalid())
  6584. return true;
  6585. TheCall->setArg(i, Arg.get());
  6586. i++;
  6587. }
  6588. // Make sure variadic args are scalar.
  6589. unsigned FirstDataArg = i;
  6590. while (i < NumArgs) {
  6591. ExprResult Arg = DefaultVariadicArgumentPromotion(
  6592. TheCall->getArg(i), VariadicFunction, nullptr);
  6593. if (Arg.isInvalid())
  6594. return true;
  6595. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  6596. if (ArgSize.getQuantity() >= 0x100) {
  6597. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  6598. << i << (int)ArgSize.getQuantity() << 0xff
  6599. << TheCall->getSourceRange();
  6600. }
  6601. TheCall->setArg(i, Arg.get());
  6602. i++;
  6603. }
  6604. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  6605. // call to avoid duplicate diagnostics.
  6606. if (!IsSizeCall) {
  6607. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  6608. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  6609. bool Success = CheckFormatArguments(
  6610. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  6611. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  6612. CheckedVarArgs);
  6613. if (!Success)
  6614. return true;
  6615. }
  6616. if (IsSizeCall) {
  6617. TheCall->setType(Context.getSizeType());
  6618. } else {
  6619. TheCall->setType(Context.VoidPtrTy);
  6620. }
  6621. return false;
  6622. }
  6623. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  6624. /// TheCall is a constant expression.
  6625. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  6626. llvm::APSInt &Result) {
  6627. Expr *Arg = TheCall->getArg(ArgNum);
  6628. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  6629. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  6630. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  6631. Optional<llvm::APSInt> R;
  6632. if (!(R = Arg->getIntegerConstantExpr(Context)))
  6633. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  6634. << FDecl->getDeclName() << Arg->getSourceRange();
  6635. Result = *R;
  6636. return false;
  6637. }
  6638. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  6639. /// TheCall is a constant expression in the range [Low, High].
  6640. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  6641. int Low, int High, bool RangeIsError) {
  6642. if (isConstantEvaluated())
  6643. return false;
  6644. llvm::APSInt Result;
  6645. // We can't check the value of a dependent argument.
  6646. Expr *Arg = TheCall->getArg(ArgNum);
  6647. if (Arg->isTypeDependent() || Arg->isValueDependent())
  6648. return false;
  6649. // Check constant-ness first.
  6650. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  6651. return true;
  6652. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  6653. if (RangeIsError)
  6654. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  6655. << toString(Result, 10) << Low << High << Arg->getSourceRange();
  6656. else
  6657. // Defer the warning until we know if the code will be emitted so that
  6658. // dead code can ignore this.
  6659. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  6660. PDiag(diag::warn_argument_invalid_range)
  6661. << toString(Result, 10) << Low << High
  6662. << Arg->getSourceRange());
  6663. }
  6664. return false;
  6665. }
  6666. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  6667. /// TheCall is a constant expression is a multiple of Num..
  6668. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  6669. unsigned Num) {
  6670. llvm::APSInt Result;
  6671. // We can't check the value of a dependent argument.
  6672. Expr *Arg = TheCall->getArg(ArgNum);
  6673. if (Arg->isTypeDependent() || Arg->isValueDependent())
  6674. return false;
  6675. // Check constant-ness first.
  6676. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  6677. return true;
  6678. if (Result.getSExtValue() % Num != 0)
  6679. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  6680. << Num << Arg->getSourceRange();
  6681. return false;
  6682. }
  6683. /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
  6684. /// constant expression representing a power of 2.
  6685. bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
  6686. llvm::APSInt Result;
  6687. // We can't check the value of a dependent argument.
  6688. Expr *Arg = TheCall->getArg(ArgNum);
  6689. if (Arg->isTypeDependent() || Arg->isValueDependent())
  6690. return false;
  6691. // Check constant-ness first.
  6692. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  6693. return true;
  6694. // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
  6695. // and only if x is a power of 2.
  6696. if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
  6697. return false;
  6698. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
  6699. << Arg->getSourceRange();
  6700. }
  6701. static bool IsShiftedByte(llvm::APSInt Value) {
  6702. if (Value.isNegative())
  6703. return false;
  6704. // Check if it's a shifted byte, by shifting it down
  6705. while (true) {
  6706. // If the value fits in the bottom byte, the check passes.
  6707. if (Value < 0x100)
  6708. return true;
  6709. // Otherwise, if the value has _any_ bits in the bottom byte, the check
  6710. // fails.
  6711. if ((Value & 0xFF) != 0)
  6712. return false;
  6713. // If the bottom 8 bits are all 0, but something above that is nonzero,
  6714. // then shifting the value right by 8 bits won't affect whether it's a
  6715. // shifted byte or not. So do that, and go round again.
  6716. Value >>= 8;
  6717. }
  6718. }
  6719. /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
  6720. /// a constant expression representing an arbitrary byte value shifted left by
  6721. /// a multiple of 8 bits.
  6722. bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
  6723. unsigned ArgBits) {
  6724. llvm::APSInt Result;
  6725. // We can't check the value of a dependent argument.
  6726. Expr *Arg = TheCall->getArg(ArgNum);
  6727. if (Arg->isTypeDependent() || Arg->isValueDependent())
  6728. return false;
  6729. // Check constant-ness first.
  6730. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  6731. return true;
  6732. // Truncate to the given size.
  6733. Result = Result.getLoBits(ArgBits);
  6734. Result.setIsUnsigned(true);
  6735. if (IsShiftedByte(Result))
  6736. return false;
  6737. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
  6738. << Arg->getSourceRange();
  6739. }
  6740. /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
  6741. /// TheCall is a constant expression representing either a shifted byte value,
  6742. /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
  6743. /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
  6744. /// Arm MVE intrinsics.
  6745. bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
  6746. int ArgNum,
  6747. unsigned ArgBits) {
  6748. llvm::APSInt Result;
  6749. // We can't check the value of a dependent argument.
  6750. Expr *Arg = TheCall->getArg(ArgNum);
  6751. if (Arg->isTypeDependent() || Arg->isValueDependent())
  6752. return false;
  6753. // Check constant-ness first.
  6754. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  6755. return true;
  6756. // Truncate to the given size.
  6757. Result = Result.getLoBits(ArgBits);
  6758. Result.setIsUnsigned(true);
  6759. // Check to see if it's in either of the required forms.
  6760. if (IsShiftedByte(Result) ||
  6761. (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
  6762. return false;
  6763. return Diag(TheCall->getBeginLoc(),
  6764. diag::err_argument_not_shifted_byte_or_xxff)
  6765. << Arg->getSourceRange();
  6766. }
  6767. /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
  6768. bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
  6769. if (BuiltinID == AArch64::BI__builtin_arm_irg) {
  6770. if (checkArgCount(*this, TheCall, 2))
  6771. return true;
  6772. Expr *Arg0 = TheCall->getArg(0);
  6773. Expr *Arg1 = TheCall->getArg(1);
  6774. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  6775. if (FirstArg.isInvalid())
  6776. return true;
  6777. QualType FirstArgType = FirstArg.get()->getType();
  6778. if (!FirstArgType->isAnyPointerType())
  6779. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  6780. << "first" << FirstArgType << Arg0->getSourceRange();
  6781. TheCall->setArg(0, FirstArg.get());
  6782. ExprResult SecArg = DefaultLvalueConversion(Arg1);
  6783. if (SecArg.isInvalid())
  6784. return true;
  6785. QualType SecArgType = SecArg.get()->getType();
  6786. if (!SecArgType->isIntegerType())
  6787. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  6788. << "second" << SecArgType << Arg1->getSourceRange();
  6789. // Derive the return type from the pointer argument.
  6790. TheCall->setType(FirstArgType);
  6791. return false;
  6792. }
  6793. if (BuiltinID == AArch64::BI__builtin_arm_addg) {
  6794. if (checkArgCount(*this, TheCall, 2))
  6795. return true;
  6796. Expr *Arg0 = TheCall->getArg(0);
  6797. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  6798. if (FirstArg.isInvalid())
  6799. return true;
  6800. QualType FirstArgType = FirstArg.get()->getType();
  6801. if (!FirstArgType->isAnyPointerType())
  6802. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  6803. << "first" << FirstArgType << Arg0->getSourceRange();
  6804. TheCall->setArg(0, FirstArg.get());
  6805. // Derive the return type from the pointer argument.
  6806. TheCall->setType(FirstArgType);
  6807. // Second arg must be an constant in range [0,15]
  6808. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  6809. }
  6810. if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
  6811. if (checkArgCount(*this, TheCall, 2))
  6812. return true;
  6813. Expr *Arg0 = TheCall->getArg(0);
  6814. Expr *Arg1 = TheCall->getArg(1);
  6815. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  6816. if (FirstArg.isInvalid())
  6817. return true;
  6818. QualType FirstArgType = FirstArg.get()->getType();
  6819. if (!FirstArgType->isAnyPointerType())
  6820. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  6821. << "first" << FirstArgType << Arg0->getSourceRange();
  6822. QualType SecArgType = Arg1->getType();
  6823. if (!SecArgType->isIntegerType())
  6824. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  6825. << "second" << SecArgType << Arg1->getSourceRange();
  6826. TheCall->setType(Context.IntTy);
  6827. return false;
  6828. }
  6829. if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
  6830. BuiltinID == AArch64::BI__builtin_arm_stg) {
  6831. if (checkArgCount(*this, TheCall, 1))
  6832. return true;
  6833. Expr *Arg0 = TheCall->getArg(0);
  6834. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  6835. if (FirstArg.isInvalid())
  6836. return true;
  6837. QualType FirstArgType = FirstArg.get()->getType();
  6838. if (!FirstArgType->isAnyPointerType())
  6839. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  6840. << "first" << FirstArgType << Arg0->getSourceRange();
  6841. TheCall->setArg(0, FirstArg.get());
  6842. // Derive the return type from the pointer argument.
  6843. if (BuiltinID == AArch64::BI__builtin_arm_ldg)
  6844. TheCall->setType(FirstArgType);
  6845. return false;
  6846. }
  6847. if (BuiltinID == AArch64::BI__builtin_arm_subp) {
  6848. Expr *ArgA = TheCall->getArg(0);
  6849. Expr *ArgB = TheCall->getArg(1);
  6850. ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
  6851. ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
  6852. if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
  6853. return true;
  6854. QualType ArgTypeA = ArgExprA.get()->getType();
  6855. QualType ArgTypeB = ArgExprB.get()->getType();
  6856. auto isNull = [&] (Expr *E) -> bool {
  6857. return E->isNullPointerConstant(
  6858. Context, Expr::NPC_ValueDependentIsNotNull); };
  6859. // argument should be either a pointer or null
  6860. if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
  6861. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  6862. << "first" << ArgTypeA << ArgA->getSourceRange();
  6863. if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
  6864. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  6865. << "second" << ArgTypeB << ArgB->getSourceRange();
  6866. // Ensure Pointee types are compatible
  6867. if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
  6868. ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
  6869. QualType pointeeA = ArgTypeA->getPointeeType();
  6870. QualType pointeeB = ArgTypeB->getPointeeType();
  6871. if (!Context.typesAreCompatible(
  6872. Context.getCanonicalType(pointeeA).getUnqualifiedType(),
  6873. Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
  6874. return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
  6875. << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
  6876. << ArgB->getSourceRange();
  6877. }
  6878. }
  6879. // at least one argument should be pointer type
  6880. if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
  6881. return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
  6882. << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
  6883. if (isNull(ArgA)) // adopt type of the other pointer
  6884. ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
  6885. if (isNull(ArgB))
  6886. ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
  6887. TheCall->setArg(0, ArgExprA.get());
  6888. TheCall->setArg(1, ArgExprB.get());
  6889. TheCall->setType(Context.LongLongTy);
  6890. return false;
  6891. }
  6892. assert(false && "Unhandled ARM MTE intrinsic");
  6893. return true;
  6894. }
  6895. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  6896. /// TheCall is an ARM/AArch64 special register string literal.
  6897. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  6898. int ArgNum, unsigned ExpectedFieldNum,
  6899. bool AllowName) {
  6900. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  6901. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  6902. BuiltinID == ARM::BI__builtin_arm_rsr ||
  6903. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  6904. BuiltinID == ARM::BI__builtin_arm_wsr ||
  6905. BuiltinID == ARM::BI__builtin_arm_wsrp;
  6906. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  6907. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  6908. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  6909. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  6910. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  6911. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  6912. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  6913. // We can't check the value of a dependent argument.
  6914. Expr *Arg = TheCall->getArg(ArgNum);
  6915. if (Arg->isTypeDependent() || Arg->isValueDependent())
  6916. return false;
  6917. // Check if the argument is a string literal.
  6918. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  6919. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  6920. << Arg->getSourceRange();
  6921. // Check the type of special register given.
  6922. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  6923. SmallVector<StringRef, 6> Fields;
  6924. Reg.split(Fields, ":");
  6925. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  6926. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  6927. << Arg->getSourceRange();
  6928. // If the string is the name of a register then we cannot check that it is
  6929. // valid here but if the string is of one the forms described in ACLE then we
  6930. // can check that the supplied fields are integers and within the valid
  6931. // ranges.
  6932. if (Fields.size() > 1) {
  6933. bool FiveFields = Fields.size() == 5;
  6934. bool ValidString = true;
  6935. if (IsARMBuiltin) {
  6936. ValidString &= Fields[0].startswith_insensitive("cp") ||
  6937. Fields[0].startswith_insensitive("p");
  6938. if (ValidString)
  6939. Fields[0] = Fields[0].drop_front(
  6940. Fields[0].startswith_insensitive("cp") ? 2 : 1);
  6941. ValidString &= Fields[2].startswith_insensitive("c");
  6942. if (ValidString)
  6943. Fields[2] = Fields[2].drop_front(1);
  6944. if (FiveFields) {
  6945. ValidString &= Fields[3].startswith_insensitive("c");
  6946. if (ValidString)
  6947. Fields[3] = Fields[3].drop_front(1);
  6948. }
  6949. }
  6950. SmallVector<int, 5> Ranges;
  6951. if (FiveFields)
  6952. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  6953. else
  6954. Ranges.append({15, 7, 15});
  6955. for (unsigned i=0; i<Fields.size(); ++i) {
  6956. int IntField;
  6957. ValidString &= !Fields[i].getAsInteger(10, IntField);
  6958. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  6959. }
  6960. if (!ValidString)
  6961. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  6962. << Arg->getSourceRange();
  6963. } else if (IsAArch64Builtin && Fields.size() == 1) {
  6964. // If the register name is one of those that appear in the condition below
  6965. // and the special register builtin being used is one of the write builtins,
  6966. // then we require that the argument provided for writing to the register
  6967. // is an integer constant expression. This is because it will be lowered to
  6968. // an MSR (immediate) instruction, so we need to know the immediate at
  6969. // compile time.
  6970. if (TheCall->getNumArgs() != 2)
  6971. return false;
  6972. std::string RegLower = Reg.lower();
  6973. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  6974. RegLower != "pan" && RegLower != "uao")
  6975. return false;
  6976. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  6977. }
  6978. return false;
  6979. }
  6980. /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
  6981. /// Emit an error and return true on failure; return false on success.
  6982. /// TypeStr is a string containing the type descriptor of the value returned by
  6983. /// the builtin and the descriptors of the expected type of the arguments.
  6984. bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
  6985. const char *TypeStr) {
  6986. assert((TypeStr[0] != '\0') &&
  6987. "Invalid types in PPC MMA builtin declaration");
  6988. switch (BuiltinID) {
  6989. default:
  6990. // This function is called in CheckPPCBuiltinFunctionCall where the
  6991. // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
  6992. // we are isolating the pair vector memop builtins that can be used with mma
  6993. // off so the default case is every builtin that requires mma and paired
  6994. // vector memops.
  6995. if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
  6996. diag::err_ppc_builtin_only_on_arch, "10") ||
  6997. SemaFeatureCheck(*this, TheCall, "mma",
  6998. diag::err_ppc_builtin_only_on_arch, "10"))
  6999. return true;
  7000. break;
  7001. case PPC::BI__builtin_vsx_lxvp:
  7002. case PPC::BI__builtin_vsx_stxvp:
  7003. case PPC::BI__builtin_vsx_assemble_pair:
  7004. case PPC::BI__builtin_vsx_disassemble_pair:
  7005. if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
  7006. diag::err_ppc_builtin_only_on_arch, "10"))
  7007. return true;
  7008. break;
  7009. }
  7010. unsigned Mask = 0;
  7011. unsigned ArgNum = 0;
  7012. // The first type in TypeStr is the type of the value returned by the
  7013. // builtin. So we first read that type and change the type of TheCall.
  7014. QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
  7015. TheCall->setType(type);
  7016. while (*TypeStr != '\0') {
  7017. Mask = 0;
  7018. QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
  7019. if (ArgNum >= TheCall->getNumArgs()) {
  7020. ArgNum++;
  7021. break;
  7022. }
  7023. Expr *Arg = TheCall->getArg(ArgNum);
  7024. QualType PassedType = Arg->getType();
  7025. QualType StrippedRVType = PassedType.getCanonicalType();
  7026. // Strip Restrict/Volatile qualifiers.
  7027. if (StrippedRVType.isRestrictQualified() ||
  7028. StrippedRVType.isVolatileQualified())
  7029. StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
  7030. // The only case where the argument type and expected type are allowed to
  7031. // mismatch is if the argument type is a non-void pointer (or array) and
  7032. // expected type is a void pointer.
  7033. if (StrippedRVType != ExpectedType)
  7034. if (!(ExpectedType->isVoidPointerType() &&
  7035. (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
  7036. return Diag(Arg->getBeginLoc(),
  7037. diag::err_typecheck_convert_incompatible)
  7038. << PassedType << ExpectedType << 1 << 0 << 0;
  7039. // If the value of the Mask is not 0, we have a constraint in the size of
  7040. // the integer argument so here we ensure the argument is a constant that
  7041. // is in the valid range.
  7042. if (Mask != 0 &&
  7043. SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
  7044. return true;
  7045. ArgNum++;
  7046. }
  7047. // In case we exited early from the previous loop, there are other types to
  7048. // read from TypeStr. So we need to read them all to ensure we have the right
  7049. // number of arguments in TheCall and if it is not the case, to display a
  7050. // better error message.
  7051. while (*TypeStr != '\0') {
  7052. (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
  7053. ArgNum++;
  7054. }
  7055. if (checkArgCount(*this, TheCall, ArgNum))
  7056. return true;
  7057. return false;
  7058. }
  7059. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  7060. /// This checks that the target supports __builtin_longjmp and
  7061. /// that val is a constant 1.
  7062. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  7063. if (!Context.getTargetInfo().hasSjLjLowering())
  7064. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  7065. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  7066. Expr *Arg = TheCall->getArg(1);
  7067. llvm::APSInt Result;
  7068. // TODO: This is less than ideal. Overload this to take a value.
  7069. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  7070. return true;
  7071. if (Result != 1)
  7072. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  7073. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  7074. return false;
  7075. }
  7076. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  7077. /// This checks that the target supports __builtin_setjmp.
  7078. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  7079. if (!Context.getTargetInfo().hasSjLjLowering())
  7080. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  7081. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  7082. return false;
  7083. }
  7084. namespace {
  7085. class UncoveredArgHandler {
  7086. enum { Unknown = -1, AllCovered = -2 };
  7087. signed FirstUncoveredArg = Unknown;
  7088. SmallVector<const Expr *, 4> DiagnosticExprs;
  7089. public:
  7090. UncoveredArgHandler() = default;
  7091. bool hasUncoveredArg() const {
  7092. return (FirstUncoveredArg >= 0);
  7093. }
  7094. unsigned getUncoveredArg() const {
  7095. assert(hasUncoveredArg() && "no uncovered argument");
  7096. return FirstUncoveredArg;
  7097. }
  7098. void setAllCovered() {
  7099. // A string has been found with all arguments covered, so clear out
  7100. // the diagnostics.
  7101. DiagnosticExprs.clear();
  7102. FirstUncoveredArg = AllCovered;
  7103. }
  7104. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  7105. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  7106. // Don't update if a previous string covers all arguments.
  7107. if (FirstUncoveredArg == AllCovered)
  7108. return;
  7109. // UncoveredArgHandler tracks the highest uncovered argument index
  7110. // and with it all the strings that match this index.
  7111. if (NewFirstUncoveredArg == FirstUncoveredArg)
  7112. DiagnosticExprs.push_back(StrExpr);
  7113. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  7114. DiagnosticExprs.clear();
  7115. DiagnosticExprs.push_back(StrExpr);
  7116. FirstUncoveredArg = NewFirstUncoveredArg;
  7117. }
  7118. }
  7119. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  7120. };
  7121. enum StringLiteralCheckType {
  7122. SLCT_NotALiteral,
  7123. SLCT_UncheckedLiteral,
  7124. SLCT_CheckedLiteral
  7125. };
  7126. } // namespace
  7127. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  7128. BinaryOperatorKind BinOpKind,
  7129. bool AddendIsRight) {
  7130. unsigned BitWidth = Offset.getBitWidth();
  7131. unsigned AddendBitWidth = Addend.getBitWidth();
  7132. // There might be negative interim results.
  7133. if (Addend.isUnsigned()) {
  7134. Addend = Addend.zext(++AddendBitWidth);
  7135. Addend.setIsSigned(true);
  7136. }
  7137. // Adjust the bit width of the APSInts.
  7138. if (AddendBitWidth > BitWidth) {
  7139. Offset = Offset.sext(AddendBitWidth);
  7140. BitWidth = AddendBitWidth;
  7141. } else if (BitWidth > AddendBitWidth) {
  7142. Addend = Addend.sext(BitWidth);
  7143. }
  7144. bool Ov = false;
  7145. llvm::APSInt ResOffset = Offset;
  7146. if (BinOpKind == BO_Add)
  7147. ResOffset = Offset.sadd_ov(Addend, Ov);
  7148. else {
  7149. assert(AddendIsRight && BinOpKind == BO_Sub &&
  7150. "operator must be add or sub with addend on the right");
  7151. ResOffset = Offset.ssub_ov(Addend, Ov);
  7152. }
  7153. // We add an offset to a pointer here so we should support an offset as big as
  7154. // possible.
  7155. if (Ov) {
  7156. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  7157. "index (intermediate) result too big");
  7158. Offset = Offset.sext(2 * BitWidth);
  7159. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  7160. return;
  7161. }
  7162. Offset = ResOffset;
  7163. }
  7164. namespace {
  7165. // This is a wrapper class around StringLiteral to support offsetted string
  7166. // literals as format strings. It takes the offset into account when returning
  7167. // the string and its length or the source locations to display notes correctly.
  7168. class FormatStringLiteral {
  7169. const StringLiteral *FExpr;
  7170. int64_t Offset;
  7171. public:
  7172. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  7173. : FExpr(fexpr), Offset(Offset) {}
  7174. StringRef getString() const {
  7175. return FExpr->getString().drop_front(Offset);
  7176. }
  7177. unsigned getByteLength() const {
  7178. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  7179. }
  7180. unsigned getLength() const { return FExpr->getLength() - Offset; }
  7181. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  7182. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  7183. QualType getType() const { return FExpr->getType(); }
  7184. bool isAscii() const { return FExpr->isAscii(); }
  7185. bool isWide() const { return FExpr->isWide(); }
  7186. bool isUTF8() const { return FExpr->isUTF8(); }
  7187. bool isUTF16() const { return FExpr->isUTF16(); }
  7188. bool isUTF32() const { return FExpr->isUTF32(); }
  7189. bool isPascal() const { return FExpr->isPascal(); }
  7190. SourceLocation getLocationOfByte(
  7191. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  7192. const TargetInfo &Target, unsigned *StartToken = nullptr,
  7193. unsigned *StartTokenByteOffset = nullptr) const {
  7194. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  7195. StartToken, StartTokenByteOffset);
  7196. }
  7197. SourceLocation getBeginLoc() const LLVM_READONLY {
  7198. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  7199. }
  7200. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  7201. };
  7202. } // namespace
  7203. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7204. const Expr *OrigFormatExpr,
  7205. ArrayRef<const Expr *> Args,
  7206. bool HasVAListArg, unsigned format_idx,
  7207. unsigned firstDataArg,
  7208. Sema::FormatStringType Type,
  7209. bool inFunctionCall,
  7210. Sema::VariadicCallType CallType,
  7211. llvm::SmallBitVector &CheckedVarArgs,
  7212. UncoveredArgHandler &UncoveredArg,
  7213. bool IgnoreStringsWithoutSpecifiers);
  7214. // Determine if an expression is a string literal or constant string.
  7215. // If this function returns false on the arguments to a function expecting a
  7216. // format string, we will usually need to emit a warning.
  7217. // True string literals are then checked by CheckFormatString.
  7218. static StringLiteralCheckType
  7219. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  7220. bool HasVAListArg, unsigned format_idx,
  7221. unsigned firstDataArg, Sema::FormatStringType Type,
  7222. Sema::VariadicCallType CallType, bool InFunctionCall,
  7223. llvm::SmallBitVector &CheckedVarArgs,
  7224. UncoveredArgHandler &UncoveredArg,
  7225. llvm::APSInt Offset,
  7226. bool IgnoreStringsWithoutSpecifiers = false) {
  7227. if (S.isConstantEvaluated())
  7228. return SLCT_NotALiteral;
  7229. tryAgain:
  7230. assert(Offset.isSigned() && "invalid offset");
  7231. if (E->isTypeDependent() || E->isValueDependent())
  7232. return SLCT_NotALiteral;
  7233. E = E->IgnoreParenCasts();
  7234. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  7235. // Technically -Wformat-nonliteral does not warn about this case.
  7236. // The behavior of printf and friends in this case is implementation
  7237. // dependent. Ideally if the format string cannot be null then
  7238. // it should have a 'nonnull' attribute in the function prototype.
  7239. return SLCT_UncheckedLiteral;
  7240. switch (E->getStmtClass()) {
  7241. case Stmt::BinaryConditionalOperatorClass:
  7242. case Stmt::ConditionalOperatorClass: {
  7243. // The expression is a literal if both sub-expressions were, and it was
  7244. // completely checked only if both sub-expressions were checked.
  7245. const AbstractConditionalOperator *C =
  7246. cast<AbstractConditionalOperator>(E);
  7247. // Determine whether it is necessary to check both sub-expressions, for
  7248. // example, because the condition expression is a constant that can be
  7249. // evaluated at compile time.
  7250. bool CheckLeft = true, CheckRight = true;
  7251. bool Cond;
  7252. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
  7253. S.isConstantEvaluated())) {
  7254. if (Cond)
  7255. CheckRight = false;
  7256. else
  7257. CheckLeft = false;
  7258. }
  7259. // We need to maintain the offsets for the right and the left hand side
  7260. // separately to check if every possible indexed expression is a valid
  7261. // string literal. They might have different offsets for different string
  7262. // literals in the end.
  7263. StringLiteralCheckType Left;
  7264. if (!CheckLeft)
  7265. Left = SLCT_UncheckedLiteral;
  7266. else {
  7267. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  7268. HasVAListArg, format_idx, firstDataArg,
  7269. Type, CallType, InFunctionCall,
  7270. CheckedVarArgs, UncoveredArg, Offset,
  7271. IgnoreStringsWithoutSpecifiers);
  7272. if (Left == SLCT_NotALiteral || !CheckRight) {
  7273. return Left;
  7274. }
  7275. }
  7276. StringLiteralCheckType Right = checkFormatStringExpr(
  7277. S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
  7278. Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  7279. IgnoreStringsWithoutSpecifiers);
  7280. return (CheckLeft && Left < Right) ? Left : Right;
  7281. }
  7282. case Stmt::ImplicitCastExprClass:
  7283. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  7284. goto tryAgain;
  7285. case Stmt::OpaqueValueExprClass:
  7286. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  7287. E = src;
  7288. goto tryAgain;
  7289. }
  7290. return SLCT_NotALiteral;
  7291. case Stmt::PredefinedExprClass:
  7292. // While __func__, etc., are technically not string literals, they
  7293. // cannot contain format specifiers and thus are not a security
  7294. // liability.
  7295. return SLCT_UncheckedLiteral;
  7296. case Stmt::DeclRefExprClass: {
  7297. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  7298. // As an exception, do not flag errors for variables binding to
  7299. // const string literals.
  7300. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  7301. bool isConstant = false;
  7302. QualType T = DR->getType();
  7303. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  7304. isConstant = AT->getElementType().isConstant(S.Context);
  7305. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  7306. isConstant = T.isConstant(S.Context) &&
  7307. PT->getPointeeType().isConstant(S.Context);
  7308. } else if (T->isObjCObjectPointerType()) {
  7309. // In ObjC, there is usually no "const ObjectPointer" type,
  7310. // so don't check if the pointee type is constant.
  7311. isConstant = T.isConstant(S.Context);
  7312. }
  7313. if (isConstant) {
  7314. if (const Expr *Init = VD->getAnyInitializer()) {
  7315. // Look through initializers like const char c[] = { "foo" }
  7316. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  7317. if (InitList->isStringLiteralInit())
  7318. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  7319. }
  7320. return checkFormatStringExpr(S, Init, Args,
  7321. HasVAListArg, format_idx,
  7322. firstDataArg, Type, CallType,
  7323. /*InFunctionCall*/ false, CheckedVarArgs,
  7324. UncoveredArg, Offset);
  7325. }
  7326. }
  7327. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  7328. // special check to see if the format string is a function parameter
  7329. // of the function calling the printf function. If the function
  7330. // has an attribute indicating it is a printf-like function, then we
  7331. // should suppress warnings concerning non-literals being used in a call
  7332. // to a vprintf function. For example:
  7333. //
  7334. // void
  7335. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  7336. // va_list ap;
  7337. // va_start(ap, fmt);
  7338. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  7339. // ...
  7340. // }
  7341. if (HasVAListArg) {
  7342. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  7343. if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
  7344. int PVIndex = PV->getFunctionScopeIndex() + 1;
  7345. for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
  7346. // adjust for implicit parameter
  7347. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
  7348. if (MD->isInstance())
  7349. ++PVIndex;
  7350. // We also check if the formats are compatible.
  7351. // We can't pass a 'scanf' string to a 'printf' function.
  7352. if (PVIndex == PVFormat->getFormatIdx() &&
  7353. Type == S.GetFormatStringType(PVFormat))
  7354. return SLCT_UncheckedLiteral;
  7355. }
  7356. }
  7357. }
  7358. }
  7359. }
  7360. return SLCT_NotALiteral;
  7361. }
  7362. case Stmt::CallExprClass:
  7363. case Stmt::CXXMemberCallExprClass: {
  7364. const CallExpr *CE = cast<CallExpr>(E);
  7365. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  7366. bool IsFirst = true;
  7367. StringLiteralCheckType CommonResult;
  7368. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  7369. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  7370. StringLiteralCheckType Result = checkFormatStringExpr(
  7371. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  7372. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  7373. IgnoreStringsWithoutSpecifiers);
  7374. if (IsFirst) {
  7375. CommonResult = Result;
  7376. IsFirst = false;
  7377. }
  7378. }
  7379. if (!IsFirst)
  7380. return CommonResult;
  7381. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  7382. unsigned BuiltinID = FD->getBuiltinID();
  7383. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  7384. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  7385. const Expr *Arg = CE->getArg(0);
  7386. return checkFormatStringExpr(S, Arg, Args,
  7387. HasVAListArg, format_idx,
  7388. firstDataArg, Type, CallType,
  7389. InFunctionCall, CheckedVarArgs,
  7390. UncoveredArg, Offset,
  7391. IgnoreStringsWithoutSpecifiers);
  7392. }
  7393. }
  7394. }
  7395. return SLCT_NotALiteral;
  7396. }
  7397. case Stmt::ObjCMessageExprClass: {
  7398. const auto *ME = cast<ObjCMessageExpr>(E);
  7399. if (const auto *MD = ME->getMethodDecl()) {
  7400. if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
  7401. // As a special case heuristic, if we're using the method -[NSBundle
  7402. // localizedStringForKey:value:table:], ignore any key strings that lack
  7403. // format specifiers. The idea is that if the key doesn't have any
  7404. // format specifiers then its probably just a key to map to the
  7405. // localized strings. If it does have format specifiers though, then its
  7406. // likely that the text of the key is the format string in the
  7407. // programmer's language, and should be checked.
  7408. const ObjCInterfaceDecl *IFace;
  7409. if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
  7410. IFace->getIdentifier()->isStr("NSBundle") &&
  7411. MD->getSelector().isKeywordSelector(
  7412. {"localizedStringForKey", "value", "table"})) {
  7413. IgnoreStringsWithoutSpecifiers = true;
  7414. }
  7415. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  7416. return checkFormatStringExpr(
  7417. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  7418. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  7419. IgnoreStringsWithoutSpecifiers);
  7420. }
  7421. }
  7422. return SLCT_NotALiteral;
  7423. }
  7424. case Stmt::ObjCStringLiteralClass:
  7425. case Stmt::StringLiteralClass: {
  7426. const StringLiteral *StrE = nullptr;
  7427. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  7428. StrE = ObjCFExpr->getString();
  7429. else
  7430. StrE = cast<StringLiteral>(E);
  7431. if (StrE) {
  7432. if (Offset.isNegative() || Offset > StrE->getLength()) {
  7433. // TODO: It would be better to have an explicit warning for out of
  7434. // bounds literals.
  7435. return SLCT_NotALiteral;
  7436. }
  7437. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  7438. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  7439. firstDataArg, Type, InFunctionCall, CallType,
  7440. CheckedVarArgs, UncoveredArg,
  7441. IgnoreStringsWithoutSpecifiers);
  7442. return SLCT_CheckedLiteral;
  7443. }
  7444. return SLCT_NotALiteral;
  7445. }
  7446. case Stmt::BinaryOperatorClass: {
  7447. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  7448. // A string literal + an int offset is still a string literal.
  7449. if (BinOp->isAdditiveOp()) {
  7450. Expr::EvalResult LResult, RResult;
  7451. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
  7452. LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  7453. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
  7454. RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  7455. if (LIsInt != RIsInt) {
  7456. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  7457. if (LIsInt) {
  7458. if (BinOpKind == BO_Add) {
  7459. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  7460. E = BinOp->getRHS();
  7461. goto tryAgain;
  7462. }
  7463. } else {
  7464. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  7465. E = BinOp->getLHS();
  7466. goto tryAgain;
  7467. }
  7468. }
  7469. }
  7470. return SLCT_NotALiteral;
  7471. }
  7472. case Stmt::UnaryOperatorClass: {
  7473. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  7474. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  7475. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  7476. Expr::EvalResult IndexResult;
  7477. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
  7478. Expr::SE_NoSideEffects,
  7479. S.isConstantEvaluated())) {
  7480. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  7481. /*RHS is int*/ true);
  7482. E = ASE->getBase();
  7483. goto tryAgain;
  7484. }
  7485. }
  7486. return SLCT_NotALiteral;
  7487. }
  7488. default:
  7489. return SLCT_NotALiteral;
  7490. }
  7491. }
  7492. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  7493. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  7494. .Case("scanf", FST_Scanf)
  7495. .Cases("printf", "printf0", FST_Printf)
  7496. .Cases("NSString", "CFString", FST_NSString)
  7497. .Case("strftime", FST_Strftime)
  7498. .Case("strfmon", FST_Strfmon)
  7499. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  7500. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  7501. .Case("os_trace", FST_OSLog)
  7502. .Case("os_log", FST_OSLog)
  7503. .Default(FST_Unknown);
  7504. }
  7505. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  7506. /// functions) for correct use of format strings.
  7507. /// Returns true if a format string has been fully checked.
  7508. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  7509. ArrayRef<const Expr *> Args,
  7510. bool IsCXXMember,
  7511. VariadicCallType CallType,
  7512. SourceLocation Loc, SourceRange Range,
  7513. llvm::SmallBitVector &CheckedVarArgs) {
  7514. FormatStringInfo FSI;
  7515. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  7516. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  7517. FSI.FirstDataArg, GetFormatStringType(Format),
  7518. CallType, Loc, Range, CheckedVarArgs);
  7519. return false;
  7520. }
  7521. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  7522. bool HasVAListArg, unsigned format_idx,
  7523. unsigned firstDataArg, FormatStringType Type,
  7524. VariadicCallType CallType,
  7525. SourceLocation Loc, SourceRange Range,
  7526. llvm::SmallBitVector &CheckedVarArgs) {
  7527. // CHECK: printf/scanf-like function is called with no format string.
  7528. if (format_idx >= Args.size()) {
  7529. Diag(Loc, diag::warn_missing_format_string) << Range;
  7530. return false;
  7531. }
  7532. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  7533. // CHECK: format string is not a string literal.
  7534. //
  7535. // Dynamically generated format strings are difficult to
  7536. // automatically vet at compile time. Requiring that format strings
  7537. // are string literals: (1) permits the checking of format strings by
  7538. // the compiler and thereby (2) can practically remove the source of
  7539. // many format string exploits.
  7540. // Format string can be either ObjC string (e.g. @"%d") or
  7541. // C string (e.g. "%d")
  7542. // ObjC string uses the same format specifiers as C string, so we can use
  7543. // the same format string checking logic for both ObjC and C strings.
  7544. UncoveredArgHandler UncoveredArg;
  7545. StringLiteralCheckType CT =
  7546. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  7547. format_idx, firstDataArg, Type, CallType,
  7548. /*IsFunctionCall*/ true, CheckedVarArgs,
  7549. UncoveredArg,
  7550. /*no string offset*/ llvm::APSInt(64, false) = 0);
  7551. // Generate a diagnostic where an uncovered argument is detected.
  7552. if (UncoveredArg.hasUncoveredArg()) {
  7553. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  7554. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  7555. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  7556. }
  7557. if (CT != SLCT_NotALiteral)
  7558. // Literal format string found, check done!
  7559. return CT == SLCT_CheckedLiteral;
  7560. // Strftime is particular as it always uses a single 'time' argument,
  7561. // so it is safe to pass a non-literal string.
  7562. if (Type == FST_Strftime)
  7563. return false;
  7564. // Do not emit diag when the string param is a macro expansion and the
  7565. // format is either NSString or CFString. This is a hack to prevent
  7566. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  7567. // which are usually used in place of NS and CF string literals.
  7568. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  7569. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  7570. return false;
  7571. // If there are no arguments specified, warn with -Wformat-security, otherwise
  7572. // warn only with -Wformat-nonliteral.
  7573. if (Args.size() == firstDataArg) {
  7574. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  7575. << OrigFormatExpr->getSourceRange();
  7576. switch (Type) {
  7577. default:
  7578. break;
  7579. case FST_Kprintf:
  7580. case FST_FreeBSDKPrintf:
  7581. case FST_Printf:
  7582. Diag(FormatLoc, diag::note_format_security_fixit)
  7583. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  7584. break;
  7585. case FST_NSString:
  7586. Diag(FormatLoc, diag::note_format_security_fixit)
  7587. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  7588. break;
  7589. }
  7590. } else {
  7591. Diag(FormatLoc, diag::warn_format_nonliteral)
  7592. << OrigFormatExpr->getSourceRange();
  7593. }
  7594. return false;
  7595. }
  7596. namespace {
  7597. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  7598. protected:
  7599. Sema &S;
  7600. const FormatStringLiteral *FExpr;
  7601. const Expr *OrigFormatExpr;
  7602. const Sema::FormatStringType FSType;
  7603. const unsigned FirstDataArg;
  7604. const unsigned NumDataArgs;
  7605. const char *Beg; // Start of format string.
  7606. const bool HasVAListArg;
  7607. ArrayRef<const Expr *> Args;
  7608. unsigned FormatIdx;
  7609. llvm::SmallBitVector CoveredArgs;
  7610. bool usesPositionalArgs = false;
  7611. bool atFirstArg = true;
  7612. bool inFunctionCall;
  7613. Sema::VariadicCallType CallType;
  7614. llvm::SmallBitVector &CheckedVarArgs;
  7615. UncoveredArgHandler &UncoveredArg;
  7616. public:
  7617. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  7618. const Expr *origFormatExpr,
  7619. const Sema::FormatStringType type, unsigned firstDataArg,
  7620. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  7621. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7622. bool inFunctionCall, Sema::VariadicCallType callType,
  7623. llvm::SmallBitVector &CheckedVarArgs,
  7624. UncoveredArgHandler &UncoveredArg)
  7625. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  7626. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  7627. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  7628. inFunctionCall(inFunctionCall), CallType(callType),
  7629. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  7630. CoveredArgs.resize(numDataArgs);
  7631. CoveredArgs.reset();
  7632. }
  7633. void DoneProcessing();
  7634. void HandleIncompleteSpecifier(const char *startSpecifier,
  7635. unsigned specifierLen) override;
  7636. void HandleInvalidLengthModifier(
  7637. const analyze_format_string::FormatSpecifier &FS,
  7638. const analyze_format_string::ConversionSpecifier &CS,
  7639. const char *startSpecifier, unsigned specifierLen,
  7640. unsigned DiagID);
  7641. void HandleNonStandardLengthModifier(
  7642. const analyze_format_string::FormatSpecifier &FS,
  7643. const char *startSpecifier, unsigned specifierLen);
  7644. void HandleNonStandardConversionSpecifier(
  7645. const analyze_format_string::ConversionSpecifier &CS,
  7646. const char *startSpecifier, unsigned specifierLen);
  7647. void HandlePosition(const char *startPos, unsigned posLen) override;
  7648. void HandleInvalidPosition(const char *startSpecifier,
  7649. unsigned specifierLen,
  7650. analyze_format_string::PositionContext p) override;
  7651. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  7652. void HandleNullChar(const char *nullCharacter) override;
  7653. template <typename Range>
  7654. static void
  7655. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  7656. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  7657. bool IsStringLocation, Range StringRange,
  7658. ArrayRef<FixItHint> Fixit = None);
  7659. protected:
  7660. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  7661. const char *startSpec,
  7662. unsigned specifierLen,
  7663. const char *csStart, unsigned csLen);
  7664. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  7665. const char *startSpec,
  7666. unsigned specifierLen);
  7667. SourceRange getFormatStringRange();
  7668. CharSourceRange getSpecifierRange(const char *startSpecifier,
  7669. unsigned specifierLen);
  7670. SourceLocation getLocationOfByte(const char *x);
  7671. const Expr *getDataArg(unsigned i) const;
  7672. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  7673. const analyze_format_string::ConversionSpecifier &CS,
  7674. const char *startSpecifier, unsigned specifierLen,
  7675. unsigned argIndex);
  7676. template <typename Range>
  7677. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  7678. bool IsStringLocation, Range StringRange,
  7679. ArrayRef<FixItHint> Fixit = None);
  7680. };
  7681. } // namespace
  7682. SourceRange CheckFormatHandler::getFormatStringRange() {
  7683. return OrigFormatExpr->getSourceRange();
  7684. }
  7685. CharSourceRange CheckFormatHandler::
  7686. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  7687. SourceLocation Start = getLocationOfByte(startSpecifier);
  7688. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  7689. // Advance the end SourceLocation by one due to half-open ranges.
  7690. End = End.getLocWithOffset(1);
  7691. return CharSourceRange::getCharRange(Start, End);
  7692. }
  7693. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  7694. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  7695. S.getLangOpts(), S.Context.getTargetInfo());
  7696. }
  7697. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  7698. unsigned specifierLen){
  7699. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  7700. getLocationOfByte(startSpecifier),
  7701. /*IsStringLocation*/true,
  7702. getSpecifierRange(startSpecifier, specifierLen));
  7703. }
  7704. void CheckFormatHandler::HandleInvalidLengthModifier(
  7705. const analyze_format_string::FormatSpecifier &FS,
  7706. const analyze_format_string::ConversionSpecifier &CS,
  7707. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  7708. using namespace analyze_format_string;
  7709. const LengthModifier &LM = FS.getLengthModifier();
  7710. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  7711. // See if we know how to fix this length modifier.
  7712. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  7713. if (FixedLM) {
  7714. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  7715. getLocationOfByte(LM.getStart()),
  7716. /*IsStringLocation*/true,
  7717. getSpecifierRange(startSpecifier, specifierLen));
  7718. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  7719. << FixedLM->toString()
  7720. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  7721. } else {
  7722. FixItHint Hint;
  7723. if (DiagID == diag::warn_format_nonsensical_length)
  7724. Hint = FixItHint::CreateRemoval(LMRange);
  7725. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  7726. getLocationOfByte(LM.getStart()),
  7727. /*IsStringLocation*/true,
  7728. getSpecifierRange(startSpecifier, specifierLen),
  7729. Hint);
  7730. }
  7731. }
  7732. void CheckFormatHandler::HandleNonStandardLengthModifier(
  7733. const analyze_format_string::FormatSpecifier &FS,
  7734. const char *startSpecifier, unsigned specifierLen) {
  7735. using namespace analyze_format_string;
  7736. const LengthModifier &LM = FS.getLengthModifier();
  7737. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  7738. // See if we know how to fix this length modifier.
  7739. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  7740. if (FixedLM) {
  7741. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  7742. << LM.toString() << 0,
  7743. getLocationOfByte(LM.getStart()),
  7744. /*IsStringLocation*/true,
  7745. getSpecifierRange(startSpecifier, specifierLen));
  7746. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  7747. << FixedLM->toString()
  7748. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  7749. } else {
  7750. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  7751. << LM.toString() << 0,
  7752. getLocationOfByte(LM.getStart()),
  7753. /*IsStringLocation*/true,
  7754. getSpecifierRange(startSpecifier, specifierLen));
  7755. }
  7756. }
  7757. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  7758. const analyze_format_string::ConversionSpecifier &CS,
  7759. const char *startSpecifier, unsigned specifierLen) {
  7760. using namespace analyze_format_string;
  7761. // See if we know how to fix this conversion specifier.
  7762. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  7763. if (FixedCS) {
  7764. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  7765. << CS.toString() << /*conversion specifier*/1,
  7766. getLocationOfByte(CS.getStart()),
  7767. /*IsStringLocation*/true,
  7768. getSpecifierRange(startSpecifier, specifierLen));
  7769. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  7770. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  7771. << FixedCS->toString()
  7772. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  7773. } else {
  7774. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  7775. << CS.toString() << /*conversion specifier*/1,
  7776. getLocationOfByte(CS.getStart()),
  7777. /*IsStringLocation*/true,
  7778. getSpecifierRange(startSpecifier, specifierLen));
  7779. }
  7780. }
  7781. void CheckFormatHandler::HandlePosition(const char *startPos,
  7782. unsigned posLen) {
  7783. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  7784. getLocationOfByte(startPos),
  7785. /*IsStringLocation*/true,
  7786. getSpecifierRange(startPos, posLen));
  7787. }
  7788. void
  7789. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  7790. analyze_format_string::PositionContext p) {
  7791. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  7792. << (unsigned) p,
  7793. getLocationOfByte(startPos), /*IsStringLocation*/true,
  7794. getSpecifierRange(startPos, posLen));
  7795. }
  7796. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  7797. unsigned posLen) {
  7798. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  7799. getLocationOfByte(startPos),
  7800. /*IsStringLocation*/true,
  7801. getSpecifierRange(startPos, posLen));
  7802. }
  7803. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  7804. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  7805. // The presence of a null character is likely an error.
  7806. EmitFormatDiagnostic(
  7807. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  7808. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  7809. getFormatStringRange());
  7810. }
  7811. }
  7812. // Note that this may return NULL if there was an error parsing or building
  7813. // one of the argument expressions.
  7814. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  7815. return Args[FirstDataArg + i];
  7816. }
  7817. void CheckFormatHandler::DoneProcessing() {
  7818. // Does the number of data arguments exceed the number of
  7819. // format conversions in the format string?
  7820. if (!HasVAListArg) {
  7821. // Find any arguments that weren't covered.
  7822. CoveredArgs.flip();
  7823. signed notCoveredArg = CoveredArgs.find_first();
  7824. if (notCoveredArg >= 0) {
  7825. assert((unsigned)notCoveredArg < NumDataArgs);
  7826. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  7827. } else {
  7828. UncoveredArg.setAllCovered();
  7829. }
  7830. }
  7831. }
  7832. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  7833. const Expr *ArgExpr) {
  7834. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  7835. "Invalid state");
  7836. if (!ArgExpr)
  7837. return;
  7838. SourceLocation Loc = ArgExpr->getBeginLoc();
  7839. if (S.getSourceManager().isInSystemMacro(Loc))
  7840. return;
  7841. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  7842. for (auto E : DiagnosticExprs)
  7843. PDiag << E->getSourceRange();
  7844. CheckFormatHandler::EmitFormatDiagnostic(
  7845. S, IsFunctionCall, DiagnosticExprs[0],
  7846. PDiag, Loc, /*IsStringLocation*/false,
  7847. DiagnosticExprs[0]->getSourceRange());
  7848. }
  7849. bool
  7850. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  7851. SourceLocation Loc,
  7852. const char *startSpec,
  7853. unsigned specifierLen,
  7854. const char *csStart,
  7855. unsigned csLen) {
  7856. bool keepGoing = true;
  7857. if (argIndex < NumDataArgs) {
  7858. // Consider the argument coverered, even though the specifier doesn't
  7859. // make sense.
  7860. CoveredArgs.set(argIndex);
  7861. }
  7862. else {
  7863. // If argIndex exceeds the number of data arguments we
  7864. // don't issue a warning because that is just a cascade of warnings (and
  7865. // they may have intended '%%' anyway). We don't want to continue processing
  7866. // the format string after this point, however, as we will like just get
  7867. // gibberish when trying to match arguments.
  7868. keepGoing = false;
  7869. }
  7870. StringRef Specifier(csStart, csLen);
  7871. // If the specifier in non-printable, it could be the first byte of a UTF-8
  7872. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  7873. // hex value.
  7874. std::string CodePointStr;
  7875. if (!llvm::sys::locale::isPrint(*csStart)) {
  7876. llvm::UTF32 CodePoint;
  7877. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  7878. const llvm::UTF8 *E =
  7879. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  7880. llvm::ConversionResult Result =
  7881. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  7882. if (Result != llvm::conversionOK) {
  7883. unsigned char FirstChar = *csStart;
  7884. CodePoint = (llvm::UTF32)FirstChar;
  7885. }
  7886. llvm::raw_string_ostream OS(CodePointStr);
  7887. if (CodePoint < 256)
  7888. OS << "\\x" << llvm::format("%02x", CodePoint);
  7889. else if (CodePoint <= 0xFFFF)
  7890. OS << "\\u" << llvm::format("%04x", CodePoint);
  7891. else
  7892. OS << "\\U" << llvm::format("%08x", CodePoint);
  7893. OS.flush();
  7894. Specifier = CodePointStr;
  7895. }
  7896. EmitFormatDiagnostic(
  7897. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  7898. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  7899. return keepGoing;
  7900. }
  7901. void
  7902. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  7903. const char *startSpec,
  7904. unsigned specifierLen) {
  7905. EmitFormatDiagnostic(
  7906. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  7907. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  7908. }
  7909. bool
  7910. CheckFormatHandler::CheckNumArgs(
  7911. const analyze_format_string::FormatSpecifier &FS,
  7912. const analyze_format_string::ConversionSpecifier &CS,
  7913. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  7914. if (argIndex >= NumDataArgs) {
  7915. PartialDiagnostic PDiag = FS.usesPositionalArg()
  7916. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  7917. << (argIndex+1) << NumDataArgs)
  7918. : S.PDiag(diag::warn_printf_insufficient_data_args);
  7919. EmitFormatDiagnostic(
  7920. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  7921. getSpecifierRange(startSpecifier, specifierLen));
  7922. // Since more arguments than conversion tokens are given, by extension
  7923. // all arguments are covered, so mark this as so.
  7924. UncoveredArg.setAllCovered();
  7925. return false;
  7926. }
  7927. return true;
  7928. }
  7929. template<typename Range>
  7930. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  7931. SourceLocation Loc,
  7932. bool IsStringLocation,
  7933. Range StringRange,
  7934. ArrayRef<FixItHint> FixIt) {
  7935. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  7936. Loc, IsStringLocation, StringRange, FixIt);
  7937. }
  7938. /// If the format string is not within the function call, emit a note
  7939. /// so that the function call and string are in diagnostic messages.
  7940. ///
  7941. /// \param InFunctionCall if true, the format string is within the function
  7942. /// call and only one diagnostic message will be produced. Otherwise, an
  7943. /// extra note will be emitted pointing to location of the format string.
  7944. ///
  7945. /// \param ArgumentExpr the expression that is passed as the format string
  7946. /// argument in the function call. Used for getting locations when two
  7947. /// diagnostics are emitted.
  7948. ///
  7949. /// \param PDiag the callee should already have provided any strings for the
  7950. /// diagnostic message. This function only adds locations and fixits
  7951. /// to diagnostics.
  7952. ///
  7953. /// \param Loc primary location for diagnostic. If two diagnostics are
  7954. /// required, one will be at Loc and a new SourceLocation will be created for
  7955. /// the other one.
  7956. ///
  7957. /// \param IsStringLocation if true, Loc points to the format string should be
  7958. /// used for the note. Otherwise, Loc points to the argument list and will
  7959. /// be used with PDiag.
  7960. ///
  7961. /// \param StringRange some or all of the string to highlight. This is
  7962. /// templated so it can accept either a CharSourceRange or a SourceRange.
  7963. ///
  7964. /// \param FixIt optional fix it hint for the format string.
  7965. template <typename Range>
  7966. void CheckFormatHandler::EmitFormatDiagnostic(
  7967. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  7968. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  7969. Range StringRange, ArrayRef<FixItHint> FixIt) {
  7970. if (InFunctionCall) {
  7971. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  7972. D << StringRange;
  7973. D << FixIt;
  7974. } else {
  7975. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  7976. << ArgumentExpr->getSourceRange();
  7977. const Sema::SemaDiagnosticBuilder &Note =
  7978. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  7979. diag::note_format_string_defined);
  7980. Note << StringRange;
  7981. Note << FixIt;
  7982. }
  7983. }
  7984. //===--- CHECK: Printf format string checking ------------------------------===//
  7985. namespace {
  7986. class CheckPrintfHandler : public CheckFormatHandler {
  7987. public:
  7988. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7989. const Expr *origFormatExpr,
  7990. const Sema::FormatStringType type, unsigned firstDataArg,
  7991. unsigned numDataArgs, bool isObjC, const char *beg,
  7992. bool hasVAListArg, ArrayRef<const Expr *> Args,
  7993. unsigned formatIdx, bool inFunctionCall,
  7994. Sema::VariadicCallType CallType,
  7995. llvm::SmallBitVector &CheckedVarArgs,
  7996. UncoveredArgHandler &UncoveredArg)
  7997. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7998. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7999. inFunctionCall, CallType, CheckedVarArgs,
  8000. UncoveredArg) {}
  8001. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  8002. /// Returns true if '%@' specifiers are allowed in the format string.
  8003. bool allowsObjCArg() const {
  8004. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  8005. FSType == Sema::FST_OSTrace;
  8006. }
  8007. bool HandleInvalidPrintfConversionSpecifier(
  8008. const analyze_printf::PrintfSpecifier &FS,
  8009. const char *startSpecifier,
  8010. unsigned specifierLen) override;
  8011. void handleInvalidMaskType(StringRef MaskType) override;
  8012. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  8013. const char *startSpecifier, unsigned specifierLen,
  8014. const TargetInfo &Target) override;
  8015. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  8016. const char *StartSpecifier,
  8017. unsigned SpecifierLen,
  8018. const Expr *E);
  8019. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  8020. const char *startSpecifier, unsigned specifierLen);
  8021. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  8022. const analyze_printf::OptionalAmount &Amt,
  8023. unsigned type,
  8024. const char *startSpecifier, unsigned specifierLen);
  8025. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  8026. const analyze_printf::OptionalFlag &flag,
  8027. const char *startSpecifier, unsigned specifierLen);
  8028. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  8029. const analyze_printf::OptionalFlag &ignoredFlag,
  8030. const analyze_printf::OptionalFlag &flag,
  8031. const char *startSpecifier, unsigned specifierLen);
  8032. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  8033. const Expr *E);
  8034. void HandleEmptyObjCModifierFlag(const char *startFlag,
  8035. unsigned flagLen) override;
  8036. void HandleInvalidObjCModifierFlag(const char *startFlag,
  8037. unsigned flagLen) override;
  8038. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  8039. const char *flagsEnd,
  8040. const char *conversionPosition)
  8041. override;
  8042. };
  8043. } // namespace
  8044. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  8045. const analyze_printf::PrintfSpecifier &FS,
  8046. const char *startSpecifier,
  8047. unsigned specifierLen) {
  8048. const analyze_printf::PrintfConversionSpecifier &CS =
  8049. FS.getConversionSpecifier();
  8050. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  8051. getLocationOfByte(CS.getStart()),
  8052. startSpecifier, specifierLen,
  8053. CS.getStart(), CS.getLength());
  8054. }
  8055. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  8056. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  8057. }
  8058. bool CheckPrintfHandler::HandleAmount(
  8059. const analyze_format_string::OptionalAmount &Amt,
  8060. unsigned k, const char *startSpecifier,
  8061. unsigned specifierLen) {
  8062. if (Amt.hasDataArgument()) {
  8063. if (!HasVAListArg) {
  8064. unsigned argIndex = Amt.getArgIndex();
  8065. if (argIndex >= NumDataArgs) {
  8066. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  8067. << k,
  8068. getLocationOfByte(Amt.getStart()),
  8069. /*IsStringLocation*/true,
  8070. getSpecifierRange(startSpecifier, specifierLen));
  8071. // Don't do any more checking. We will just emit
  8072. // spurious errors.
  8073. return false;
  8074. }
  8075. // Type check the data argument. It should be an 'int'.
  8076. // Although not in conformance with C99, we also allow the argument to be
  8077. // an 'unsigned int' as that is a reasonably safe case. GCC also
  8078. // doesn't emit a warning for that case.
  8079. CoveredArgs.set(argIndex);
  8080. const Expr *Arg = getDataArg(argIndex);
  8081. if (!Arg)
  8082. return false;
  8083. QualType T = Arg->getType();
  8084. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  8085. assert(AT.isValid());
  8086. if (!AT.matchesType(S.Context, T)) {
  8087. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  8088. << k << AT.getRepresentativeTypeName(S.Context)
  8089. << T << Arg->getSourceRange(),
  8090. getLocationOfByte(Amt.getStart()),
  8091. /*IsStringLocation*/true,
  8092. getSpecifierRange(startSpecifier, specifierLen));
  8093. // Don't do any more checking. We will just emit
  8094. // spurious errors.
  8095. return false;
  8096. }
  8097. }
  8098. }
  8099. return true;
  8100. }
  8101. void CheckPrintfHandler::HandleInvalidAmount(
  8102. const analyze_printf::PrintfSpecifier &FS,
  8103. const analyze_printf::OptionalAmount &Amt,
  8104. unsigned type,
  8105. const char *startSpecifier,
  8106. unsigned specifierLen) {
  8107. const analyze_printf::PrintfConversionSpecifier &CS =
  8108. FS.getConversionSpecifier();
  8109. FixItHint fixit =
  8110. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  8111. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  8112. Amt.getConstantLength()))
  8113. : FixItHint();
  8114. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  8115. << type << CS.toString(),
  8116. getLocationOfByte(Amt.getStart()),
  8117. /*IsStringLocation*/true,
  8118. getSpecifierRange(startSpecifier, specifierLen),
  8119. fixit);
  8120. }
  8121. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  8122. const analyze_printf::OptionalFlag &flag,
  8123. const char *startSpecifier,
  8124. unsigned specifierLen) {
  8125. // Warn about pointless flag with a fixit removal.
  8126. const analyze_printf::PrintfConversionSpecifier &CS =
  8127. FS.getConversionSpecifier();
  8128. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  8129. << flag.toString() << CS.toString(),
  8130. getLocationOfByte(flag.getPosition()),
  8131. /*IsStringLocation*/true,
  8132. getSpecifierRange(startSpecifier, specifierLen),
  8133. FixItHint::CreateRemoval(
  8134. getSpecifierRange(flag.getPosition(), 1)));
  8135. }
  8136. void CheckPrintfHandler::HandleIgnoredFlag(
  8137. const analyze_printf::PrintfSpecifier &FS,
  8138. const analyze_printf::OptionalFlag &ignoredFlag,
  8139. const analyze_printf::OptionalFlag &flag,
  8140. const char *startSpecifier,
  8141. unsigned specifierLen) {
  8142. // Warn about ignored flag with a fixit removal.
  8143. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  8144. << ignoredFlag.toString() << flag.toString(),
  8145. getLocationOfByte(ignoredFlag.getPosition()),
  8146. /*IsStringLocation*/true,
  8147. getSpecifierRange(startSpecifier, specifierLen),
  8148. FixItHint::CreateRemoval(
  8149. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  8150. }
  8151. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  8152. unsigned flagLen) {
  8153. // Warn about an empty flag.
  8154. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  8155. getLocationOfByte(startFlag),
  8156. /*IsStringLocation*/true,
  8157. getSpecifierRange(startFlag, flagLen));
  8158. }
  8159. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  8160. unsigned flagLen) {
  8161. // Warn about an invalid flag.
  8162. auto Range = getSpecifierRange(startFlag, flagLen);
  8163. StringRef flag(startFlag, flagLen);
  8164. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  8165. getLocationOfByte(startFlag),
  8166. /*IsStringLocation*/true,
  8167. Range, FixItHint::CreateRemoval(Range));
  8168. }
  8169. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  8170. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  8171. // Warn about using '[...]' without a '@' conversion.
  8172. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  8173. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  8174. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  8175. getLocationOfByte(conversionPosition),
  8176. /*IsStringLocation*/true,
  8177. Range, FixItHint::CreateRemoval(Range));
  8178. }
  8179. // Determines if the specified is a C++ class or struct containing
  8180. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  8181. // "c_str()").
  8182. template<typename MemberKind>
  8183. static llvm::SmallPtrSet<MemberKind*, 1>
  8184. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  8185. const RecordType *RT = Ty->getAs<RecordType>();
  8186. llvm::SmallPtrSet<MemberKind*, 1> Results;
  8187. if (!RT)
  8188. return Results;
  8189. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  8190. if (!RD || !RD->getDefinition())
  8191. return Results;
  8192. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  8193. Sema::LookupMemberName);
  8194. R.suppressDiagnostics();
  8195. // We just need to include all members of the right kind turned up by the
  8196. // filter, at this point.
  8197. if (S.LookupQualifiedName(R, RT->getDecl()))
  8198. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  8199. NamedDecl *decl = (*I)->getUnderlyingDecl();
  8200. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  8201. Results.insert(FK);
  8202. }
  8203. return Results;
  8204. }
  8205. /// Check if we could call '.c_str()' on an object.
  8206. ///
  8207. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  8208. /// allow the call, or if it would be ambiguous).
  8209. bool Sema::hasCStrMethod(const Expr *E) {
  8210. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  8211. MethodSet Results =
  8212. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  8213. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  8214. MI != ME; ++MI)
  8215. if ((*MI)->getMinRequiredArguments() == 0)
  8216. return true;
  8217. return false;
  8218. }
  8219. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  8220. // better diagnostic if so. AT is assumed to be valid.
  8221. // Returns true when a c_str() conversion method is found.
  8222. bool CheckPrintfHandler::checkForCStrMembers(
  8223. const analyze_printf::ArgType &AT, const Expr *E) {
  8224. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  8225. MethodSet Results =
  8226. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  8227. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  8228. MI != ME; ++MI) {
  8229. const CXXMethodDecl *Method = *MI;
  8230. if (Method->getMinRequiredArguments() == 0 &&
  8231. AT.matchesType(S.Context, Method->getReturnType())) {
  8232. // FIXME: Suggest parens if the expression needs them.
  8233. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  8234. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  8235. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  8236. return true;
  8237. }
  8238. }
  8239. return false;
  8240. }
  8241. bool CheckPrintfHandler::HandlePrintfSpecifier(
  8242. const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
  8243. unsigned specifierLen, const TargetInfo &Target) {
  8244. using namespace analyze_format_string;
  8245. using namespace analyze_printf;
  8246. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  8247. if (FS.consumesDataArgument()) {
  8248. if (atFirstArg) {
  8249. atFirstArg = false;
  8250. usesPositionalArgs = FS.usesPositionalArg();
  8251. }
  8252. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  8253. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  8254. startSpecifier, specifierLen);
  8255. return false;
  8256. }
  8257. }
  8258. // First check if the field width, precision, and conversion specifier
  8259. // have matching data arguments.
  8260. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  8261. startSpecifier, specifierLen)) {
  8262. return false;
  8263. }
  8264. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  8265. startSpecifier, specifierLen)) {
  8266. return false;
  8267. }
  8268. if (!CS.consumesDataArgument()) {
  8269. // FIXME: Technically specifying a precision or field width here
  8270. // makes no sense. Worth issuing a warning at some point.
  8271. return true;
  8272. }
  8273. // Consume the argument.
  8274. unsigned argIndex = FS.getArgIndex();
  8275. if (argIndex < NumDataArgs) {
  8276. // The check to see if the argIndex is valid will come later.
  8277. // We set the bit here because we may exit early from this
  8278. // function if we encounter some other error.
  8279. CoveredArgs.set(argIndex);
  8280. }
  8281. // FreeBSD kernel extensions.
  8282. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  8283. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  8284. // We need at least two arguments.
  8285. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  8286. return false;
  8287. // Claim the second argument.
  8288. CoveredArgs.set(argIndex + 1);
  8289. // Type check the first argument (int for %b, pointer for %D)
  8290. const Expr *Ex = getDataArg(argIndex);
  8291. const analyze_printf::ArgType &AT =
  8292. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  8293. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  8294. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  8295. EmitFormatDiagnostic(
  8296. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  8297. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  8298. << false << Ex->getSourceRange(),
  8299. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  8300. getSpecifierRange(startSpecifier, specifierLen));
  8301. // Type check the second argument (char * for both %b and %D)
  8302. Ex = getDataArg(argIndex + 1);
  8303. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  8304. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  8305. EmitFormatDiagnostic(
  8306. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  8307. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  8308. << false << Ex->getSourceRange(),
  8309. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  8310. getSpecifierRange(startSpecifier, specifierLen));
  8311. return true;
  8312. }
  8313. // Check for using an Objective-C specific conversion specifier
  8314. // in a non-ObjC literal.
  8315. if (!allowsObjCArg() && CS.isObjCArg()) {
  8316. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  8317. specifierLen);
  8318. }
  8319. // %P can only be used with os_log.
  8320. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  8321. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  8322. specifierLen);
  8323. }
  8324. // %n is not allowed with os_log.
  8325. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  8326. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  8327. getLocationOfByte(CS.getStart()),
  8328. /*IsStringLocation*/ false,
  8329. getSpecifierRange(startSpecifier, specifierLen));
  8330. return true;
  8331. }
  8332. // Only scalars are allowed for os_trace.
  8333. if (FSType == Sema::FST_OSTrace &&
  8334. (CS.getKind() == ConversionSpecifier::PArg ||
  8335. CS.getKind() == ConversionSpecifier::sArg ||
  8336. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  8337. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  8338. specifierLen);
  8339. }
  8340. // Check for use of public/private annotation outside of os_log().
  8341. if (FSType != Sema::FST_OSLog) {
  8342. if (FS.isPublic().isSet()) {
  8343. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  8344. << "public",
  8345. getLocationOfByte(FS.isPublic().getPosition()),
  8346. /*IsStringLocation*/ false,
  8347. getSpecifierRange(startSpecifier, specifierLen));
  8348. }
  8349. if (FS.isPrivate().isSet()) {
  8350. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  8351. << "private",
  8352. getLocationOfByte(FS.isPrivate().getPosition()),
  8353. /*IsStringLocation*/ false,
  8354. getSpecifierRange(startSpecifier, specifierLen));
  8355. }
  8356. }
  8357. const llvm::Triple &Triple = Target.getTriple();
  8358. if (CS.getKind() == ConversionSpecifier::nArg &&
  8359. (Triple.isAndroid() || Triple.isOSFuchsia())) {
  8360. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
  8361. getLocationOfByte(CS.getStart()),
  8362. /*IsStringLocation*/ false,
  8363. getSpecifierRange(startSpecifier, specifierLen));
  8364. }
  8365. // Check for invalid use of field width
  8366. if (!FS.hasValidFieldWidth()) {
  8367. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  8368. startSpecifier, specifierLen);
  8369. }
  8370. // Check for invalid use of precision
  8371. if (!FS.hasValidPrecision()) {
  8372. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  8373. startSpecifier, specifierLen);
  8374. }
  8375. // Precision is mandatory for %P specifier.
  8376. if (CS.getKind() == ConversionSpecifier::PArg &&
  8377. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  8378. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  8379. getLocationOfByte(startSpecifier),
  8380. /*IsStringLocation*/ false,
  8381. getSpecifierRange(startSpecifier, specifierLen));
  8382. }
  8383. // Check each flag does not conflict with any other component.
  8384. if (!FS.hasValidThousandsGroupingPrefix())
  8385. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  8386. if (!FS.hasValidLeadingZeros())
  8387. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  8388. if (!FS.hasValidPlusPrefix())
  8389. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  8390. if (!FS.hasValidSpacePrefix())
  8391. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  8392. if (!FS.hasValidAlternativeForm())
  8393. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  8394. if (!FS.hasValidLeftJustified())
  8395. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  8396. // Check that flags are not ignored by another flag
  8397. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  8398. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  8399. startSpecifier, specifierLen);
  8400. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  8401. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  8402. startSpecifier, specifierLen);
  8403. // Check the length modifier is valid with the given conversion specifier.
  8404. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  8405. S.getLangOpts()))
  8406. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  8407. diag::warn_format_nonsensical_length);
  8408. else if (!FS.hasStandardLengthModifier())
  8409. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  8410. else if (!FS.hasStandardLengthConversionCombination())
  8411. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  8412. diag::warn_format_non_standard_conversion_spec);
  8413. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  8414. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  8415. // The remaining checks depend on the data arguments.
  8416. if (HasVAListArg)
  8417. return true;
  8418. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  8419. return false;
  8420. const Expr *Arg = getDataArg(argIndex);
  8421. if (!Arg)
  8422. return true;
  8423. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  8424. }
  8425. static bool requiresParensToAddCast(const Expr *E) {
  8426. // FIXME: We should have a general way to reason about operator
  8427. // precedence and whether parens are actually needed here.
  8428. // Take care of a few common cases where they aren't.
  8429. const Expr *Inside = E->IgnoreImpCasts();
  8430. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  8431. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  8432. switch (Inside->getStmtClass()) {
  8433. case Stmt::ArraySubscriptExprClass:
  8434. case Stmt::CallExprClass:
  8435. case Stmt::CharacterLiteralClass:
  8436. case Stmt::CXXBoolLiteralExprClass:
  8437. case Stmt::DeclRefExprClass:
  8438. case Stmt::FloatingLiteralClass:
  8439. case Stmt::IntegerLiteralClass:
  8440. case Stmt::MemberExprClass:
  8441. case Stmt::ObjCArrayLiteralClass:
  8442. case Stmt::ObjCBoolLiteralExprClass:
  8443. case Stmt::ObjCBoxedExprClass:
  8444. case Stmt::ObjCDictionaryLiteralClass:
  8445. case Stmt::ObjCEncodeExprClass:
  8446. case Stmt::ObjCIvarRefExprClass:
  8447. case Stmt::ObjCMessageExprClass:
  8448. case Stmt::ObjCPropertyRefExprClass:
  8449. case Stmt::ObjCStringLiteralClass:
  8450. case Stmt::ObjCSubscriptRefExprClass:
  8451. case Stmt::ParenExprClass:
  8452. case Stmt::StringLiteralClass:
  8453. case Stmt::UnaryOperatorClass:
  8454. return false;
  8455. default:
  8456. return true;
  8457. }
  8458. }
  8459. static std::pair<QualType, StringRef>
  8460. shouldNotPrintDirectly(const ASTContext &Context,
  8461. QualType IntendedTy,
  8462. const Expr *E) {
  8463. // Use a 'while' to peel off layers of typedefs.
  8464. QualType TyTy = IntendedTy;
  8465. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  8466. StringRef Name = UserTy->getDecl()->getName();
  8467. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  8468. .Case("CFIndex", Context.getNSIntegerType())
  8469. .Case("NSInteger", Context.getNSIntegerType())
  8470. .Case("NSUInteger", Context.getNSUIntegerType())
  8471. .Case("SInt32", Context.IntTy)
  8472. .Case("UInt32", Context.UnsignedIntTy)
  8473. .Default(QualType());
  8474. if (!CastTy.isNull())
  8475. return std::make_pair(CastTy, Name);
  8476. TyTy = UserTy->desugar();
  8477. }
  8478. // Strip parens if necessary.
  8479. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  8480. return shouldNotPrintDirectly(Context,
  8481. PE->getSubExpr()->getType(),
  8482. PE->getSubExpr());
  8483. // If this is a conditional expression, then its result type is constructed
  8484. // via usual arithmetic conversions and thus there might be no necessary
  8485. // typedef sugar there. Recurse to operands to check for NSInteger &
  8486. // Co. usage condition.
  8487. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  8488. QualType TrueTy, FalseTy;
  8489. StringRef TrueName, FalseName;
  8490. std::tie(TrueTy, TrueName) =
  8491. shouldNotPrintDirectly(Context,
  8492. CO->getTrueExpr()->getType(),
  8493. CO->getTrueExpr());
  8494. std::tie(FalseTy, FalseName) =
  8495. shouldNotPrintDirectly(Context,
  8496. CO->getFalseExpr()->getType(),
  8497. CO->getFalseExpr());
  8498. if (TrueTy == FalseTy)
  8499. return std::make_pair(TrueTy, TrueName);
  8500. else if (TrueTy.isNull())
  8501. return std::make_pair(FalseTy, FalseName);
  8502. else if (FalseTy.isNull())
  8503. return std::make_pair(TrueTy, TrueName);
  8504. }
  8505. return std::make_pair(QualType(), StringRef());
  8506. }
  8507. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  8508. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  8509. /// type do not count.
  8510. static bool
  8511. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  8512. QualType From = ICE->getSubExpr()->getType();
  8513. QualType To = ICE->getType();
  8514. // It's an integer promotion if the destination type is the promoted
  8515. // source type.
  8516. if (ICE->getCastKind() == CK_IntegralCast &&
  8517. From->isPromotableIntegerType() &&
  8518. S.Context.getPromotedIntegerType(From) == To)
  8519. return true;
  8520. // Look through vector types, since we do default argument promotion for
  8521. // those in OpenCL.
  8522. if (const auto *VecTy = From->getAs<ExtVectorType>())
  8523. From = VecTy->getElementType();
  8524. if (const auto *VecTy = To->getAs<ExtVectorType>())
  8525. To = VecTy->getElementType();
  8526. // It's a floating promotion if the source type is a lower rank.
  8527. return ICE->getCastKind() == CK_FloatingCast &&
  8528. S.Context.getFloatingTypeOrder(From, To) < 0;
  8529. }
  8530. bool
  8531. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  8532. const char *StartSpecifier,
  8533. unsigned SpecifierLen,
  8534. const Expr *E) {
  8535. using namespace analyze_format_string;
  8536. using namespace analyze_printf;
  8537. // Now type check the data expression that matches the
  8538. // format specifier.
  8539. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  8540. if (!AT.isValid())
  8541. return true;
  8542. QualType ExprTy = E->getType();
  8543. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  8544. ExprTy = TET->getUnderlyingExpr()->getType();
  8545. }
  8546. // Diagnose attempts to print a boolean value as a character. Unlike other
  8547. // -Wformat diagnostics, this is fine from a type perspective, but it still
  8548. // doesn't make sense.
  8549. if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
  8550. E->isKnownToHaveBooleanValue()) {
  8551. const CharSourceRange &CSR =
  8552. getSpecifierRange(StartSpecifier, SpecifierLen);
  8553. SmallString<4> FSString;
  8554. llvm::raw_svector_ostream os(FSString);
  8555. FS.toString(os);
  8556. EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
  8557. << FSString,
  8558. E->getExprLoc(), false, CSR);
  8559. return true;
  8560. }
  8561. analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
  8562. if (Match == analyze_printf::ArgType::Match)
  8563. return true;
  8564. // Look through argument promotions for our error message's reported type.
  8565. // This includes the integral and floating promotions, but excludes array
  8566. // and function pointer decay (seeing that an argument intended to be a
  8567. // string has type 'char [6]' is probably more confusing than 'char *') and
  8568. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  8569. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  8570. if (isArithmeticArgumentPromotion(S, ICE)) {
  8571. E = ICE->getSubExpr();
  8572. ExprTy = E->getType();
  8573. // Check if we didn't match because of an implicit cast from a 'char'
  8574. // or 'short' to an 'int'. This is done because printf is a varargs
  8575. // function.
  8576. if (ICE->getType() == S.Context.IntTy ||
  8577. ICE->getType() == S.Context.UnsignedIntTy) {
  8578. // All further checking is done on the subexpression
  8579. const analyze_printf::ArgType::MatchKind ImplicitMatch =
  8580. AT.matchesType(S.Context, ExprTy);
  8581. if (ImplicitMatch == analyze_printf::ArgType::Match)
  8582. return true;
  8583. if (ImplicitMatch == ArgType::NoMatchPedantic ||
  8584. ImplicitMatch == ArgType::NoMatchTypeConfusion)
  8585. Match = ImplicitMatch;
  8586. }
  8587. }
  8588. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  8589. // Special case for 'a', which has type 'int' in C.
  8590. // Note, however, that we do /not/ want to treat multibyte constants like
  8591. // 'MooV' as characters! This form is deprecated but still exists. In
  8592. // addition, don't treat expressions as of type 'char' if one byte length
  8593. // modifier is provided.
  8594. if (ExprTy == S.Context.IntTy &&
  8595. FS.getLengthModifier().getKind() != LengthModifier::AsChar)
  8596. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  8597. ExprTy = S.Context.CharTy;
  8598. }
  8599. // Look through enums to their underlying type.
  8600. bool IsEnum = false;
  8601. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  8602. ExprTy = EnumTy->getDecl()->getIntegerType();
  8603. IsEnum = true;
  8604. }
  8605. // %C in an Objective-C context prints a unichar, not a wchar_t.
  8606. // If the argument is an integer of some kind, believe the %C and suggest
  8607. // a cast instead of changing the conversion specifier.
  8608. QualType IntendedTy = ExprTy;
  8609. if (isObjCContext() &&
  8610. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  8611. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  8612. !ExprTy->isCharType()) {
  8613. // 'unichar' is defined as a typedef of unsigned short, but we should
  8614. // prefer using the typedef if it is visible.
  8615. IntendedTy = S.Context.UnsignedShortTy;
  8616. // While we are here, check if the value is an IntegerLiteral that happens
  8617. // to be within the valid range.
  8618. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  8619. const llvm::APInt &V = IL->getValue();
  8620. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  8621. return true;
  8622. }
  8623. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  8624. Sema::LookupOrdinaryName);
  8625. if (S.LookupName(Result, S.getCurScope())) {
  8626. NamedDecl *ND = Result.getFoundDecl();
  8627. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  8628. if (TD->getUnderlyingType() == IntendedTy)
  8629. IntendedTy = S.Context.getTypedefType(TD);
  8630. }
  8631. }
  8632. }
  8633. // Special-case some of Darwin's platform-independence types by suggesting
  8634. // casts to primitive types that are known to be large enough.
  8635. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  8636. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  8637. QualType CastTy;
  8638. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  8639. if (!CastTy.isNull()) {
  8640. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  8641. // (long in ASTContext). Only complain to pedants.
  8642. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  8643. (AT.isSizeT() || AT.isPtrdiffT()) &&
  8644. AT.matchesType(S.Context, CastTy))
  8645. Match = ArgType::NoMatchPedantic;
  8646. IntendedTy = CastTy;
  8647. ShouldNotPrintDirectly = true;
  8648. }
  8649. }
  8650. // We may be able to offer a FixItHint if it is a supported type.
  8651. PrintfSpecifier fixedFS = FS;
  8652. bool Success =
  8653. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  8654. if (Success) {
  8655. // Get the fix string from the fixed format specifier
  8656. SmallString<16> buf;
  8657. llvm::raw_svector_ostream os(buf);
  8658. fixedFS.toString(os);
  8659. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  8660. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  8661. unsigned Diag;
  8662. switch (Match) {
  8663. case ArgType::Match: llvm_unreachable("expected non-matching");
  8664. case ArgType::NoMatchPedantic:
  8665. Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  8666. break;
  8667. case ArgType::NoMatchTypeConfusion:
  8668. Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
  8669. break;
  8670. case ArgType::NoMatch:
  8671. Diag = diag::warn_format_conversion_argument_type_mismatch;
  8672. break;
  8673. }
  8674. // In this case, the specifier is wrong and should be changed to match
  8675. // the argument.
  8676. EmitFormatDiagnostic(S.PDiag(Diag)
  8677. << AT.getRepresentativeTypeName(S.Context)
  8678. << IntendedTy << IsEnum << E->getSourceRange(),
  8679. E->getBeginLoc(),
  8680. /*IsStringLocation*/ false, SpecRange,
  8681. FixItHint::CreateReplacement(SpecRange, os.str()));
  8682. } else {
  8683. // The canonical type for formatting this value is different from the
  8684. // actual type of the expression. (This occurs, for example, with Darwin's
  8685. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  8686. // should be printed as 'long' for 64-bit compatibility.)
  8687. // Rather than emitting a normal format/argument mismatch, we want to
  8688. // add a cast to the recommended type (and correct the format string
  8689. // if necessary).
  8690. SmallString<16> CastBuf;
  8691. llvm::raw_svector_ostream CastFix(CastBuf);
  8692. CastFix << "(";
  8693. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  8694. CastFix << ")";
  8695. SmallVector<FixItHint,4> Hints;
  8696. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  8697. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  8698. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  8699. // If there's already a cast present, just replace it.
  8700. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  8701. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  8702. } else if (!requiresParensToAddCast(E)) {
  8703. // If the expression has high enough precedence,
  8704. // just write the C-style cast.
  8705. Hints.push_back(
  8706. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  8707. } else {
  8708. // Otherwise, add parens around the expression as well as the cast.
  8709. CastFix << "(";
  8710. Hints.push_back(
  8711. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  8712. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  8713. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  8714. }
  8715. if (ShouldNotPrintDirectly) {
  8716. // The expression has a type that should not be printed directly.
  8717. // We extract the name from the typedef because we don't want to show
  8718. // the underlying type in the diagnostic.
  8719. StringRef Name;
  8720. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  8721. Name = TypedefTy->getDecl()->getName();
  8722. else
  8723. Name = CastTyName;
  8724. unsigned Diag = Match == ArgType::NoMatchPedantic
  8725. ? diag::warn_format_argument_needs_cast_pedantic
  8726. : diag::warn_format_argument_needs_cast;
  8727. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  8728. << E->getSourceRange(),
  8729. E->getBeginLoc(), /*IsStringLocation=*/false,
  8730. SpecRange, Hints);
  8731. } else {
  8732. // In this case, the expression could be printed using a different
  8733. // specifier, but we've decided that the specifier is probably correct
  8734. // and we should cast instead. Just use the normal warning message.
  8735. EmitFormatDiagnostic(
  8736. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  8737. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  8738. << E->getSourceRange(),
  8739. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  8740. }
  8741. }
  8742. } else {
  8743. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  8744. SpecifierLen);
  8745. // Since the warning for passing non-POD types to variadic functions
  8746. // was deferred until now, we emit a warning for non-POD
  8747. // arguments here.
  8748. switch (S.isValidVarArgType(ExprTy)) {
  8749. case Sema::VAK_Valid:
  8750. case Sema::VAK_ValidInCXX11: {
  8751. unsigned Diag;
  8752. switch (Match) {
  8753. case ArgType::Match: llvm_unreachable("expected non-matching");
  8754. case ArgType::NoMatchPedantic:
  8755. Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  8756. break;
  8757. case ArgType::NoMatchTypeConfusion:
  8758. Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
  8759. break;
  8760. case ArgType::NoMatch:
  8761. Diag = diag::warn_format_conversion_argument_type_mismatch;
  8762. break;
  8763. }
  8764. EmitFormatDiagnostic(
  8765. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  8766. << IsEnum << CSR << E->getSourceRange(),
  8767. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  8768. break;
  8769. }
  8770. case Sema::VAK_Undefined:
  8771. case Sema::VAK_MSVCUndefined:
  8772. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  8773. << S.getLangOpts().CPlusPlus11 << ExprTy
  8774. << CallType
  8775. << AT.getRepresentativeTypeName(S.Context) << CSR
  8776. << E->getSourceRange(),
  8777. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  8778. checkForCStrMembers(AT, E);
  8779. break;
  8780. case Sema::VAK_Invalid:
  8781. if (ExprTy->isObjCObjectType())
  8782. EmitFormatDiagnostic(
  8783. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  8784. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  8785. << AT.getRepresentativeTypeName(S.Context) << CSR
  8786. << E->getSourceRange(),
  8787. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  8788. else
  8789. // FIXME: If this is an initializer list, suggest removing the braces
  8790. // or inserting a cast to the target type.
  8791. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  8792. << isa<InitListExpr>(E) << ExprTy << CallType
  8793. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  8794. break;
  8795. }
  8796. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  8797. "format string specifier index out of range");
  8798. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  8799. }
  8800. return true;
  8801. }
  8802. //===--- CHECK: Scanf format string checking ------------------------------===//
  8803. namespace {
  8804. class CheckScanfHandler : public CheckFormatHandler {
  8805. public:
  8806. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  8807. const Expr *origFormatExpr, Sema::FormatStringType type,
  8808. unsigned firstDataArg, unsigned numDataArgs,
  8809. const char *beg, bool hasVAListArg,
  8810. ArrayRef<const Expr *> Args, unsigned formatIdx,
  8811. bool inFunctionCall, Sema::VariadicCallType CallType,
  8812. llvm::SmallBitVector &CheckedVarArgs,
  8813. UncoveredArgHandler &UncoveredArg)
  8814. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  8815. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  8816. inFunctionCall, CallType, CheckedVarArgs,
  8817. UncoveredArg) {}
  8818. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  8819. const char *startSpecifier,
  8820. unsigned specifierLen) override;
  8821. bool HandleInvalidScanfConversionSpecifier(
  8822. const analyze_scanf::ScanfSpecifier &FS,
  8823. const char *startSpecifier,
  8824. unsigned specifierLen) override;
  8825. void HandleIncompleteScanList(const char *start, const char *end) override;
  8826. };
  8827. } // namespace
  8828. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  8829. const char *end) {
  8830. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  8831. getLocationOfByte(end), /*IsStringLocation*/true,
  8832. getSpecifierRange(start, end - start));
  8833. }
  8834. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  8835. const analyze_scanf::ScanfSpecifier &FS,
  8836. const char *startSpecifier,
  8837. unsigned specifierLen) {
  8838. const analyze_scanf::ScanfConversionSpecifier &CS =
  8839. FS.getConversionSpecifier();
  8840. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  8841. getLocationOfByte(CS.getStart()),
  8842. startSpecifier, specifierLen,
  8843. CS.getStart(), CS.getLength());
  8844. }
  8845. bool CheckScanfHandler::HandleScanfSpecifier(
  8846. const analyze_scanf::ScanfSpecifier &FS,
  8847. const char *startSpecifier,
  8848. unsigned specifierLen) {
  8849. using namespace analyze_scanf;
  8850. using namespace analyze_format_string;
  8851. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  8852. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  8853. // be used to decide if we are using positional arguments consistently.
  8854. if (FS.consumesDataArgument()) {
  8855. if (atFirstArg) {
  8856. atFirstArg = false;
  8857. usesPositionalArgs = FS.usesPositionalArg();
  8858. }
  8859. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  8860. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  8861. startSpecifier, specifierLen);
  8862. return false;
  8863. }
  8864. }
  8865. // Check if the field with is non-zero.
  8866. const OptionalAmount &Amt = FS.getFieldWidth();
  8867. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  8868. if (Amt.getConstantAmount() == 0) {
  8869. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  8870. Amt.getConstantLength());
  8871. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  8872. getLocationOfByte(Amt.getStart()),
  8873. /*IsStringLocation*/true, R,
  8874. FixItHint::CreateRemoval(R));
  8875. }
  8876. }
  8877. if (!FS.consumesDataArgument()) {
  8878. // FIXME: Technically specifying a precision or field width here
  8879. // makes no sense. Worth issuing a warning at some point.
  8880. return true;
  8881. }
  8882. // Consume the argument.
  8883. unsigned argIndex = FS.getArgIndex();
  8884. if (argIndex < NumDataArgs) {
  8885. // The check to see if the argIndex is valid will come later.
  8886. // We set the bit here because we may exit early from this
  8887. // function if we encounter some other error.
  8888. CoveredArgs.set(argIndex);
  8889. }
  8890. // Check the length modifier is valid with the given conversion specifier.
  8891. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  8892. S.getLangOpts()))
  8893. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  8894. diag::warn_format_nonsensical_length);
  8895. else if (!FS.hasStandardLengthModifier())
  8896. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  8897. else if (!FS.hasStandardLengthConversionCombination())
  8898. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  8899. diag::warn_format_non_standard_conversion_spec);
  8900. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  8901. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  8902. // The remaining checks depend on the data arguments.
  8903. if (HasVAListArg)
  8904. return true;
  8905. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  8906. return false;
  8907. // Check that the argument type matches the format specifier.
  8908. const Expr *Ex = getDataArg(argIndex);
  8909. if (!Ex)
  8910. return true;
  8911. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  8912. if (!AT.isValid()) {
  8913. return true;
  8914. }
  8915. analyze_format_string::ArgType::MatchKind Match =
  8916. AT.matchesType(S.Context, Ex->getType());
  8917. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  8918. if (Match == analyze_format_string::ArgType::Match)
  8919. return true;
  8920. ScanfSpecifier fixedFS = FS;
  8921. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  8922. S.getLangOpts(), S.Context);
  8923. unsigned Diag =
  8924. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  8925. : diag::warn_format_conversion_argument_type_mismatch;
  8926. if (Success) {
  8927. // Get the fix string from the fixed format specifier.
  8928. SmallString<128> buf;
  8929. llvm::raw_svector_ostream os(buf);
  8930. fixedFS.toString(os);
  8931. EmitFormatDiagnostic(
  8932. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  8933. << Ex->getType() << false << Ex->getSourceRange(),
  8934. Ex->getBeginLoc(),
  8935. /*IsStringLocation*/ false,
  8936. getSpecifierRange(startSpecifier, specifierLen),
  8937. FixItHint::CreateReplacement(
  8938. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  8939. } else {
  8940. EmitFormatDiagnostic(S.PDiag(Diag)
  8941. << AT.getRepresentativeTypeName(S.Context)
  8942. << Ex->getType() << false << Ex->getSourceRange(),
  8943. Ex->getBeginLoc(),
  8944. /*IsStringLocation*/ false,
  8945. getSpecifierRange(startSpecifier, specifierLen));
  8946. }
  8947. return true;
  8948. }
  8949. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  8950. const Expr *OrigFormatExpr,
  8951. ArrayRef<const Expr *> Args,
  8952. bool HasVAListArg, unsigned format_idx,
  8953. unsigned firstDataArg,
  8954. Sema::FormatStringType Type,
  8955. bool inFunctionCall,
  8956. Sema::VariadicCallType CallType,
  8957. llvm::SmallBitVector &CheckedVarArgs,
  8958. UncoveredArgHandler &UncoveredArg,
  8959. bool IgnoreStringsWithoutSpecifiers) {
  8960. // CHECK: is the format string a wide literal?
  8961. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  8962. CheckFormatHandler::EmitFormatDiagnostic(
  8963. S, inFunctionCall, Args[format_idx],
  8964. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  8965. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  8966. return;
  8967. }
  8968. // Str - The format string. NOTE: this is NOT null-terminated!
  8969. StringRef StrRef = FExpr->getString();
  8970. const char *Str = StrRef.data();
  8971. // Account for cases where the string literal is truncated in a declaration.
  8972. const ConstantArrayType *T =
  8973. S.Context.getAsConstantArrayType(FExpr->getType());
  8974. assert(T && "String literal not of constant array type!");
  8975. size_t TypeSize = T->getSize().getZExtValue();
  8976. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  8977. const unsigned numDataArgs = Args.size() - firstDataArg;
  8978. if (IgnoreStringsWithoutSpecifiers &&
  8979. !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
  8980. Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
  8981. return;
  8982. // Emit a warning if the string literal is truncated and does not contain an
  8983. // embedded null character.
  8984. if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
  8985. CheckFormatHandler::EmitFormatDiagnostic(
  8986. S, inFunctionCall, Args[format_idx],
  8987. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  8988. FExpr->getBeginLoc(),
  8989. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  8990. return;
  8991. }
  8992. // CHECK: empty format string?
  8993. if (StrLen == 0 && numDataArgs > 0) {
  8994. CheckFormatHandler::EmitFormatDiagnostic(
  8995. S, inFunctionCall, Args[format_idx],
  8996. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  8997. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  8998. return;
  8999. }
  9000. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  9001. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  9002. Type == Sema::FST_OSTrace) {
  9003. CheckPrintfHandler H(
  9004. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  9005. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  9006. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  9007. CheckedVarArgs, UncoveredArg);
  9008. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  9009. S.getLangOpts(),
  9010. S.Context.getTargetInfo(),
  9011. Type == Sema::FST_FreeBSDKPrintf))
  9012. H.DoneProcessing();
  9013. } else if (Type == Sema::FST_Scanf) {
  9014. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  9015. numDataArgs, Str, HasVAListArg, Args, format_idx,
  9016. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  9017. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  9018. S.getLangOpts(),
  9019. S.Context.getTargetInfo()))
  9020. H.DoneProcessing();
  9021. } // TODO: handle other formats
  9022. }
  9023. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  9024. // Str - The format string. NOTE: this is NOT null-terminated!
  9025. StringRef StrRef = FExpr->getString();
  9026. const char *Str = StrRef.data();
  9027. // Account for cases where the string literal is truncated in a declaration.
  9028. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  9029. assert(T && "String literal not of constant array type!");
  9030. size_t TypeSize = T->getSize().getZExtValue();
  9031. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  9032. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  9033. getLangOpts(),
  9034. Context.getTargetInfo());
  9035. }
  9036. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  9037. // Returns the related absolute value function that is larger, of 0 if one
  9038. // does not exist.
  9039. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  9040. switch (AbsFunction) {
  9041. default:
  9042. return 0;
  9043. case Builtin::BI__builtin_abs:
  9044. return Builtin::BI__builtin_labs;
  9045. case Builtin::BI__builtin_labs:
  9046. return Builtin::BI__builtin_llabs;
  9047. case Builtin::BI__builtin_llabs:
  9048. return 0;
  9049. case Builtin::BI__builtin_fabsf:
  9050. return Builtin::BI__builtin_fabs;
  9051. case Builtin::BI__builtin_fabs:
  9052. return Builtin::BI__builtin_fabsl;
  9053. case Builtin::BI__builtin_fabsl:
  9054. return 0;
  9055. case Builtin::BI__builtin_cabsf:
  9056. return Builtin::BI__builtin_cabs;
  9057. case Builtin::BI__builtin_cabs:
  9058. return Builtin::BI__builtin_cabsl;
  9059. case Builtin::BI__builtin_cabsl:
  9060. return 0;
  9061. case Builtin::BIabs:
  9062. return Builtin::BIlabs;
  9063. case Builtin::BIlabs:
  9064. return Builtin::BIllabs;
  9065. case Builtin::BIllabs:
  9066. return 0;
  9067. case Builtin::BIfabsf:
  9068. return Builtin::BIfabs;
  9069. case Builtin::BIfabs:
  9070. return Builtin::BIfabsl;
  9071. case Builtin::BIfabsl:
  9072. return 0;
  9073. case Builtin::BIcabsf:
  9074. return Builtin::BIcabs;
  9075. case Builtin::BIcabs:
  9076. return Builtin::BIcabsl;
  9077. case Builtin::BIcabsl:
  9078. return 0;
  9079. }
  9080. }
  9081. // Returns the argument type of the absolute value function.
  9082. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  9083. unsigned AbsType) {
  9084. if (AbsType == 0)
  9085. return QualType();
  9086. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  9087. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  9088. if (Error != ASTContext::GE_None)
  9089. return QualType();
  9090. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  9091. if (!FT)
  9092. return QualType();
  9093. if (FT->getNumParams() != 1)
  9094. return QualType();
  9095. return FT->getParamType(0);
  9096. }
  9097. // Returns the best absolute value function, or zero, based on type and
  9098. // current absolute value function.
  9099. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  9100. unsigned AbsFunctionKind) {
  9101. unsigned BestKind = 0;
  9102. uint64_t ArgSize = Context.getTypeSize(ArgType);
  9103. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  9104. Kind = getLargerAbsoluteValueFunction(Kind)) {
  9105. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  9106. if (Context.getTypeSize(ParamType) >= ArgSize) {
  9107. if (BestKind == 0)
  9108. BestKind = Kind;
  9109. else if (Context.hasSameType(ParamType, ArgType)) {
  9110. BestKind = Kind;
  9111. break;
  9112. }
  9113. }
  9114. }
  9115. return BestKind;
  9116. }
  9117. enum AbsoluteValueKind {
  9118. AVK_Integer,
  9119. AVK_Floating,
  9120. AVK_Complex
  9121. };
  9122. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  9123. if (T->isIntegralOrEnumerationType())
  9124. return AVK_Integer;
  9125. if (T->isRealFloatingType())
  9126. return AVK_Floating;
  9127. if (T->isAnyComplexType())
  9128. return AVK_Complex;
  9129. llvm_unreachable("Type not integer, floating, or complex");
  9130. }
  9131. // Changes the absolute value function to a different type. Preserves whether
  9132. // the function is a builtin.
  9133. static unsigned changeAbsFunction(unsigned AbsKind,
  9134. AbsoluteValueKind ValueKind) {
  9135. switch (ValueKind) {
  9136. case AVK_Integer:
  9137. switch (AbsKind) {
  9138. default:
  9139. return 0;
  9140. case Builtin::BI__builtin_fabsf:
  9141. case Builtin::BI__builtin_fabs:
  9142. case Builtin::BI__builtin_fabsl:
  9143. case Builtin::BI__builtin_cabsf:
  9144. case Builtin::BI__builtin_cabs:
  9145. case Builtin::BI__builtin_cabsl:
  9146. return Builtin::BI__builtin_abs;
  9147. case Builtin::BIfabsf:
  9148. case Builtin::BIfabs:
  9149. case Builtin::BIfabsl:
  9150. case Builtin::BIcabsf:
  9151. case Builtin::BIcabs:
  9152. case Builtin::BIcabsl:
  9153. return Builtin::BIabs;
  9154. }
  9155. case AVK_Floating:
  9156. switch (AbsKind) {
  9157. default:
  9158. return 0;
  9159. case Builtin::BI__builtin_abs:
  9160. case Builtin::BI__builtin_labs:
  9161. case Builtin::BI__builtin_llabs:
  9162. case Builtin::BI__builtin_cabsf:
  9163. case Builtin::BI__builtin_cabs:
  9164. case Builtin::BI__builtin_cabsl:
  9165. return Builtin::BI__builtin_fabsf;
  9166. case Builtin::BIabs:
  9167. case Builtin::BIlabs:
  9168. case Builtin::BIllabs:
  9169. case Builtin::BIcabsf:
  9170. case Builtin::BIcabs:
  9171. case Builtin::BIcabsl:
  9172. return Builtin::BIfabsf;
  9173. }
  9174. case AVK_Complex:
  9175. switch (AbsKind) {
  9176. default:
  9177. return 0;
  9178. case Builtin::BI__builtin_abs:
  9179. case Builtin::BI__builtin_labs:
  9180. case Builtin::BI__builtin_llabs:
  9181. case Builtin::BI__builtin_fabsf:
  9182. case Builtin::BI__builtin_fabs:
  9183. case Builtin::BI__builtin_fabsl:
  9184. return Builtin::BI__builtin_cabsf;
  9185. case Builtin::BIabs:
  9186. case Builtin::BIlabs:
  9187. case Builtin::BIllabs:
  9188. case Builtin::BIfabsf:
  9189. case Builtin::BIfabs:
  9190. case Builtin::BIfabsl:
  9191. return Builtin::BIcabsf;
  9192. }
  9193. }
  9194. llvm_unreachable("Unable to convert function");
  9195. }
  9196. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  9197. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  9198. if (!FnInfo)
  9199. return 0;
  9200. switch (FDecl->getBuiltinID()) {
  9201. default:
  9202. return 0;
  9203. case Builtin::BI__builtin_abs:
  9204. case Builtin::BI__builtin_fabs:
  9205. case Builtin::BI__builtin_fabsf:
  9206. case Builtin::BI__builtin_fabsl:
  9207. case Builtin::BI__builtin_labs:
  9208. case Builtin::BI__builtin_llabs:
  9209. case Builtin::BI__builtin_cabs:
  9210. case Builtin::BI__builtin_cabsf:
  9211. case Builtin::BI__builtin_cabsl:
  9212. case Builtin::BIabs:
  9213. case Builtin::BIlabs:
  9214. case Builtin::BIllabs:
  9215. case Builtin::BIfabs:
  9216. case Builtin::BIfabsf:
  9217. case Builtin::BIfabsl:
  9218. case Builtin::BIcabs:
  9219. case Builtin::BIcabsf:
  9220. case Builtin::BIcabsl:
  9221. return FDecl->getBuiltinID();
  9222. }
  9223. llvm_unreachable("Unknown Builtin type");
  9224. }
  9225. // If the replacement is valid, emit a note with replacement function.
  9226. // Additionally, suggest including the proper header if not already included.
  9227. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  9228. unsigned AbsKind, QualType ArgType) {
  9229. bool EmitHeaderHint = true;
  9230. const char *HeaderName = nullptr;
  9231. const char *FunctionName = nullptr;
  9232. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  9233. FunctionName = "std::abs";
  9234. if (ArgType->isIntegralOrEnumerationType()) {
  9235. HeaderName = "cstdlib";
  9236. } else if (ArgType->isRealFloatingType()) {
  9237. HeaderName = "cmath";
  9238. } else {
  9239. llvm_unreachable("Invalid Type");
  9240. }
  9241. // Lookup all std::abs
  9242. if (NamespaceDecl *Std = S.getStdNamespace()) {
  9243. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  9244. R.suppressDiagnostics();
  9245. S.LookupQualifiedName(R, Std);
  9246. for (const auto *I : R) {
  9247. const FunctionDecl *FDecl = nullptr;
  9248. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  9249. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  9250. } else {
  9251. FDecl = dyn_cast<FunctionDecl>(I);
  9252. }
  9253. if (!FDecl)
  9254. continue;
  9255. // Found std::abs(), check that they are the right ones.
  9256. if (FDecl->getNumParams() != 1)
  9257. continue;
  9258. // Check that the parameter type can handle the argument.
  9259. QualType ParamType = FDecl->getParamDecl(0)->getType();
  9260. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  9261. S.Context.getTypeSize(ArgType) <=
  9262. S.Context.getTypeSize(ParamType)) {
  9263. // Found a function, don't need the header hint.
  9264. EmitHeaderHint = false;
  9265. break;
  9266. }
  9267. }
  9268. }
  9269. } else {
  9270. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  9271. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  9272. if (HeaderName) {
  9273. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  9274. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  9275. R.suppressDiagnostics();
  9276. S.LookupName(R, S.getCurScope());
  9277. if (R.isSingleResult()) {
  9278. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  9279. if (FD && FD->getBuiltinID() == AbsKind) {
  9280. EmitHeaderHint = false;
  9281. } else {
  9282. return;
  9283. }
  9284. } else if (!R.empty()) {
  9285. return;
  9286. }
  9287. }
  9288. }
  9289. S.Diag(Loc, diag::note_replace_abs_function)
  9290. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  9291. if (!HeaderName)
  9292. return;
  9293. if (!EmitHeaderHint)
  9294. return;
  9295. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  9296. << FunctionName;
  9297. }
  9298. template <std::size_t StrLen>
  9299. static bool IsStdFunction(const FunctionDecl *FDecl,
  9300. const char (&Str)[StrLen]) {
  9301. if (!FDecl)
  9302. return false;
  9303. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  9304. return false;
  9305. if (!FDecl->isInStdNamespace())
  9306. return false;
  9307. return true;
  9308. }
  9309. // Warn when using the wrong abs() function.
  9310. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  9311. const FunctionDecl *FDecl) {
  9312. if (Call->getNumArgs() != 1)
  9313. return;
  9314. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  9315. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  9316. if (AbsKind == 0 && !IsStdAbs)
  9317. return;
  9318. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  9319. QualType ParamType = Call->getArg(0)->getType();
  9320. // Unsigned types cannot be negative. Suggest removing the absolute value
  9321. // function call.
  9322. if (ArgType->isUnsignedIntegerType()) {
  9323. const char *FunctionName =
  9324. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  9325. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  9326. Diag(Call->getExprLoc(), diag::note_remove_abs)
  9327. << FunctionName
  9328. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  9329. return;
  9330. }
  9331. // Taking the absolute value of a pointer is very suspicious, they probably
  9332. // wanted to index into an array, dereference a pointer, call a function, etc.
  9333. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  9334. unsigned DiagType = 0;
  9335. if (ArgType->isFunctionType())
  9336. DiagType = 1;
  9337. else if (ArgType->isArrayType())
  9338. DiagType = 2;
  9339. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  9340. return;
  9341. }
  9342. // std::abs has overloads which prevent most of the absolute value problems
  9343. // from occurring.
  9344. if (IsStdAbs)
  9345. return;
  9346. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  9347. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  9348. // The argument and parameter are the same kind. Check if they are the right
  9349. // size.
  9350. if (ArgValueKind == ParamValueKind) {
  9351. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  9352. return;
  9353. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  9354. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  9355. << FDecl << ArgType << ParamType;
  9356. if (NewAbsKind == 0)
  9357. return;
  9358. emitReplacement(*this, Call->getExprLoc(),
  9359. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  9360. return;
  9361. }
  9362. // ArgValueKind != ParamValueKind
  9363. // The wrong type of absolute value function was used. Attempt to find the
  9364. // proper one.
  9365. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  9366. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  9367. if (NewAbsKind == 0)
  9368. return;
  9369. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  9370. << FDecl << ParamValueKind << ArgValueKind;
  9371. emitReplacement(*this, Call->getExprLoc(),
  9372. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  9373. }
  9374. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  9375. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  9376. const FunctionDecl *FDecl) {
  9377. if (!Call || !FDecl) return;
  9378. // Ignore template specializations and macros.
  9379. if (inTemplateInstantiation()) return;
  9380. if (Call->getExprLoc().isMacroID()) return;
  9381. // Only care about the one template argument, two function parameter std::max
  9382. if (Call->getNumArgs() != 2) return;
  9383. if (!IsStdFunction(FDecl, "max")) return;
  9384. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  9385. if (!ArgList) return;
  9386. if (ArgList->size() != 1) return;
  9387. // Check that template type argument is unsigned integer.
  9388. const auto& TA = ArgList->get(0);
  9389. if (TA.getKind() != TemplateArgument::Type) return;
  9390. QualType ArgType = TA.getAsType();
  9391. if (!ArgType->isUnsignedIntegerType()) return;
  9392. // See if either argument is a literal zero.
  9393. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  9394. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  9395. if (!MTE) return false;
  9396. const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
  9397. if (!Num) return false;
  9398. if (Num->getValue() != 0) return false;
  9399. return true;
  9400. };
  9401. const Expr *FirstArg = Call->getArg(0);
  9402. const Expr *SecondArg = Call->getArg(1);
  9403. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  9404. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  9405. // Only warn when exactly one argument is zero.
  9406. if (IsFirstArgZero == IsSecondArgZero) return;
  9407. SourceRange FirstRange = FirstArg->getSourceRange();
  9408. SourceRange SecondRange = SecondArg->getSourceRange();
  9409. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  9410. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  9411. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  9412. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  9413. SourceRange RemovalRange;
  9414. if (IsFirstArgZero) {
  9415. RemovalRange = SourceRange(FirstRange.getBegin(),
  9416. SecondRange.getBegin().getLocWithOffset(-1));
  9417. } else {
  9418. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  9419. SecondRange.getEnd());
  9420. }
  9421. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  9422. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  9423. << FixItHint::CreateRemoval(RemovalRange);
  9424. }
  9425. //===--- CHECK: Standard memory functions ---------------------------------===//
  9426. /// Takes the expression passed to the size_t parameter of functions
  9427. /// such as memcmp, strncat, etc and warns if it's a comparison.
  9428. ///
  9429. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  9430. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  9431. IdentifierInfo *FnName,
  9432. SourceLocation FnLoc,
  9433. SourceLocation RParenLoc) {
  9434. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  9435. if (!Size)
  9436. return false;
  9437. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  9438. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  9439. return false;
  9440. SourceRange SizeRange = Size->getSourceRange();
  9441. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  9442. << SizeRange << FnName;
  9443. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  9444. << FnName
  9445. << FixItHint::CreateInsertion(
  9446. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  9447. << FixItHint::CreateRemoval(RParenLoc);
  9448. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  9449. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  9450. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  9451. ")");
  9452. return true;
  9453. }
  9454. /// Determine whether the given type is or contains a dynamic class type
  9455. /// (e.g., whether it has a vtable).
  9456. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  9457. bool &IsContained) {
  9458. // Look through array types while ignoring qualifiers.
  9459. const Type *Ty = T->getBaseElementTypeUnsafe();
  9460. IsContained = false;
  9461. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  9462. RD = RD ? RD->getDefinition() : nullptr;
  9463. if (!RD || RD->isInvalidDecl())
  9464. return nullptr;
  9465. if (RD->isDynamicClass())
  9466. return RD;
  9467. // Check all the fields. If any bases were dynamic, the class is dynamic.
  9468. // It's impossible for a class to transitively contain itself by value, so
  9469. // infinite recursion is impossible.
  9470. for (auto *FD : RD->fields()) {
  9471. bool SubContained;
  9472. if (const CXXRecordDecl *ContainedRD =
  9473. getContainedDynamicClass(FD->getType(), SubContained)) {
  9474. IsContained = true;
  9475. return ContainedRD;
  9476. }
  9477. }
  9478. return nullptr;
  9479. }
  9480. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  9481. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  9482. if (Unary->getKind() == UETT_SizeOf)
  9483. return Unary;
  9484. return nullptr;
  9485. }
  9486. /// If E is a sizeof expression, returns its argument expression,
  9487. /// otherwise returns NULL.
  9488. static const Expr *getSizeOfExprArg(const Expr *E) {
  9489. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  9490. if (!SizeOf->isArgumentType())
  9491. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  9492. return nullptr;
  9493. }
  9494. /// If E is a sizeof expression, returns its argument type.
  9495. static QualType getSizeOfArgType(const Expr *E) {
  9496. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  9497. return SizeOf->getTypeOfArgument();
  9498. return QualType();
  9499. }
  9500. namespace {
  9501. struct SearchNonTrivialToInitializeField
  9502. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  9503. using Super =
  9504. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  9505. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  9506. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  9507. SourceLocation SL) {
  9508. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  9509. asDerived().visitArray(PDIK, AT, SL);
  9510. return;
  9511. }
  9512. Super::visitWithKind(PDIK, FT, SL);
  9513. }
  9514. void visitARCStrong(QualType FT, SourceLocation SL) {
  9515. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  9516. }
  9517. void visitARCWeak(QualType FT, SourceLocation SL) {
  9518. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  9519. }
  9520. void visitStruct(QualType FT, SourceLocation SL) {
  9521. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  9522. visit(FD->getType(), FD->getLocation());
  9523. }
  9524. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  9525. const ArrayType *AT, SourceLocation SL) {
  9526. visit(getContext().getBaseElementType(AT), SL);
  9527. }
  9528. void visitTrivial(QualType FT, SourceLocation SL) {}
  9529. static void diag(QualType RT, const Expr *E, Sema &S) {
  9530. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  9531. }
  9532. ASTContext &getContext() { return S.getASTContext(); }
  9533. const Expr *E;
  9534. Sema &S;
  9535. };
  9536. struct SearchNonTrivialToCopyField
  9537. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  9538. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  9539. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  9540. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  9541. SourceLocation SL) {
  9542. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  9543. asDerived().visitArray(PCK, AT, SL);
  9544. return;
  9545. }
  9546. Super::visitWithKind(PCK, FT, SL);
  9547. }
  9548. void visitARCStrong(QualType FT, SourceLocation SL) {
  9549. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  9550. }
  9551. void visitARCWeak(QualType FT, SourceLocation SL) {
  9552. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  9553. }
  9554. void visitStruct(QualType FT, SourceLocation SL) {
  9555. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  9556. visit(FD->getType(), FD->getLocation());
  9557. }
  9558. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  9559. SourceLocation SL) {
  9560. visit(getContext().getBaseElementType(AT), SL);
  9561. }
  9562. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  9563. SourceLocation SL) {}
  9564. void visitTrivial(QualType FT, SourceLocation SL) {}
  9565. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  9566. static void diag(QualType RT, const Expr *E, Sema &S) {
  9567. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  9568. }
  9569. ASTContext &getContext() { return S.getASTContext(); }
  9570. const Expr *E;
  9571. Sema &S;
  9572. };
  9573. }
  9574. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  9575. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  9576. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  9577. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  9578. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  9579. return false;
  9580. return doesExprLikelyComputeSize(BO->getLHS()) ||
  9581. doesExprLikelyComputeSize(BO->getRHS());
  9582. }
  9583. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  9584. }
  9585. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  9586. ///
  9587. /// \code
  9588. /// #define MACRO 0
  9589. /// foo(MACRO);
  9590. /// foo(0);
  9591. /// \endcode
  9592. ///
  9593. /// This should return true for the first call to foo, but not for the second
  9594. /// (regardless of whether foo is a macro or function).
  9595. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  9596. SourceLocation CallLoc,
  9597. SourceLocation ArgLoc) {
  9598. if (!CallLoc.isMacroID())
  9599. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  9600. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  9601. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  9602. }
  9603. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  9604. /// last two arguments transposed.
  9605. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  9606. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  9607. return;
  9608. const Expr *SizeArg =
  9609. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  9610. auto isLiteralZero = [](const Expr *E) {
  9611. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  9612. };
  9613. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  9614. SourceLocation CallLoc = Call->getRParenLoc();
  9615. SourceManager &SM = S.getSourceManager();
  9616. if (isLiteralZero(SizeArg) &&
  9617. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  9618. SourceLocation DiagLoc = SizeArg->getExprLoc();
  9619. // Some platforms #define bzero to __builtin_memset. See if this is the
  9620. // case, and if so, emit a better diagnostic.
  9621. if (BId == Builtin::BIbzero ||
  9622. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  9623. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  9624. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  9625. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  9626. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  9627. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  9628. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  9629. }
  9630. return;
  9631. }
  9632. // If the second argument to a memset is a sizeof expression and the third
  9633. // isn't, this is also likely an error. This should catch
  9634. // 'memset(buf, sizeof(buf), 0xff)'.
  9635. if (BId == Builtin::BImemset &&
  9636. doesExprLikelyComputeSize(Call->getArg(1)) &&
  9637. !doesExprLikelyComputeSize(Call->getArg(2))) {
  9638. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  9639. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  9640. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  9641. return;
  9642. }
  9643. }
  9644. /// Check for dangerous or invalid arguments to memset().
  9645. ///
  9646. /// This issues warnings on known problematic, dangerous or unspecified
  9647. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  9648. /// function calls.
  9649. ///
  9650. /// \param Call The call expression to diagnose.
  9651. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  9652. unsigned BId,
  9653. IdentifierInfo *FnName) {
  9654. assert(BId != 0);
  9655. // It is possible to have a non-standard definition of memset. Validate
  9656. // we have enough arguments, and if not, abort further checking.
  9657. unsigned ExpectedNumArgs =
  9658. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  9659. if (Call->getNumArgs() < ExpectedNumArgs)
  9660. return;
  9661. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  9662. BId == Builtin::BIstrndup ? 1 : 2);
  9663. unsigned LenArg =
  9664. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  9665. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  9666. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  9667. Call->getBeginLoc(), Call->getRParenLoc()))
  9668. return;
  9669. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  9670. CheckMemaccessSize(*this, BId, Call);
  9671. // We have special checking when the length is a sizeof expression.
  9672. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  9673. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  9674. llvm::FoldingSetNodeID SizeOfArgID;
  9675. // Although widely used, 'bzero' is not a standard function. Be more strict
  9676. // with the argument types before allowing diagnostics and only allow the
  9677. // form bzero(ptr, sizeof(...)).
  9678. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  9679. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  9680. return;
  9681. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  9682. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  9683. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  9684. QualType DestTy = Dest->getType();
  9685. QualType PointeeTy;
  9686. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  9687. PointeeTy = DestPtrTy->getPointeeType();
  9688. // Never warn about void type pointers. This can be used to suppress
  9689. // false positives.
  9690. if (PointeeTy->isVoidType())
  9691. continue;
  9692. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  9693. // actually comparing the expressions for equality. Because computing the
  9694. // expression IDs can be expensive, we only do this if the diagnostic is
  9695. // enabled.
  9696. if (SizeOfArg &&
  9697. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  9698. SizeOfArg->getExprLoc())) {
  9699. // We only compute IDs for expressions if the warning is enabled, and
  9700. // cache the sizeof arg's ID.
  9701. if (SizeOfArgID == llvm::FoldingSetNodeID())
  9702. SizeOfArg->Profile(SizeOfArgID, Context, true);
  9703. llvm::FoldingSetNodeID DestID;
  9704. Dest->Profile(DestID, Context, true);
  9705. if (DestID == SizeOfArgID) {
  9706. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  9707. // over sizeof(src) as well.
  9708. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  9709. StringRef ReadableName = FnName->getName();
  9710. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  9711. if (UnaryOp->getOpcode() == UO_AddrOf)
  9712. ActionIdx = 1; // If its an address-of operator, just remove it.
  9713. if (!PointeeTy->isIncompleteType() &&
  9714. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  9715. ActionIdx = 2; // If the pointee's size is sizeof(char),
  9716. // suggest an explicit length.
  9717. // If the function is defined as a builtin macro, do not show macro
  9718. // expansion.
  9719. SourceLocation SL = SizeOfArg->getExprLoc();
  9720. SourceRange DSR = Dest->getSourceRange();
  9721. SourceRange SSR = SizeOfArg->getSourceRange();
  9722. SourceManager &SM = getSourceManager();
  9723. if (SM.isMacroArgExpansion(SL)) {
  9724. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  9725. SL = SM.getSpellingLoc(SL);
  9726. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  9727. SM.getSpellingLoc(DSR.getEnd()));
  9728. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  9729. SM.getSpellingLoc(SSR.getEnd()));
  9730. }
  9731. DiagRuntimeBehavior(SL, SizeOfArg,
  9732. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  9733. << ReadableName
  9734. << PointeeTy
  9735. << DestTy
  9736. << DSR
  9737. << SSR);
  9738. DiagRuntimeBehavior(SL, SizeOfArg,
  9739. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  9740. << ActionIdx
  9741. << SSR);
  9742. break;
  9743. }
  9744. }
  9745. // Also check for cases where the sizeof argument is the exact same
  9746. // type as the memory argument, and where it points to a user-defined
  9747. // record type.
  9748. if (SizeOfArgTy != QualType()) {
  9749. if (PointeeTy->isRecordType() &&
  9750. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  9751. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  9752. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  9753. << FnName << SizeOfArgTy << ArgIdx
  9754. << PointeeTy << Dest->getSourceRange()
  9755. << LenExpr->getSourceRange());
  9756. break;
  9757. }
  9758. }
  9759. } else if (DestTy->isArrayType()) {
  9760. PointeeTy = DestTy;
  9761. }
  9762. if (PointeeTy == QualType())
  9763. continue;
  9764. // Always complain about dynamic classes.
  9765. bool IsContained;
  9766. if (const CXXRecordDecl *ContainedRD =
  9767. getContainedDynamicClass(PointeeTy, IsContained)) {
  9768. unsigned OperationType = 0;
  9769. const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
  9770. // "overwritten" if we're warning about the destination for any call
  9771. // but memcmp; otherwise a verb appropriate to the call.
  9772. if (ArgIdx != 0 || IsCmp) {
  9773. if (BId == Builtin::BImemcpy)
  9774. OperationType = 1;
  9775. else if(BId == Builtin::BImemmove)
  9776. OperationType = 2;
  9777. else if (IsCmp)
  9778. OperationType = 3;
  9779. }
  9780. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  9781. PDiag(diag::warn_dyn_class_memaccess)
  9782. << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
  9783. << IsContained << ContainedRD << OperationType
  9784. << Call->getCallee()->getSourceRange());
  9785. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  9786. BId != Builtin::BImemset)
  9787. DiagRuntimeBehavior(
  9788. Dest->getExprLoc(), Dest,
  9789. PDiag(diag::warn_arc_object_memaccess)
  9790. << ArgIdx << FnName << PointeeTy
  9791. << Call->getCallee()->getSourceRange());
  9792. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  9793. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  9794. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  9795. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  9796. PDiag(diag::warn_cstruct_memaccess)
  9797. << ArgIdx << FnName << PointeeTy << 0);
  9798. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  9799. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  9800. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  9801. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  9802. PDiag(diag::warn_cstruct_memaccess)
  9803. << ArgIdx << FnName << PointeeTy << 1);
  9804. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  9805. } else {
  9806. continue;
  9807. }
  9808. } else
  9809. continue;
  9810. DiagRuntimeBehavior(
  9811. Dest->getExprLoc(), Dest,
  9812. PDiag(diag::note_bad_memaccess_silence)
  9813. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  9814. break;
  9815. }
  9816. }
  9817. // A little helper routine: ignore addition and subtraction of integer literals.
  9818. // This intentionally does not ignore all integer constant expressions because
  9819. // we don't want to remove sizeof().
  9820. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  9821. Ex = Ex->IgnoreParenCasts();
  9822. while (true) {
  9823. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  9824. if (!BO || !BO->isAdditiveOp())
  9825. break;
  9826. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  9827. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  9828. if (isa<IntegerLiteral>(RHS))
  9829. Ex = LHS;
  9830. else if (isa<IntegerLiteral>(LHS))
  9831. Ex = RHS;
  9832. else
  9833. break;
  9834. }
  9835. return Ex;
  9836. }
  9837. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  9838. ASTContext &Context) {
  9839. // Only handle constant-sized or VLAs, but not flexible members.
  9840. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  9841. // Only issue the FIXIT for arrays of size > 1.
  9842. if (CAT->getSize().getSExtValue() <= 1)
  9843. return false;
  9844. } else if (!Ty->isVariableArrayType()) {
  9845. return false;
  9846. }
  9847. return true;
  9848. }
  9849. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  9850. // be the size of the source, instead of the destination.
  9851. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  9852. IdentifierInfo *FnName) {
  9853. // Don't crash if the user has the wrong number of arguments
  9854. unsigned NumArgs = Call->getNumArgs();
  9855. if ((NumArgs != 3) && (NumArgs != 4))
  9856. return;
  9857. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  9858. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  9859. const Expr *CompareWithSrc = nullptr;
  9860. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  9861. Call->getBeginLoc(), Call->getRParenLoc()))
  9862. return;
  9863. // Look for 'strlcpy(dst, x, sizeof(x))'
  9864. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  9865. CompareWithSrc = Ex;
  9866. else {
  9867. // Look for 'strlcpy(dst, x, strlen(x))'
  9868. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  9869. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  9870. SizeCall->getNumArgs() == 1)
  9871. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  9872. }
  9873. }
  9874. if (!CompareWithSrc)
  9875. return;
  9876. // Determine if the argument to sizeof/strlen is equal to the source
  9877. // argument. In principle there's all kinds of things you could do
  9878. // here, for instance creating an == expression and evaluating it with
  9879. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  9880. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  9881. if (!SrcArgDRE)
  9882. return;
  9883. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  9884. if (!CompareWithSrcDRE ||
  9885. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  9886. return;
  9887. const Expr *OriginalSizeArg = Call->getArg(2);
  9888. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  9889. << OriginalSizeArg->getSourceRange() << FnName;
  9890. // Output a FIXIT hint if the destination is an array (rather than a
  9891. // pointer to an array). This could be enhanced to handle some
  9892. // pointers if we know the actual size, like if DstArg is 'array+2'
  9893. // we could say 'sizeof(array)-2'.
  9894. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  9895. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  9896. return;
  9897. SmallString<128> sizeString;
  9898. llvm::raw_svector_ostream OS(sizeString);
  9899. OS << "sizeof(";
  9900. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  9901. OS << ")";
  9902. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  9903. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  9904. OS.str());
  9905. }
  9906. /// Check if two expressions refer to the same declaration.
  9907. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  9908. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  9909. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  9910. return D1->getDecl() == D2->getDecl();
  9911. return false;
  9912. }
  9913. static const Expr *getStrlenExprArg(const Expr *E) {
  9914. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  9915. const FunctionDecl *FD = CE->getDirectCallee();
  9916. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  9917. return nullptr;
  9918. return CE->getArg(0)->IgnoreParenCasts();
  9919. }
  9920. return nullptr;
  9921. }
  9922. // Warn on anti-patterns as the 'size' argument to strncat.
  9923. // The correct size argument should look like following:
  9924. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  9925. void Sema::CheckStrncatArguments(const CallExpr *CE,
  9926. IdentifierInfo *FnName) {
  9927. // Don't crash if the user has the wrong number of arguments.
  9928. if (CE->getNumArgs() < 3)
  9929. return;
  9930. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  9931. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  9932. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  9933. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  9934. CE->getRParenLoc()))
  9935. return;
  9936. // Identify common expressions, which are wrongly used as the size argument
  9937. // to strncat and may lead to buffer overflows.
  9938. unsigned PatternType = 0;
  9939. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  9940. // - sizeof(dst)
  9941. if (referToTheSameDecl(SizeOfArg, DstArg))
  9942. PatternType = 1;
  9943. // - sizeof(src)
  9944. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  9945. PatternType = 2;
  9946. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  9947. if (BE->getOpcode() == BO_Sub) {
  9948. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  9949. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  9950. // - sizeof(dst) - strlen(dst)
  9951. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  9952. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  9953. PatternType = 1;
  9954. // - sizeof(src) - (anything)
  9955. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  9956. PatternType = 2;
  9957. }
  9958. }
  9959. if (PatternType == 0)
  9960. return;
  9961. // Generate the diagnostic.
  9962. SourceLocation SL = LenArg->getBeginLoc();
  9963. SourceRange SR = LenArg->getSourceRange();
  9964. SourceManager &SM = getSourceManager();
  9965. // If the function is defined as a builtin macro, do not show macro expansion.
  9966. if (SM.isMacroArgExpansion(SL)) {
  9967. SL = SM.getSpellingLoc(SL);
  9968. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  9969. SM.getSpellingLoc(SR.getEnd()));
  9970. }
  9971. // Check if the destination is an array (rather than a pointer to an array).
  9972. QualType DstTy = DstArg->getType();
  9973. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  9974. Context);
  9975. if (!isKnownSizeArray) {
  9976. if (PatternType == 1)
  9977. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  9978. else
  9979. Diag(SL, diag::warn_strncat_src_size) << SR;
  9980. return;
  9981. }
  9982. if (PatternType == 1)
  9983. Diag(SL, diag::warn_strncat_large_size) << SR;
  9984. else
  9985. Diag(SL, diag::warn_strncat_src_size) << SR;
  9986. SmallString<128> sizeString;
  9987. llvm::raw_svector_ostream OS(sizeString);
  9988. OS << "sizeof(";
  9989. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  9990. OS << ") - ";
  9991. OS << "strlen(";
  9992. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  9993. OS << ") - 1";
  9994. Diag(SL, diag::note_strncat_wrong_size)
  9995. << FixItHint::CreateReplacement(SR, OS.str());
  9996. }
  9997. namespace {
  9998. void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
  9999. const UnaryOperator *UnaryExpr, const Decl *D) {
  10000. if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
  10001. S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
  10002. << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
  10003. return;
  10004. }
  10005. }
  10006. void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
  10007. const UnaryOperator *UnaryExpr) {
  10008. if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
  10009. const Decl *D = Lvalue->getDecl();
  10010. if (isa<DeclaratorDecl>(D))
  10011. if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
  10012. return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
  10013. }
  10014. if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
  10015. return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
  10016. Lvalue->getMemberDecl());
  10017. }
  10018. void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
  10019. const UnaryOperator *UnaryExpr) {
  10020. const auto *Lambda = dyn_cast<LambdaExpr>(
  10021. UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
  10022. if (!Lambda)
  10023. return;
  10024. S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
  10025. << CalleeName << 2 /*object: lambda expression*/;
  10026. }
  10027. void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
  10028. const DeclRefExpr *Lvalue) {
  10029. const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
  10030. if (Var == nullptr)
  10031. return;
  10032. S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
  10033. << CalleeName << 0 /*object: */ << Var;
  10034. }
  10035. void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
  10036. const CastExpr *Cast) {
  10037. SmallString<128> SizeString;
  10038. llvm::raw_svector_ostream OS(SizeString);
  10039. clang::CastKind Kind = Cast->getCastKind();
  10040. if (Kind == clang::CK_BitCast &&
  10041. !Cast->getSubExpr()->getType()->isFunctionPointerType())
  10042. return;
  10043. if (Kind == clang::CK_IntegralToPointer &&
  10044. !isa<IntegerLiteral>(
  10045. Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
  10046. return;
  10047. switch (Cast->getCastKind()) {
  10048. case clang::CK_BitCast:
  10049. case clang::CK_IntegralToPointer:
  10050. case clang::CK_FunctionToPointerDecay:
  10051. OS << '\'';
  10052. Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
  10053. OS << '\'';
  10054. break;
  10055. default:
  10056. return;
  10057. }
  10058. S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
  10059. << CalleeName << 0 /*object: */ << OS.str();
  10060. }
  10061. } // namespace
  10062. /// Alerts the user that they are attempting to free a non-malloc'd object.
  10063. void Sema::CheckFreeArguments(const CallExpr *E) {
  10064. const std::string CalleeName =
  10065. dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
  10066. { // Prefer something that doesn't involve a cast to make things simpler.
  10067. const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
  10068. if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
  10069. switch (UnaryExpr->getOpcode()) {
  10070. case UnaryOperator::Opcode::UO_AddrOf:
  10071. return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
  10072. case UnaryOperator::Opcode::UO_Plus:
  10073. return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
  10074. default:
  10075. break;
  10076. }
  10077. if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
  10078. if (Lvalue->getType()->isArrayType())
  10079. return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
  10080. if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
  10081. Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
  10082. << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
  10083. return;
  10084. }
  10085. if (isa<BlockExpr>(Arg)) {
  10086. Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
  10087. << CalleeName << 1 /*object: block*/;
  10088. return;
  10089. }
  10090. }
  10091. // Maybe the cast was important, check after the other cases.
  10092. if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
  10093. return CheckFreeArgumentsCast(*this, CalleeName, Cast);
  10094. }
  10095. void
  10096. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  10097. SourceLocation ReturnLoc,
  10098. bool isObjCMethod,
  10099. const AttrVec *Attrs,
  10100. const FunctionDecl *FD) {
  10101. // Check if the return value is null but should not be.
  10102. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  10103. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  10104. CheckNonNullExpr(*this, RetValExp))
  10105. Diag(ReturnLoc, diag::warn_null_ret)
  10106. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  10107. // C++11 [basic.stc.dynamic.allocation]p4:
  10108. // If an allocation function declared with a non-throwing
  10109. // exception-specification fails to allocate storage, it shall return
  10110. // a null pointer. Any other allocation function that fails to allocate
  10111. // storage shall indicate failure only by throwing an exception [...]
  10112. if (FD) {
  10113. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  10114. if (Op == OO_New || Op == OO_Array_New) {
  10115. const FunctionProtoType *Proto
  10116. = FD->getType()->castAs<FunctionProtoType>();
  10117. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  10118. CheckNonNullExpr(*this, RetValExp))
  10119. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  10120. << FD << getLangOpts().CPlusPlus11;
  10121. }
  10122. }
  10123. // PPC MMA non-pointer types are not allowed as return type. Checking the type
  10124. // here prevent the user from using a PPC MMA type as trailing return type.
  10125. if (Context.getTargetInfo().getTriple().isPPC64())
  10126. CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
  10127. }
  10128. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  10129. /// Check for comparisons of floating point operands using != and ==.
  10130. /// Issue a warning if these are no self-comparisons, as they are not likely
  10131. /// to do what the programmer intended.
  10132. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  10133. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  10134. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  10135. // Special case: check for x == x (which is OK).
  10136. // Do not emit warnings for such cases.
  10137. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  10138. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  10139. if (DRL->getDecl() == DRR->getDecl())
  10140. return;
  10141. // Special case: check for comparisons against literals that can be exactly
  10142. // represented by APFloat. In such cases, do not emit a warning. This
  10143. // is a heuristic: often comparison against such literals are used to
  10144. // detect if a value in a variable has not changed. This clearly can
  10145. // lead to false negatives.
  10146. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  10147. if (FLL->isExact())
  10148. return;
  10149. } else
  10150. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  10151. if (FLR->isExact())
  10152. return;
  10153. // Check for comparisons with builtin types.
  10154. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  10155. if (CL->getBuiltinCallee())
  10156. return;
  10157. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  10158. if (CR->getBuiltinCallee())
  10159. return;
  10160. // Emit the diagnostic.
  10161. Diag(Loc, diag::warn_floatingpoint_eq)
  10162. << LHS->getSourceRange() << RHS->getSourceRange();
  10163. }
  10164. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  10165. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  10166. namespace {
  10167. /// Structure recording the 'active' range of an integer-valued
  10168. /// expression.
  10169. struct IntRange {
  10170. /// The number of bits active in the int. Note that this includes exactly one
  10171. /// sign bit if !NonNegative.
  10172. unsigned Width;
  10173. /// True if the int is known not to have negative values. If so, all leading
  10174. /// bits before Width are known zero, otherwise they are known to be the
  10175. /// same as the MSB within Width.
  10176. bool NonNegative;
  10177. IntRange(unsigned Width, bool NonNegative)
  10178. : Width(Width), NonNegative(NonNegative) {}
  10179. /// Number of bits excluding the sign bit.
  10180. unsigned valueBits() const {
  10181. return NonNegative ? Width : Width - 1;
  10182. }
  10183. /// Returns the range of the bool type.
  10184. static IntRange forBoolType() {
  10185. return IntRange(1, true);
  10186. }
  10187. /// Returns the range of an opaque value of the given integral type.
  10188. static IntRange forValueOfType(ASTContext &C, QualType T) {
  10189. return forValueOfCanonicalType(C,
  10190. T->getCanonicalTypeInternal().getTypePtr());
  10191. }
  10192. /// Returns the range of an opaque value of a canonical integral type.
  10193. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  10194. assert(T->isCanonicalUnqualified());
  10195. if (const VectorType *VT = dyn_cast<VectorType>(T))
  10196. T = VT->getElementType().getTypePtr();
  10197. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  10198. T = CT->getElementType().getTypePtr();
  10199. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  10200. T = AT->getValueType().getTypePtr();
  10201. if (!C.getLangOpts().CPlusPlus) {
  10202. // For enum types in C code, use the underlying datatype.
  10203. if (const EnumType *ET = dyn_cast<EnumType>(T))
  10204. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  10205. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  10206. // For enum types in C++, use the known bit width of the enumerators.
  10207. EnumDecl *Enum = ET->getDecl();
  10208. // In C++11, enums can have a fixed underlying type. Use this type to
  10209. // compute the range.
  10210. if (Enum->isFixed()) {
  10211. return IntRange(C.getIntWidth(QualType(T, 0)),
  10212. !ET->isSignedIntegerOrEnumerationType());
  10213. }
  10214. unsigned NumPositive = Enum->getNumPositiveBits();
  10215. unsigned NumNegative = Enum->getNumNegativeBits();
  10216. if (NumNegative == 0)
  10217. return IntRange(NumPositive, true/*NonNegative*/);
  10218. else
  10219. return IntRange(std::max(NumPositive + 1, NumNegative),
  10220. false/*NonNegative*/);
  10221. }
  10222. if (const auto *EIT = dyn_cast<BitIntType>(T))
  10223. return IntRange(EIT->getNumBits(), EIT->isUnsigned());
  10224. const BuiltinType *BT = cast<BuiltinType>(T);
  10225. assert(BT->isInteger());
  10226. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  10227. }
  10228. /// Returns the "target" range of a canonical integral type, i.e.
  10229. /// the range of values expressible in the type.
  10230. ///
  10231. /// This matches forValueOfCanonicalType except that enums have the
  10232. /// full range of their type, not the range of their enumerators.
  10233. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  10234. assert(T->isCanonicalUnqualified());
  10235. if (const VectorType *VT = dyn_cast<VectorType>(T))
  10236. T = VT->getElementType().getTypePtr();
  10237. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  10238. T = CT->getElementType().getTypePtr();
  10239. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  10240. T = AT->getValueType().getTypePtr();
  10241. if (const EnumType *ET = dyn_cast<EnumType>(T))
  10242. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  10243. if (const auto *EIT = dyn_cast<BitIntType>(T))
  10244. return IntRange(EIT->getNumBits(), EIT->isUnsigned());
  10245. const BuiltinType *BT = cast<BuiltinType>(T);
  10246. assert(BT->isInteger());
  10247. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  10248. }
  10249. /// Returns the supremum of two ranges: i.e. their conservative merge.
  10250. static IntRange join(IntRange L, IntRange R) {
  10251. bool Unsigned = L.NonNegative && R.NonNegative;
  10252. return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
  10253. L.NonNegative && R.NonNegative);
  10254. }
  10255. /// Return the range of a bitwise-AND of the two ranges.
  10256. static IntRange bit_and(IntRange L, IntRange R) {
  10257. unsigned Bits = std::max(L.Width, R.Width);
  10258. bool NonNegative = false;
  10259. if (L.NonNegative) {
  10260. Bits = std::min(Bits, L.Width);
  10261. NonNegative = true;
  10262. }
  10263. if (R.NonNegative) {
  10264. Bits = std::min(Bits, R.Width);
  10265. NonNegative = true;
  10266. }
  10267. return IntRange(Bits, NonNegative);
  10268. }
  10269. /// Return the range of a sum of the two ranges.
  10270. static IntRange sum(IntRange L, IntRange R) {
  10271. bool Unsigned = L.NonNegative && R.NonNegative;
  10272. return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
  10273. Unsigned);
  10274. }
  10275. /// Return the range of a difference of the two ranges.
  10276. static IntRange difference(IntRange L, IntRange R) {
  10277. // We need a 1-bit-wider range if:
  10278. // 1) LHS can be negative: least value can be reduced.
  10279. // 2) RHS can be negative: greatest value can be increased.
  10280. bool CanWiden = !L.NonNegative || !R.NonNegative;
  10281. bool Unsigned = L.NonNegative && R.Width == 0;
  10282. return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
  10283. !Unsigned,
  10284. Unsigned);
  10285. }
  10286. /// Return the range of a product of the two ranges.
  10287. static IntRange product(IntRange L, IntRange R) {
  10288. // If both LHS and RHS can be negative, we can form
  10289. // -2^L * -2^R = 2^(L + R)
  10290. // which requires L + R + 1 value bits to represent.
  10291. bool CanWiden = !L.NonNegative && !R.NonNegative;
  10292. bool Unsigned = L.NonNegative && R.NonNegative;
  10293. return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
  10294. Unsigned);
  10295. }
  10296. /// Return the range of a remainder operation between the two ranges.
  10297. static IntRange rem(IntRange L, IntRange R) {
  10298. // The result of a remainder can't be larger than the result of
  10299. // either side. The sign of the result is the sign of the LHS.
  10300. bool Unsigned = L.NonNegative;
  10301. return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
  10302. Unsigned);
  10303. }
  10304. };
  10305. } // namespace
  10306. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  10307. unsigned MaxWidth) {
  10308. if (value.isSigned() && value.isNegative())
  10309. return IntRange(value.getMinSignedBits(), false);
  10310. if (value.getBitWidth() > MaxWidth)
  10311. value = value.trunc(MaxWidth);
  10312. // isNonNegative() just checks the sign bit without considering
  10313. // signedness.
  10314. return IntRange(value.getActiveBits(), true);
  10315. }
  10316. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  10317. unsigned MaxWidth) {
  10318. if (result.isInt())
  10319. return GetValueRange(C, result.getInt(), MaxWidth);
  10320. if (result.isVector()) {
  10321. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  10322. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  10323. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  10324. R = IntRange::join(R, El);
  10325. }
  10326. return R;
  10327. }
  10328. if (result.isComplexInt()) {
  10329. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  10330. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  10331. return IntRange::join(R, I);
  10332. }
  10333. // This can happen with lossless casts to intptr_t of "based" lvalues.
  10334. // Assume it might use arbitrary bits.
  10335. // FIXME: The only reason we need to pass the type in here is to get
  10336. // the sign right on this one case. It would be nice if APValue
  10337. // preserved this.
  10338. assert(result.isLValue() || result.isAddrLabelDiff());
  10339. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  10340. }
  10341. static QualType GetExprType(const Expr *E) {
  10342. QualType Ty = E->getType();
  10343. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  10344. Ty = AtomicRHS->getValueType();
  10345. return Ty;
  10346. }
  10347. /// Pseudo-evaluate the given integer expression, estimating the
  10348. /// range of values it might take.
  10349. ///
  10350. /// \param MaxWidth The width to which the value will be truncated.
  10351. /// \param Approximate If \c true, return a likely range for the result: in
  10352. /// particular, assume that arithmetic on narrower types doesn't leave
  10353. /// those types. If \c false, return a range including all possible
  10354. /// result values.
  10355. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
  10356. bool InConstantContext, bool Approximate) {
  10357. E = E->IgnoreParens();
  10358. // Try a full evaluation first.
  10359. Expr::EvalResult result;
  10360. if (E->EvaluateAsRValue(result, C, InConstantContext))
  10361. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  10362. // I think we only want to look through implicit casts here; if the
  10363. // user has an explicit widening cast, we should treat the value as
  10364. // being of the new, wider type.
  10365. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  10366. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  10367. return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
  10368. Approximate);
  10369. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  10370. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  10371. CE->getCastKind() == CK_BooleanToSignedIntegral;
  10372. // Assume that non-integer casts can span the full range of the type.
  10373. if (!isIntegerCast)
  10374. return OutputTypeRange;
  10375. IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
  10376. std::min(MaxWidth, OutputTypeRange.Width),
  10377. InConstantContext, Approximate);
  10378. // Bail out if the subexpr's range is as wide as the cast type.
  10379. if (SubRange.Width >= OutputTypeRange.Width)
  10380. return OutputTypeRange;
  10381. // Otherwise, we take the smaller width, and we're non-negative if
  10382. // either the output type or the subexpr is.
  10383. return IntRange(SubRange.Width,
  10384. SubRange.NonNegative || OutputTypeRange.NonNegative);
  10385. }
  10386. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  10387. // If we can fold the condition, just take that operand.
  10388. bool CondResult;
  10389. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  10390. return GetExprRange(C,
  10391. CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
  10392. MaxWidth, InConstantContext, Approximate);
  10393. // Otherwise, conservatively merge.
  10394. // GetExprRange requires an integer expression, but a throw expression
  10395. // results in a void type.
  10396. Expr *E = CO->getTrueExpr();
  10397. IntRange L = E->getType()->isVoidType()
  10398. ? IntRange{0, true}
  10399. : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
  10400. E = CO->getFalseExpr();
  10401. IntRange R = E->getType()->isVoidType()
  10402. ? IntRange{0, true}
  10403. : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
  10404. return IntRange::join(L, R);
  10405. }
  10406. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  10407. IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
  10408. switch (BO->getOpcode()) {
  10409. case BO_Cmp:
  10410. llvm_unreachable("builtin <=> should have class type");
  10411. // Boolean-valued operations are single-bit and positive.
  10412. case BO_LAnd:
  10413. case BO_LOr:
  10414. case BO_LT:
  10415. case BO_GT:
  10416. case BO_LE:
  10417. case BO_GE:
  10418. case BO_EQ:
  10419. case BO_NE:
  10420. return IntRange::forBoolType();
  10421. // The type of the assignments is the type of the LHS, so the RHS
  10422. // is not necessarily the same type.
  10423. case BO_MulAssign:
  10424. case BO_DivAssign:
  10425. case BO_RemAssign:
  10426. case BO_AddAssign:
  10427. case BO_SubAssign:
  10428. case BO_XorAssign:
  10429. case BO_OrAssign:
  10430. // TODO: bitfields?
  10431. return IntRange::forValueOfType(C, GetExprType(E));
  10432. // Simple assignments just pass through the RHS, which will have
  10433. // been coerced to the LHS type.
  10434. case BO_Assign:
  10435. // TODO: bitfields?
  10436. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
  10437. Approximate);
  10438. // Operations with opaque sources are black-listed.
  10439. case BO_PtrMemD:
  10440. case BO_PtrMemI:
  10441. return IntRange::forValueOfType(C, GetExprType(E));
  10442. // Bitwise-and uses the *infinum* of the two source ranges.
  10443. case BO_And:
  10444. case BO_AndAssign:
  10445. Combine = IntRange::bit_and;
  10446. break;
  10447. // Left shift gets black-listed based on a judgement call.
  10448. case BO_Shl:
  10449. // ...except that we want to treat '1 << (blah)' as logically
  10450. // positive. It's an important idiom.
  10451. if (IntegerLiteral *I
  10452. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  10453. if (I->getValue() == 1) {
  10454. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  10455. return IntRange(R.Width, /*NonNegative*/ true);
  10456. }
  10457. }
  10458. LLVM_FALLTHROUGH;
  10459. case BO_ShlAssign:
  10460. return IntRange::forValueOfType(C, GetExprType(E));
  10461. // Right shift by a constant can narrow its left argument.
  10462. case BO_Shr:
  10463. case BO_ShrAssign: {
  10464. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
  10465. Approximate);
  10466. // If the shift amount is a positive constant, drop the width by
  10467. // that much.
  10468. if (Optional<llvm::APSInt> shift =
  10469. BO->getRHS()->getIntegerConstantExpr(C)) {
  10470. if (shift->isNonNegative()) {
  10471. unsigned zext = shift->getZExtValue();
  10472. if (zext >= L.Width)
  10473. L.Width = (L.NonNegative ? 0 : 1);
  10474. else
  10475. L.Width -= zext;
  10476. }
  10477. }
  10478. return L;
  10479. }
  10480. // Comma acts as its right operand.
  10481. case BO_Comma:
  10482. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
  10483. Approximate);
  10484. case BO_Add:
  10485. if (!Approximate)
  10486. Combine = IntRange::sum;
  10487. break;
  10488. case BO_Sub:
  10489. if (BO->getLHS()->getType()->isPointerType())
  10490. return IntRange::forValueOfType(C, GetExprType(E));
  10491. if (!Approximate)
  10492. Combine = IntRange::difference;
  10493. break;
  10494. case BO_Mul:
  10495. if (!Approximate)
  10496. Combine = IntRange::product;
  10497. break;
  10498. // The width of a division result is mostly determined by the size
  10499. // of the LHS.
  10500. case BO_Div: {
  10501. // Don't 'pre-truncate' the operands.
  10502. unsigned opWidth = C.getIntWidth(GetExprType(E));
  10503. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
  10504. Approximate);
  10505. // If the divisor is constant, use that.
  10506. if (Optional<llvm::APSInt> divisor =
  10507. BO->getRHS()->getIntegerConstantExpr(C)) {
  10508. unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
  10509. if (log2 >= L.Width)
  10510. L.Width = (L.NonNegative ? 0 : 1);
  10511. else
  10512. L.Width = std::min(L.Width - log2, MaxWidth);
  10513. return L;
  10514. }
  10515. // Otherwise, just use the LHS's width.
  10516. // FIXME: This is wrong if the LHS could be its minimal value and the RHS
  10517. // could be -1.
  10518. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
  10519. Approximate);
  10520. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  10521. }
  10522. case BO_Rem:
  10523. Combine = IntRange::rem;
  10524. break;
  10525. // The default behavior is okay for these.
  10526. case BO_Xor:
  10527. case BO_Or:
  10528. break;
  10529. }
  10530. // Combine the two ranges, but limit the result to the type in which we
  10531. // performed the computation.
  10532. QualType T = GetExprType(E);
  10533. unsigned opWidth = C.getIntWidth(T);
  10534. IntRange L =
  10535. GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
  10536. IntRange R =
  10537. GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
  10538. IntRange C = Combine(L, R);
  10539. C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
  10540. C.Width = std::min(C.Width, MaxWidth);
  10541. return C;
  10542. }
  10543. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  10544. switch (UO->getOpcode()) {
  10545. // Boolean-valued operations are white-listed.
  10546. case UO_LNot:
  10547. return IntRange::forBoolType();
  10548. // Operations with opaque sources are black-listed.
  10549. case UO_Deref:
  10550. case UO_AddrOf: // should be impossible
  10551. return IntRange::forValueOfType(C, GetExprType(E));
  10552. default:
  10553. return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
  10554. Approximate);
  10555. }
  10556. }
  10557. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  10558. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
  10559. Approximate);
  10560. if (const auto *BitField = E->getSourceBitField())
  10561. return IntRange(BitField->getBitWidthValue(C),
  10562. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  10563. return IntRange::forValueOfType(C, GetExprType(E));
  10564. }
  10565. static IntRange GetExprRange(ASTContext &C, const Expr *E,
  10566. bool InConstantContext, bool Approximate) {
  10567. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
  10568. Approximate);
  10569. }
  10570. /// Checks whether the given value, which currently has the given
  10571. /// source semantics, has the same value when coerced through the
  10572. /// target semantics.
  10573. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  10574. const llvm::fltSemantics &Src,
  10575. const llvm::fltSemantics &Tgt) {
  10576. llvm::APFloat truncated = value;
  10577. bool ignored;
  10578. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  10579. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  10580. return truncated.bitwiseIsEqual(value);
  10581. }
  10582. /// Checks whether the given value, which currently has the given
  10583. /// source semantics, has the same value when coerced through the
  10584. /// target semantics.
  10585. ///
  10586. /// The value might be a vector of floats (or a complex number).
  10587. static bool IsSameFloatAfterCast(const APValue &value,
  10588. const llvm::fltSemantics &Src,
  10589. const llvm::fltSemantics &Tgt) {
  10590. if (value.isFloat())
  10591. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  10592. if (value.isVector()) {
  10593. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  10594. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  10595. return false;
  10596. return true;
  10597. }
  10598. assert(value.isComplexFloat());
  10599. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  10600. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  10601. }
  10602. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
  10603. bool IsListInit = false);
  10604. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  10605. // Suppress cases where we are comparing against an enum constant.
  10606. if (const DeclRefExpr *DR =
  10607. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  10608. if (isa<EnumConstantDecl>(DR->getDecl()))
  10609. return true;
  10610. // Suppress cases where the value is expanded from a macro, unless that macro
  10611. // is how a language represents a boolean literal. This is the case in both C
  10612. // and Objective-C.
  10613. SourceLocation BeginLoc = E->getBeginLoc();
  10614. if (BeginLoc.isMacroID()) {
  10615. StringRef MacroName = Lexer::getImmediateMacroName(
  10616. BeginLoc, S.getSourceManager(), S.getLangOpts());
  10617. return MacroName != "YES" && MacroName != "NO" &&
  10618. MacroName != "true" && MacroName != "false";
  10619. }
  10620. return false;
  10621. }
  10622. static bool isKnownToHaveUnsignedValue(Expr *E) {
  10623. return E->getType()->isIntegerType() &&
  10624. (!E->getType()->isSignedIntegerType() ||
  10625. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  10626. }
  10627. namespace {
  10628. /// The promoted range of values of a type. In general this has the
  10629. /// following structure:
  10630. ///
  10631. /// |-----------| . . . |-----------|
  10632. /// ^ ^ ^ ^
  10633. /// Min HoleMin HoleMax Max
  10634. ///
  10635. /// ... where there is only a hole if a signed type is promoted to unsigned
  10636. /// (in which case Min and Max are the smallest and largest representable
  10637. /// values).
  10638. struct PromotedRange {
  10639. // Min, or HoleMax if there is a hole.
  10640. llvm::APSInt PromotedMin;
  10641. // Max, or HoleMin if there is a hole.
  10642. llvm::APSInt PromotedMax;
  10643. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  10644. if (R.Width == 0)
  10645. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  10646. else if (R.Width >= BitWidth && !Unsigned) {
  10647. // Promotion made the type *narrower*. This happens when promoting
  10648. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  10649. // Treat all values of 'signed int' as being in range for now.
  10650. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  10651. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  10652. } else {
  10653. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  10654. .extOrTrunc(BitWidth);
  10655. PromotedMin.setIsUnsigned(Unsigned);
  10656. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  10657. .extOrTrunc(BitWidth);
  10658. PromotedMax.setIsUnsigned(Unsigned);
  10659. }
  10660. }
  10661. // Determine whether this range is contiguous (has no hole).
  10662. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  10663. // Where a constant value is within the range.
  10664. enum ComparisonResult {
  10665. LT = 0x1,
  10666. LE = 0x2,
  10667. GT = 0x4,
  10668. GE = 0x8,
  10669. EQ = 0x10,
  10670. NE = 0x20,
  10671. InRangeFlag = 0x40,
  10672. Less = LE | LT | NE,
  10673. Min = LE | InRangeFlag,
  10674. InRange = InRangeFlag,
  10675. Max = GE | InRangeFlag,
  10676. Greater = GE | GT | NE,
  10677. OnlyValue = LE | GE | EQ | InRangeFlag,
  10678. InHole = NE
  10679. };
  10680. ComparisonResult compare(const llvm::APSInt &Value) const {
  10681. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  10682. Value.isUnsigned() == PromotedMin.isUnsigned());
  10683. if (!isContiguous()) {
  10684. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  10685. if (Value.isMinValue()) return Min;
  10686. if (Value.isMaxValue()) return Max;
  10687. if (Value >= PromotedMin) return InRange;
  10688. if (Value <= PromotedMax) return InRange;
  10689. return InHole;
  10690. }
  10691. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  10692. case -1: return Less;
  10693. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  10694. case 1:
  10695. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  10696. case -1: return InRange;
  10697. case 0: return Max;
  10698. case 1: return Greater;
  10699. }
  10700. }
  10701. llvm_unreachable("impossible compare result");
  10702. }
  10703. static llvm::Optional<StringRef>
  10704. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  10705. if (Op == BO_Cmp) {
  10706. ComparisonResult LTFlag = LT, GTFlag = GT;
  10707. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  10708. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  10709. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  10710. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  10711. return llvm::None;
  10712. }
  10713. ComparisonResult TrueFlag, FalseFlag;
  10714. if (Op == BO_EQ) {
  10715. TrueFlag = EQ;
  10716. FalseFlag = NE;
  10717. } else if (Op == BO_NE) {
  10718. TrueFlag = NE;
  10719. FalseFlag = EQ;
  10720. } else {
  10721. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  10722. TrueFlag = LT;
  10723. FalseFlag = GE;
  10724. } else {
  10725. TrueFlag = GT;
  10726. FalseFlag = LE;
  10727. }
  10728. if (Op == BO_GE || Op == BO_LE)
  10729. std::swap(TrueFlag, FalseFlag);
  10730. }
  10731. if (R & TrueFlag)
  10732. return StringRef("true");
  10733. if (R & FalseFlag)
  10734. return StringRef("false");
  10735. return llvm::None;
  10736. }
  10737. };
  10738. }
  10739. static bool HasEnumType(Expr *E) {
  10740. // Strip off implicit integral promotions.
  10741. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  10742. if (ICE->getCastKind() != CK_IntegralCast &&
  10743. ICE->getCastKind() != CK_NoOp)
  10744. break;
  10745. E = ICE->getSubExpr();
  10746. }
  10747. return E->getType()->isEnumeralType();
  10748. }
  10749. static int classifyConstantValue(Expr *Constant) {
  10750. // The values of this enumeration are used in the diagnostics
  10751. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  10752. enum ConstantValueKind {
  10753. Miscellaneous = 0,
  10754. LiteralTrue,
  10755. LiteralFalse
  10756. };
  10757. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  10758. return BL->getValue() ? ConstantValueKind::LiteralTrue
  10759. : ConstantValueKind::LiteralFalse;
  10760. return ConstantValueKind::Miscellaneous;
  10761. }
  10762. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  10763. Expr *Constant, Expr *Other,
  10764. const llvm::APSInt &Value,
  10765. bool RhsConstant) {
  10766. if (S.inTemplateInstantiation())
  10767. return false;
  10768. Expr *OriginalOther = Other;
  10769. Constant = Constant->IgnoreParenImpCasts();
  10770. Other = Other->IgnoreParenImpCasts();
  10771. // Suppress warnings on tautological comparisons between values of the same
  10772. // enumeration type. There are only two ways we could warn on this:
  10773. // - If the constant is outside the range of representable values of
  10774. // the enumeration. In such a case, we should warn about the cast
  10775. // to enumeration type, not about the comparison.
  10776. // - If the constant is the maximum / minimum in-range value. For an
  10777. // enumeratin type, such comparisons can be meaningful and useful.
  10778. if (Constant->getType()->isEnumeralType() &&
  10779. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  10780. return false;
  10781. IntRange OtherValueRange = GetExprRange(
  10782. S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
  10783. QualType OtherT = Other->getType();
  10784. if (const auto *AT = OtherT->getAs<AtomicType>())
  10785. OtherT = AT->getValueType();
  10786. IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
  10787. // Special case for ObjC BOOL on targets where its a typedef for a signed char
  10788. // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
  10789. bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
  10790. S.NSAPIObj->isObjCBOOLType(OtherT) &&
  10791. OtherT->isSpecificBuiltinType(BuiltinType::SChar);
  10792. // Whether we're treating Other as being a bool because of the form of
  10793. // expression despite it having another type (typically 'int' in C).
  10794. bool OtherIsBooleanDespiteType =
  10795. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  10796. if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
  10797. OtherTypeRange = OtherValueRange = IntRange::forBoolType();
  10798. // Check if all values in the range of possible values of this expression
  10799. // lead to the same comparison outcome.
  10800. PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
  10801. Value.isUnsigned());
  10802. auto Cmp = OtherPromotedValueRange.compare(Value);
  10803. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  10804. if (!Result)
  10805. return false;
  10806. // Also consider the range determined by the type alone. This allows us to
  10807. // classify the warning under the proper diagnostic group.
  10808. bool TautologicalTypeCompare = false;
  10809. {
  10810. PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
  10811. Value.isUnsigned());
  10812. auto TypeCmp = OtherPromotedTypeRange.compare(Value);
  10813. if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
  10814. RhsConstant)) {
  10815. TautologicalTypeCompare = true;
  10816. Cmp = TypeCmp;
  10817. Result = TypeResult;
  10818. }
  10819. }
  10820. // Don't warn if the non-constant operand actually always evaluates to the
  10821. // same value.
  10822. if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
  10823. return false;
  10824. // Suppress the diagnostic for an in-range comparison if the constant comes
  10825. // from a macro or enumerator. We don't want to diagnose
  10826. //
  10827. // some_long_value <= INT_MAX
  10828. //
  10829. // when sizeof(int) == sizeof(long).
  10830. bool InRange = Cmp & PromotedRange::InRangeFlag;
  10831. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  10832. return false;
  10833. // A comparison of an unsigned bit-field against 0 is really a type problem,
  10834. // even though at the type level the bit-field might promote to 'signed int'.
  10835. if (Other->refersToBitField() && InRange && Value == 0 &&
  10836. Other->getType()->isUnsignedIntegerOrEnumerationType())
  10837. TautologicalTypeCompare = true;
  10838. // If this is a comparison to an enum constant, include that
  10839. // constant in the diagnostic.
  10840. const EnumConstantDecl *ED = nullptr;
  10841. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  10842. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  10843. // Should be enough for uint128 (39 decimal digits)
  10844. SmallString<64> PrettySourceValue;
  10845. llvm::raw_svector_ostream OS(PrettySourceValue);
  10846. if (ED) {
  10847. OS << '\'' << *ED << "' (" << Value << ")";
  10848. } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
  10849. Constant->IgnoreParenImpCasts())) {
  10850. OS << (BL->getValue() ? "YES" : "NO");
  10851. } else {
  10852. OS << Value;
  10853. }
  10854. if (!TautologicalTypeCompare) {
  10855. S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
  10856. << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
  10857. << E->getOpcodeStr() << OS.str() << *Result
  10858. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  10859. return true;
  10860. }
  10861. if (IsObjCSignedCharBool) {
  10862. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  10863. S.PDiag(diag::warn_tautological_compare_objc_bool)
  10864. << OS.str() << *Result);
  10865. return true;
  10866. }
  10867. // FIXME: We use a somewhat different formatting for the in-range cases and
  10868. // cases involving boolean values for historical reasons. We should pick a
  10869. // consistent way of presenting these diagnostics.
  10870. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  10871. S.DiagRuntimeBehavior(
  10872. E->getOperatorLoc(), E,
  10873. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  10874. : diag::warn_tautological_bool_compare)
  10875. << OS.str() << classifyConstantValue(Constant) << OtherT
  10876. << OtherIsBooleanDespiteType << *Result
  10877. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  10878. } else {
  10879. bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
  10880. unsigned Diag =
  10881. (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  10882. ? (HasEnumType(OriginalOther)
  10883. ? diag::warn_unsigned_enum_always_true_comparison
  10884. : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
  10885. : diag::warn_unsigned_always_true_comparison)
  10886. : diag::warn_tautological_constant_compare;
  10887. S.Diag(E->getOperatorLoc(), Diag)
  10888. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  10889. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  10890. }
  10891. return true;
  10892. }
  10893. /// Analyze the operands of the given comparison. Implements the
  10894. /// fallback case from AnalyzeComparison.
  10895. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  10896. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  10897. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  10898. }
  10899. /// Implements -Wsign-compare.
  10900. ///
  10901. /// \param E the binary operator to check for warnings
  10902. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  10903. // The type the comparison is being performed in.
  10904. QualType T = E->getLHS()->getType();
  10905. // Only analyze comparison operators where both sides have been converted to
  10906. // the same type.
  10907. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  10908. return AnalyzeImpConvsInComparison(S, E);
  10909. // Don't analyze value-dependent comparisons directly.
  10910. if (E->isValueDependent())
  10911. return AnalyzeImpConvsInComparison(S, E);
  10912. Expr *LHS = E->getLHS();
  10913. Expr *RHS = E->getRHS();
  10914. if (T->isIntegralType(S.Context)) {
  10915. Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
  10916. Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
  10917. // We don't care about expressions whose result is a constant.
  10918. if (RHSValue && LHSValue)
  10919. return AnalyzeImpConvsInComparison(S, E);
  10920. // We only care about expressions where just one side is literal
  10921. if ((bool)RHSValue ^ (bool)LHSValue) {
  10922. // Is the constant on the RHS or LHS?
  10923. const bool RhsConstant = (bool)RHSValue;
  10924. Expr *Const = RhsConstant ? RHS : LHS;
  10925. Expr *Other = RhsConstant ? LHS : RHS;
  10926. const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
  10927. // Check whether an integer constant comparison results in a value
  10928. // of 'true' or 'false'.
  10929. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  10930. return AnalyzeImpConvsInComparison(S, E);
  10931. }
  10932. }
  10933. if (!T->hasUnsignedIntegerRepresentation()) {
  10934. // We don't do anything special if this isn't an unsigned integral
  10935. // comparison: we're only interested in integral comparisons, and
  10936. // signed comparisons only happen in cases we don't care to warn about.
  10937. return AnalyzeImpConvsInComparison(S, E);
  10938. }
  10939. LHS = LHS->IgnoreParenImpCasts();
  10940. RHS = RHS->IgnoreParenImpCasts();
  10941. if (!S.getLangOpts().CPlusPlus) {
  10942. // Avoid warning about comparison of integers with different signs when
  10943. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  10944. // the type of `E`.
  10945. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  10946. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  10947. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  10948. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  10949. }
  10950. // Check to see if one of the (unmodified) operands is of different
  10951. // signedness.
  10952. Expr *signedOperand, *unsignedOperand;
  10953. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  10954. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  10955. "unsigned comparison between two signed integer expressions?");
  10956. signedOperand = LHS;
  10957. unsignedOperand = RHS;
  10958. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  10959. signedOperand = RHS;
  10960. unsignedOperand = LHS;
  10961. } else {
  10962. return AnalyzeImpConvsInComparison(S, E);
  10963. }
  10964. // Otherwise, calculate the effective range of the signed operand.
  10965. IntRange signedRange = GetExprRange(
  10966. S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
  10967. // Go ahead and analyze implicit conversions in the operands. Note
  10968. // that we skip the implicit conversions on both sides.
  10969. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  10970. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  10971. // If the signed range is non-negative, -Wsign-compare won't fire.
  10972. if (signedRange.NonNegative)
  10973. return;
  10974. // For (in)equality comparisons, if the unsigned operand is a
  10975. // constant which cannot collide with a overflowed signed operand,
  10976. // then reinterpreting the signed operand as unsigned will not
  10977. // change the result of the comparison.
  10978. if (E->isEqualityOp()) {
  10979. unsigned comparisonWidth = S.Context.getIntWidth(T);
  10980. IntRange unsignedRange =
  10981. GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
  10982. /*Approximate*/ true);
  10983. // We should never be unable to prove that the unsigned operand is
  10984. // non-negative.
  10985. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  10986. if (unsignedRange.Width < comparisonWidth)
  10987. return;
  10988. }
  10989. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  10990. S.PDiag(diag::warn_mixed_sign_comparison)
  10991. << LHS->getType() << RHS->getType()
  10992. << LHS->getSourceRange() << RHS->getSourceRange());
  10993. }
  10994. /// Analyzes an attempt to assign the given value to a bitfield.
  10995. ///
  10996. /// Returns true if there was something fishy about the attempt.
  10997. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  10998. SourceLocation InitLoc) {
  10999. assert(Bitfield->isBitField());
  11000. if (Bitfield->isInvalidDecl())
  11001. return false;
  11002. // White-list bool bitfields.
  11003. QualType BitfieldType = Bitfield->getType();
  11004. if (BitfieldType->isBooleanType())
  11005. return false;
  11006. if (BitfieldType->isEnumeralType()) {
  11007. EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
  11008. // If the underlying enum type was not explicitly specified as an unsigned
  11009. // type and the enum contain only positive values, MSVC++ will cause an
  11010. // inconsistency by storing this as a signed type.
  11011. if (S.getLangOpts().CPlusPlus11 &&
  11012. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  11013. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  11014. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  11015. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  11016. << BitfieldEnumDecl;
  11017. }
  11018. }
  11019. if (Bitfield->getType()->isBooleanType())
  11020. return false;
  11021. // Ignore value- or type-dependent expressions.
  11022. if (Bitfield->getBitWidth()->isValueDependent() ||
  11023. Bitfield->getBitWidth()->isTypeDependent() ||
  11024. Init->isValueDependent() ||
  11025. Init->isTypeDependent())
  11026. return false;
  11027. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  11028. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  11029. Expr::EvalResult Result;
  11030. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  11031. Expr::SE_AllowSideEffects)) {
  11032. // The RHS is not constant. If the RHS has an enum type, make sure the
  11033. // bitfield is wide enough to hold all the values of the enum without
  11034. // truncation.
  11035. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  11036. EnumDecl *ED = EnumTy->getDecl();
  11037. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  11038. // Enum types are implicitly signed on Windows, so check if there are any
  11039. // negative enumerators to see if the enum was intended to be signed or
  11040. // not.
  11041. bool SignedEnum = ED->getNumNegativeBits() > 0;
  11042. // Check for surprising sign changes when assigning enum values to a
  11043. // bitfield of different signedness. If the bitfield is signed and we
  11044. // have exactly the right number of bits to store this unsigned enum,
  11045. // suggest changing the enum to an unsigned type. This typically happens
  11046. // on Windows where unfixed enums always use an underlying type of 'int'.
  11047. unsigned DiagID = 0;
  11048. if (SignedEnum && !SignedBitfield) {
  11049. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  11050. } else if (SignedBitfield && !SignedEnum &&
  11051. ED->getNumPositiveBits() == FieldWidth) {
  11052. DiagID = diag::warn_signed_bitfield_enum_conversion;
  11053. }
  11054. if (DiagID) {
  11055. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  11056. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  11057. SourceRange TypeRange =
  11058. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  11059. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  11060. << SignedEnum << TypeRange;
  11061. }
  11062. // Compute the required bitwidth. If the enum has negative values, we need
  11063. // one more bit than the normal number of positive bits to represent the
  11064. // sign bit.
  11065. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  11066. ED->getNumNegativeBits())
  11067. : ED->getNumPositiveBits();
  11068. // Check the bitwidth.
  11069. if (BitsNeeded > FieldWidth) {
  11070. Expr *WidthExpr = Bitfield->getBitWidth();
  11071. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  11072. << Bitfield << ED;
  11073. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  11074. << BitsNeeded << ED << WidthExpr->getSourceRange();
  11075. }
  11076. }
  11077. return false;
  11078. }
  11079. llvm::APSInt Value = Result.Val.getInt();
  11080. unsigned OriginalWidth = Value.getBitWidth();
  11081. if (!Value.isSigned() || Value.isNegative())
  11082. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  11083. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  11084. OriginalWidth = Value.getMinSignedBits();
  11085. if (OriginalWidth <= FieldWidth)
  11086. return false;
  11087. // Compute the value which the bitfield will contain.
  11088. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  11089. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  11090. // Check whether the stored value is equal to the original value.
  11091. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  11092. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  11093. return false;
  11094. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  11095. // therefore don't strictly fit into a signed bitfield of width 1.
  11096. if (FieldWidth == 1 && Value == 1)
  11097. return false;
  11098. std::string PrettyValue = toString(Value, 10);
  11099. std::string PrettyTrunc = toString(TruncatedValue, 10);
  11100. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  11101. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  11102. << Init->getSourceRange();
  11103. return true;
  11104. }
  11105. /// Analyze the given simple or compound assignment for warning-worthy
  11106. /// operations.
  11107. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  11108. // Just recurse on the LHS.
  11109. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  11110. // We want to recurse on the RHS as normal unless we're assigning to
  11111. // a bitfield.
  11112. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  11113. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  11114. E->getOperatorLoc())) {
  11115. // Recurse, ignoring any implicit conversions on the RHS.
  11116. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  11117. E->getOperatorLoc());
  11118. }
  11119. }
  11120. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  11121. // Diagnose implicitly sequentially-consistent atomic assignment.
  11122. if (E->getLHS()->getType()->isAtomicType())
  11123. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  11124. }
  11125. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  11126. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  11127. SourceLocation CContext, unsigned diag,
  11128. bool pruneControlFlow = false) {
  11129. if (pruneControlFlow) {
  11130. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  11131. S.PDiag(diag)
  11132. << SourceType << T << E->getSourceRange()
  11133. << SourceRange(CContext));
  11134. return;
  11135. }
  11136. S.Diag(E->getExprLoc(), diag)
  11137. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  11138. }
  11139. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  11140. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  11141. SourceLocation CContext,
  11142. unsigned diag, bool pruneControlFlow = false) {
  11143. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  11144. }
  11145. static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
  11146. return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
  11147. S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
  11148. }
  11149. static void adornObjCBoolConversionDiagWithTernaryFixit(
  11150. Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
  11151. Expr *Ignored = SourceExpr->IgnoreImplicit();
  11152. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
  11153. Ignored = OVE->getSourceExpr();
  11154. bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
  11155. isa<BinaryOperator>(Ignored) ||
  11156. isa<CXXOperatorCallExpr>(Ignored);
  11157. SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
  11158. if (NeedsParens)
  11159. Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
  11160. << FixItHint::CreateInsertion(EndLoc, ")");
  11161. Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
  11162. }
  11163. /// Diagnose an implicit cast from a floating point value to an integer value.
  11164. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  11165. SourceLocation CContext) {
  11166. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  11167. const bool PruneWarnings = S.inTemplateInstantiation();
  11168. Expr *InnerE = E->IgnoreParenImpCasts();
  11169. // We also want to warn on, e.g., "int i = -1.234"
  11170. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  11171. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  11172. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  11173. const bool IsLiteral =
  11174. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  11175. llvm::APFloat Value(0.0);
  11176. bool IsConstant =
  11177. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  11178. if (!IsConstant) {
  11179. if (isObjCSignedCharBool(S, T)) {
  11180. return adornObjCBoolConversionDiagWithTernaryFixit(
  11181. S, E,
  11182. S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
  11183. << E->getType());
  11184. }
  11185. return DiagnoseImpCast(S, E, T, CContext,
  11186. diag::warn_impcast_float_integer, PruneWarnings);
  11187. }
  11188. bool isExact = false;
  11189. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  11190. T->hasUnsignedIntegerRepresentation());
  11191. llvm::APFloat::opStatus Result = Value.convertToInteger(
  11192. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  11193. // FIXME: Force the precision of the source value down so we don't print
  11194. // digits which are usually useless (we don't really care here if we
  11195. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  11196. // would automatically print the shortest representation, but it's a bit
  11197. // tricky to implement.
  11198. SmallString<16> PrettySourceValue;
  11199. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  11200. precision = (precision * 59 + 195) / 196;
  11201. Value.toString(PrettySourceValue, precision);
  11202. if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
  11203. return adornObjCBoolConversionDiagWithTernaryFixit(
  11204. S, E,
  11205. S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
  11206. << PrettySourceValue);
  11207. }
  11208. if (Result == llvm::APFloat::opOK && isExact) {
  11209. if (IsLiteral) return;
  11210. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  11211. PruneWarnings);
  11212. }
  11213. // Conversion of a floating-point value to a non-bool integer where the
  11214. // integral part cannot be represented by the integer type is undefined.
  11215. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  11216. return DiagnoseImpCast(
  11217. S, E, T, CContext,
  11218. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  11219. : diag::warn_impcast_float_to_integer_out_of_range,
  11220. PruneWarnings);
  11221. unsigned DiagID = 0;
  11222. if (IsLiteral) {
  11223. // Warn on floating point literal to integer.
  11224. DiagID = diag::warn_impcast_literal_float_to_integer;
  11225. } else if (IntegerValue == 0) {
  11226. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  11227. return DiagnoseImpCast(S, E, T, CContext,
  11228. diag::warn_impcast_float_integer, PruneWarnings);
  11229. }
  11230. // Warn on non-zero to zero conversion.
  11231. DiagID = diag::warn_impcast_float_to_integer_zero;
  11232. } else {
  11233. if (IntegerValue.isUnsigned()) {
  11234. if (!IntegerValue.isMaxValue()) {
  11235. return DiagnoseImpCast(S, E, T, CContext,
  11236. diag::warn_impcast_float_integer, PruneWarnings);
  11237. }
  11238. } else { // IntegerValue.isSigned()
  11239. if (!IntegerValue.isMaxSignedValue() &&
  11240. !IntegerValue.isMinSignedValue()) {
  11241. return DiagnoseImpCast(S, E, T, CContext,
  11242. diag::warn_impcast_float_integer, PruneWarnings);
  11243. }
  11244. }
  11245. // Warn on evaluatable floating point expression to integer conversion.
  11246. DiagID = diag::warn_impcast_float_to_integer;
  11247. }
  11248. SmallString<16> PrettyTargetValue;
  11249. if (IsBool)
  11250. PrettyTargetValue = Value.isZero() ? "false" : "true";
  11251. else
  11252. IntegerValue.toString(PrettyTargetValue);
  11253. if (PruneWarnings) {
  11254. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  11255. S.PDiag(DiagID)
  11256. << E->getType() << T.getUnqualifiedType()
  11257. << PrettySourceValue << PrettyTargetValue
  11258. << E->getSourceRange() << SourceRange(CContext));
  11259. } else {
  11260. S.Diag(E->getExprLoc(), DiagID)
  11261. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  11262. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  11263. }
  11264. }
  11265. /// Analyze the given compound assignment for the possible losing of
  11266. /// floating-point precision.
  11267. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  11268. assert(isa<CompoundAssignOperator>(E) &&
  11269. "Must be compound assignment operation");
  11270. // Recurse on the LHS and RHS in here
  11271. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  11272. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  11273. if (E->getLHS()->getType()->isAtomicType())
  11274. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  11275. // Now check the outermost expression
  11276. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  11277. const auto *RBT = cast<CompoundAssignOperator>(E)
  11278. ->getComputationResultType()
  11279. ->getAs<BuiltinType>();
  11280. // The below checks assume source is floating point.
  11281. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  11282. // If source is floating point but target is an integer.
  11283. if (ResultBT->isInteger())
  11284. return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
  11285. E->getExprLoc(), diag::warn_impcast_float_integer);
  11286. if (!ResultBT->isFloatingPoint())
  11287. return;
  11288. // If both source and target are floating points, warn about losing precision.
  11289. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  11290. QualType(ResultBT, 0), QualType(RBT, 0));
  11291. if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  11292. // warn about dropping FP rank.
  11293. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  11294. diag::warn_impcast_float_result_precision);
  11295. }
  11296. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  11297. IntRange Range) {
  11298. if (!Range.Width) return "0";
  11299. llvm::APSInt ValueInRange = Value;
  11300. ValueInRange.setIsSigned(!Range.NonNegative);
  11301. ValueInRange = ValueInRange.trunc(Range.Width);
  11302. return toString(ValueInRange, 10);
  11303. }
  11304. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  11305. if (!isa<ImplicitCastExpr>(Ex))
  11306. return false;
  11307. Expr *InnerE = Ex->IgnoreParenImpCasts();
  11308. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  11309. const Type *Source =
  11310. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  11311. if (Target->isDependentType())
  11312. return false;
  11313. const BuiltinType *FloatCandidateBT =
  11314. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  11315. const Type *BoolCandidateType = ToBool ? Target : Source;
  11316. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  11317. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  11318. }
  11319. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  11320. SourceLocation CC) {
  11321. unsigned NumArgs = TheCall->getNumArgs();
  11322. for (unsigned i = 0; i < NumArgs; ++i) {
  11323. Expr *CurrA = TheCall->getArg(i);
  11324. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  11325. continue;
  11326. bool IsSwapped = ((i > 0) &&
  11327. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  11328. IsSwapped |= ((i < (NumArgs - 1)) &&
  11329. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  11330. if (IsSwapped) {
  11331. // Warn on this floating-point to bool conversion.
  11332. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  11333. CurrA->getType(), CC,
  11334. diag::warn_impcast_floating_point_to_bool);
  11335. }
  11336. }
  11337. }
  11338. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  11339. SourceLocation CC) {
  11340. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  11341. E->getExprLoc()))
  11342. return;
  11343. // Don't warn on functions which have return type nullptr_t.
  11344. if (isa<CallExpr>(E))
  11345. return;
  11346. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  11347. const Expr::NullPointerConstantKind NullKind =
  11348. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  11349. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  11350. return;
  11351. // Return if target type is a safe conversion.
  11352. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  11353. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  11354. return;
  11355. SourceLocation Loc = E->getSourceRange().getBegin();
  11356. // Venture through the macro stacks to get to the source of macro arguments.
  11357. // The new location is a better location than the complete location that was
  11358. // passed in.
  11359. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  11360. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  11361. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  11362. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  11363. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  11364. Loc, S.SourceMgr, S.getLangOpts());
  11365. if (MacroName == "NULL")
  11366. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  11367. }
  11368. // Only warn if the null and context location are in the same macro expansion.
  11369. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  11370. return;
  11371. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  11372. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  11373. << FixItHint::CreateReplacement(Loc,
  11374. S.getFixItZeroLiteralForType(T, Loc));
  11375. }
  11376. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  11377. ObjCArrayLiteral *ArrayLiteral);
  11378. static void
  11379. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  11380. ObjCDictionaryLiteral *DictionaryLiteral);
  11381. /// Check a single element within a collection literal against the
  11382. /// target element type.
  11383. static void checkObjCCollectionLiteralElement(Sema &S,
  11384. QualType TargetElementType,
  11385. Expr *Element,
  11386. unsigned ElementKind) {
  11387. // Skip a bitcast to 'id' or qualified 'id'.
  11388. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  11389. if (ICE->getCastKind() == CK_BitCast &&
  11390. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  11391. Element = ICE->getSubExpr();
  11392. }
  11393. QualType ElementType = Element->getType();
  11394. ExprResult ElementResult(Element);
  11395. if (ElementType->getAs<ObjCObjectPointerType>() &&
  11396. S.CheckSingleAssignmentConstraints(TargetElementType,
  11397. ElementResult,
  11398. false, false)
  11399. != Sema::Compatible) {
  11400. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  11401. << ElementType << ElementKind << TargetElementType
  11402. << Element->getSourceRange();
  11403. }
  11404. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  11405. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  11406. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  11407. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  11408. }
  11409. /// Check an Objective-C array literal being converted to the given
  11410. /// target type.
  11411. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  11412. ObjCArrayLiteral *ArrayLiteral) {
  11413. if (!S.NSArrayDecl)
  11414. return;
  11415. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  11416. if (!TargetObjCPtr)
  11417. return;
  11418. if (TargetObjCPtr->isUnspecialized() ||
  11419. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  11420. != S.NSArrayDecl->getCanonicalDecl())
  11421. return;
  11422. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  11423. if (TypeArgs.size() != 1)
  11424. return;
  11425. QualType TargetElementType = TypeArgs[0];
  11426. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  11427. checkObjCCollectionLiteralElement(S, TargetElementType,
  11428. ArrayLiteral->getElement(I),
  11429. 0);
  11430. }
  11431. }
  11432. /// Check an Objective-C dictionary literal being converted to the given
  11433. /// target type.
  11434. static void
  11435. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  11436. ObjCDictionaryLiteral *DictionaryLiteral) {
  11437. if (!S.NSDictionaryDecl)
  11438. return;
  11439. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  11440. if (!TargetObjCPtr)
  11441. return;
  11442. if (TargetObjCPtr->isUnspecialized() ||
  11443. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  11444. != S.NSDictionaryDecl->getCanonicalDecl())
  11445. return;
  11446. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  11447. if (TypeArgs.size() != 2)
  11448. return;
  11449. QualType TargetKeyType = TypeArgs[0];
  11450. QualType TargetObjectType = TypeArgs[1];
  11451. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  11452. auto Element = DictionaryLiteral->getKeyValueElement(I);
  11453. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  11454. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  11455. }
  11456. }
  11457. // Helper function to filter out cases for constant width constant conversion.
  11458. // Don't warn on char array initialization or for non-decimal values.
  11459. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  11460. SourceLocation CC) {
  11461. // If initializing from a constant, and the constant starts with '0',
  11462. // then it is a binary, octal, or hexadecimal. Allow these constants
  11463. // to fill all the bits, even if there is a sign change.
  11464. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  11465. const char FirstLiteralCharacter =
  11466. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  11467. if (FirstLiteralCharacter == '0')
  11468. return false;
  11469. }
  11470. // If the CC location points to a '{', and the type is char, then assume
  11471. // assume it is an array initialization.
  11472. if (CC.isValid() && T->isCharType()) {
  11473. const char FirstContextCharacter =
  11474. S.getSourceManager().getCharacterData(CC)[0];
  11475. if (FirstContextCharacter == '{')
  11476. return false;
  11477. }
  11478. return true;
  11479. }
  11480. static const IntegerLiteral *getIntegerLiteral(Expr *E) {
  11481. const auto *IL = dyn_cast<IntegerLiteral>(E);
  11482. if (!IL) {
  11483. if (auto *UO = dyn_cast<UnaryOperator>(E)) {
  11484. if (UO->getOpcode() == UO_Minus)
  11485. return dyn_cast<IntegerLiteral>(UO->getSubExpr());
  11486. }
  11487. }
  11488. return IL;
  11489. }
  11490. static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
  11491. E = E->IgnoreParenImpCasts();
  11492. SourceLocation ExprLoc = E->getExprLoc();
  11493. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  11494. BinaryOperator::Opcode Opc = BO->getOpcode();
  11495. Expr::EvalResult Result;
  11496. // Do not diagnose unsigned shifts.
  11497. if (Opc == BO_Shl) {
  11498. const auto *LHS = getIntegerLiteral(BO->getLHS());
  11499. const auto *RHS = getIntegerLiteral(BO->getRHS());
  11500. if (LHS && LHS->getValue() == 0)
  11501. S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
  11502. else if (!E->isValueDependent() && LHS && RHS &&
  11503. RHS->getValue().isNonNegative() &&
  11504. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
  11505. S.Diag(ExprLoc, diag::warn_left_shift_always)
  11506. << (Result.Val.getInt() != 0);
  11507. else if (E->getType()->isSignedIntegerType())
  11508. S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
  11509. }
  11510. }
  11511. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  11512. const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
  11513. const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
  11514. if (!LHS || !RHS)
  11515. return;
  11516. if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
  11517. (RHS->getValue() == 0 || RHS->getValue() == 1))
  11518. // Do not diagnose common idioms.
  11519. return;
  11520. if (LHS->getValue() != 0 && RHS->getValue() != 0)
  11521. S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
  11522. }
  11523. }
  11524. static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  11525. SourceLocation CC,
  11526. bool *ICContext = nullptr,
  11527. bool IsListInit = false) {
  11528. if (E->isTypeDependent() || E->isValueDependent()) return;
  11529. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  11530. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  11531. if (Source == Target) return;
  11532. if (Target->isDependentType()) return;
  11533. // If the conversion context location is invalid don't complain. We also
  11534. // don't want to emit a warning if the issue occurs from the expansion of
  11535. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  11536. // delay this check as long as possible. Once we detect we are in that
  11537. // scenario, we just return.
  11538. if (CC.isInvalid())
  11539. return;
  11540. if (Source->isAtomicType())
  11541. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  11542. // Diagnose implicit casts to bool.
  11543. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  11544. if (isa<StringLiteral>(E))
  11545. // Warn on string literal to bool. Checks for string literals in logical
  11546. // and expressions, for instance, assert(0 && "error here"), are
  11547. // prevented by a check in AnalyzeImplicitConversions().
  11548. return DiagnoseImpCast(S, E, T, CC,
  11549. diag::warn_impcast_string_literal_to_bool);
  11550. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  11551. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  11552. // This covers the literal expressions that evaluate to Objective-C
  11553. // objects.
  11554. return DiagnoseImpCast(S, E, T, CC,
  11555. diag::warn_impcast_objective_c_literal_to_bool);
  11556. }
  11557. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  11558. // Warn on pointer to bool conversion that is always true.
  11559. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  11560. SourceRange(CC));
  11561. }
  11562. }
  11563. // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
  11564. // is a typedef for signed char (macOS), then that constant value has to be 1
  11565. // or 0.
  11566. if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
  11567. Expr::EvalResult Result;
  11568. if (E->EvaluateAsInt(Result, S.getASTContext(),
  11569. Expr::SE_AllowSideEffects)) {
  11570. if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
  11571. adornObjCBoolConversionDiagWithTernaryFixit(
  11572. S, E,
  11573. S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
  11574. << toString(Result.Val.getInt(), 10));
  11575. }
  11576. return;
  11577. }
  11578. }
  11579. // Check implicit casts from Objective-C collection literals to specialized
  11580. // collection types, e.g., NSArray<NSString *> *.
  11581. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  11582. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  11583. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  11584. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  11585. // Strip vector types.
  11586. if (isa<VectorType>(Source)) {
  11587. if (Target->isVLSTBuiltinType() &&
  11588. (S.Context.areCompatibleSveTypes(QualType(Target, 0),
  11589. QualType(Source, 0)) ||
  11590. S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
  11591. QualType(Source, 0))))
  11592. return;
  11593. if (!isa<VectorType>(Target)) {
  11594. if (S.SourceMgr.isInSystemMacro(CC))
  11595. return;
  11596. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  11597. }
  11598. // If the vector cast is cast between two vectors of the same size, it is
  11599. // a bitcast, not a conversion.
  11600. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  11601. return;
  11602. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  11603. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  11604. }
  11605. if (auto VecTy = dyn_cast<VectorType>(Target))
  11606. Target = VecTy->getElementType().getTypePtr();
  11607. // Strip complex types.
  11608. if (isa<ComplexType>(Source)) {
  11609. if (!isa<ComplexType>(Target)) {
  11610. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  11611. return;
  11612. return DiagnoseImpCast(S, E, T, CC,
  11613. S.getLangOpts().CPlusPlus
  11614. ? diag::err_impcast_complex_scalar
  11615. : diag::warn_impcast_complex_scalar);
  11616. }
  11617. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  11618. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  11619. }
  11620. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  11621. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  11622. // If the source is floating point...
  11623. if (SourceBT && SourceBT->isFloatingPoint()) {
  11624. // ...and the target is floating point...
  11625. if (TargetBT && TargetBT->isFloatingPoint()) {
  11626. // ...then warn if we're dropping FP rank.
  11627. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  11628. QualType(SourceBT, 0), QualType(TargetBT, 0));
  11629. if (Order > 0) {
  11630. // Don't warn about float constants that are precisely
  11631. // representable in the target type.
  11632. Expr::EvalResult result;
  11633. if (E->EvaluateAsRValue(result, S.Context)) {
  11634. // Value might be a float, a float vector, or a float complex.
  11635. if (IsSameFloatAfterCast(result.Val,
  11636. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  11637. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  11638. return;
  11639. }
  11640. if (S.SourceMgr.isInSystemMacro(CC))
  11641. return;
  11642. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  11643. }
  11644. // ... or possibly if we're increasing rank, too
  11645. else if (Order < 0) {
  11646. if (S.SourceMgr.isInSystemMacro(CC))
  11647. return;
  11648. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  11649. }
  11650. return;
  11651. }
  11652. // If the target is integral, always warn.
  11653. if (TargetBT && TargetBT->isInteger()) {
  11654. if (S.SourceMgr.isInSystemMacro(CC))
  11655. return;
  11656. DiagnoseFloatingImpCast(S, E, T, CC);
  11657. }
  11658. // Detect the case where a call result is converted from floating-point to
  11659. // to bool, and the final argument to the call is converted from bool, to
  11660. // discover this typo:
  11661. //
  11662. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  11663. //
  11664. // FIXME: This is an incredibly special case; is there some more general
  11665. // way to detect this class of misplaced-parentheses bug?
  11666. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  11667. // Check last argument of function call to see if it is an
  11668. // implicit cast from a type matching the type the result
  11669. // is being cast to.
  11670. CallExpr *CEx = cast<CallExpr>(E);
  11671. if (unsigned NumArgs = CEx->getNumArgs()) {
  11672. Expr *LastA = CEx->getArg(NumArgs - 1);
  11673. Expr *InnerE = LastA->IgnoreParenImpCasts();
  11674. if (isa<ImplicitCastExpr>(LastA) &&
  11675. InnerE->getType()->isBooleanType()) {
  11676. // Warn on this floating-point to bool conversion
  11677. DiagnoseImpCast(S, E, T, CC,
  11678. diag::warn_impcast_floating_point_to_bool);
  11679. }
  11680. }
  11681. }
  11682. return;
  11683. }
  11684. // Valid casts involving fixed point types should be accounted for here.
  11685. if (Source->isFixedPointType()) {
  11686. if (Target->isUnsaturatedFixedPointType()) {
  11687. Expr::EvalResult Result;
  11688. if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
  11689. S.isConstantEvaluated())) {
  11690. llvm::APFixedPoint Value = Result.Val.getFixedPoint();
  11691. llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  11692. llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  11693. if (Value > MaxVal || Value < MinVal) {
  11694. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  11695. S.PDiag(diag::warn_impcast_fixed_point_range)
  11696. << Value.toString() << T
  11697. << E->getSourceRange()
  11698. << clang::SourceRange(CC));
  11699. return;
  11700. }
  11701. }
  11702. } else if (Target->isIntegerType()) {
  11703. Expr::EvalResult Result;
  11704. if (!S.isConstantEvaluated() &&
  11705. E->EvaluateAsFixedPoint(Result, S.Context,
  11706. Expr::SE_AllowSideEffects)) {
  11707. llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
  11708. bool Overflowed;
  11709. llvm::APSInt IntResult = FXResult.convertToInt(
  11710. S.Context.getIntWidth(T),
  11711. Target->isSignedIntegerOrEnumerationType(), &Overflowed);
  11712. if (Overflowed) {
  11713. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  11714. S.PDiag(diag::warn_impcast_fixed_point_range)
  11715. << FXResult.toString() << T
  11716. << E->getSourceRange()
  11717. << clang::SourceRange(CC));
  11718. return;
  11719. }
  11720. }
  11721. }
  11722. } else if (Target->isUnsaturatedFixedPointType()) {
  11723. if (Source->isIntegerType()) {
  11724. Expr::EvalResult Result;
  11725. if (!S.isConstantEvaluated() &&
  11726. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  11727. llvm::APSInt Value = Result.Val.getInt();
  11728. bool Overflowed;
  11729. llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
  11730. Value, S.Context.getFixedPointSemantics(T), &Overflowed);
  11731. if (Overflowed) {
  11732. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  11733. S.PDiag(diag::warn_impcast_fixed_point_range)
  11734. << toString(Value, /*Radix=*/10) << T
  11735. << E->getSourceRange()
  11736. << clang::SourceRange(CC));
  11737. return;
  11738. }
  11739. }
  11740. }
  11741. }
  11742. // If we are casting an integer type to a floating point type without
  11743. // initialization-list syntax, we might lose accuracy if the floating
  11744. // point type has a narrower significand than the integer type.
  11745. if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
  11746. TargetBT->isFloatingType() && !IsListInit) {
  11747. // Determine the number of precision bits in the source integer type.
  11748. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
  11749. /*Approximate*/ true);
  11750. unsigned int SourcePrecision = SourceRange.Width;
  11751. // Determine the number of precision bits in the
  11752. // target floating point type.
  11753. unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
  11754. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  11755. if (SourcePrecision > 0 && TargetPrecision > 0 &&
  11756. SourcePrecision > TargetPrecision) {
  11757. if (Optional<llvm::APSInt> SourceInt =
  11758. E->getIntegerConstantExpr(S.Context)) {
  11759. // If the source integer is a constant, convert it to the target
  11760. // floating point type. Issue a warning if the value changes
  11761. // during the whole conversion.
  11762. llvm::APFloat TargetFloatValue(
  11763. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  11764. llvm::APFloat::opStatus ConversionStatus =
  11765. TargetFloatValue.convertFromAPInt(
  11766. *SourceInt, SourceBT->isSignedInteger(),
  11767. llvm::APFloat::rmNearestTiesToEven);
  11768. if (ConversionStatus != llvm::APFloat::opOK) {
  11769. SmallString<32> PrettySourceValue;
  11770. SourceInt->toString(PrettySourceValue, 10);
  11771. SmallString<32> PrettyTargetValue;
  11772. TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
  11773. S.DiagRuntimeBehavior(
  11774. E->getExprLoc(), E,
  11775. S.PDiag(diag::warn_impcast_integer_float_precision_constant)
  11776. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  11777. << E->getSourceRange() << clang::SourceRange(CC));
  11778. }
  11779. } else {
  11780. // Otherwise, the implicit conversion may lose precision.
  11781. DiagnoseImpCast(S, E, T, CC,
  11782. diag::warn_impcast_integer_float_precision);
  11783. }
  11784. }
  11785. }
  11786. DiagnoseNullConversion(S, E, T, CC);
  11787. S.DiscardMisalignedMemberAddress(Target, E);
  11788. if (Target->isBooleanType())
  11789. DiagnoseIntInBoolContext(S, E);
  11790. if (!Source->isIntegerType() || !Target->isIntegerType())
  11791. return;
  11792. // TODO: remove this early return once the false positives for constant->bool
  11793. // in templates, macros, etc, are reduced or removed.
  11794. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  11795. return;
  11796. if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
  11797. !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
  11798. return adornObjCBoolConversionDiagWithTernaryFixit(
  11799. S, E,
  11800. S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
  11801. << E->getType());
  11802. }
  11803. IntRange SourceTypeRange =
  11804. IntRange::forTargetOfCanonicalType(S.Context, Source);
  11805. IntRange LikelySourceRange =
  11806. GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
  11807. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  11808. if (LikelySourceRange.Width > TargetRange.Width) {
  11809. // If the source is a constant, use a default-on diagnostic.
  11810. // TODO: this should happen for bitfield stores, too.
  11811. Expr::EvalResult Result;
  11812. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
  11813. S.isConstantEvaluated())) {
  11814. llvm::APSInt Value(32);
  11815. Value = Result.Val.getInt();
  11816. if (S.SourceMgr.isInSystemMacro(CC))
  11817. return;
  11818. std::string PrettySourceValue = toString(Value, 10);
  11819. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  11820. S.DiagRuntimeBehavior(
  11821. E->getExprLoc(), E,
  11822. S.PDiag(diag::warn_impcast_integer_precision_constant)
  11823. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  11824. << E->getSourceRange() << SourceRange(CC));
  11825. return;
  11826. }
  11827. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  11828. if (S.SourceMgr.isInSystemMacro(CC))
  11829. return;
  11830. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  11831. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  11832. /* pruneControlFlow */ true);
  11833. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  11834. }
  11835. if (TargetRange.Width > SourceTypeRange.Width) {
  11836. if (auto *UO = dyn_cast<UnaryOperator>(E))
  11837. if (UO->getOpcode() == UO_Minus)
  11838. if (Source->isUnsignedIntegerType()) {
  11839. if (Target->isUnsignedIntegerType())
  11840. return DiagnoseImpCast(S, E, T, CC,
  11841. diag::warn_impcast_high_order_zero_bits);
  11842. if (Target->isSignedIntegerType())
  11843. return DiagnoseImpCast(S, E, T, CC,
  11844. diag::warn_impcast_nonnegative_result);
  11845. }
  11846. }
  11847. if (TargetRange.Width == LikelySourceRange.Width &&
  11848. !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
  11849. Source->isSignedIntegerType()) {
  11850. // Warn when doing a signed to signed conversion, warn if the positive
  11851. // source value is exactly the width of the target type, which will
  11852. // cause a negative value to be stored.
  11853. Expr::EvalResult Result;
  11854. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  11855. !S.SourceMgr.isInSystemMacro(CC)) {
  11856. llvm::APSInt Value = Result.Val.getInt();
  11857. if (isSameWidthConstantConversion(S, E, T, CC)) {
  11858. std::string PrettySourceValue = toString(Value, 10);
  11859. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  11860. S.DiagRuntimeBehavior(
  11861. E->getExprLoc(), E,
  11862. S.PDiag(diag::warn_impcast_integer_precision_constant)
  11863. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  11864. << E->getSourceRange() << SourceRange(CC));
  11865. return;
  11866. }
  11867. }
  11868. // Fall through for non-constants to give a sign conversion warning.
  11869. }
  11870. if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
  11871. (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
  11872. LikelySourceRange.Width == TargetRange.Width)) {
  11873. if (S.SourceMgr.isInSystemMacro(CC))
  11874. return;
  11875. unsigned DiagID = diag::warn_impcast_integer_sign;
  11876. // Traditionally, gcc has warned about this under -Wsign-compare.
  11877. // We also want to warn about it in -Wconversion.
  11878. // So if -Wconversion is off, use a completely identical diagnostic
  11879. // in the sign-compare group.
  11880. // The conditional-checking code will
  11881. if (ICContext) {
  11882. DiagID = diag::warn_impcast_integer_sign_conditional;
  11883. *ICContext = true;
  11884. }
  11885. return DiagnoseImpCast(S, E, T, CC, DiagID);
  11886. }
  11887. // Diagnose conversions between different enumeration types.
  11888. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  11889. // type, to give us better diagnostics.
  11890. QualType SourceType = E->getType();
  11891. if (!S.getLangOpts().CPlusPlus) {
  11892. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  11893. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  11894. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  11895. SourceType = S.Context.getTypeDeclType(Enum);
  11896. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  11897. }
  11898. }
  11899. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  11900. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  11901. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  11902. TargetEnum->getDecl()->hasNameForLinkage() &&
  11903. SourceEnum != TargetEnum) {
  11904. if (S.SourceMgr.isInSystemMacro(CC))
  11905. return;
  11906. return DiagnoseImpCast(S, E, SourceType, T, CC,
  11907. diag::warn_impcast_different_enum_types);
  11908. }
  11909. }
  11910. static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
  11911. SourceLocation CC, QualType T);
  11912. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  11913. SourceLocation CC, bool &ICContext) {
  11914. E = E->IgnoreParenImpCasts();
  11915. if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
  11916. return CheckConditionalOperator(S, CO, CC, T);
  11917. AnalyzeImplicitConversions(S, E, CC);
  11918. if (E->getType() != T)
  11919. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  11920. }
  11921. static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
  11922. SourceLocation CC, QualType T) {
  11923. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  11924. Expr *TrueExpr = E->getTrueExpr();
  11925. if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
  11926. TrueExpr = BCO->getCommon();
  11927. bool Suspicious = false;
  11928. CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
  11929. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  11930. if (T->isBooleanType())
  11931. DiagnoseIntInBoolContext(S, E);
  11932. // If -Wconversion would have warned about either of the candidates
  11933. // for a signedness conversion to the context type...
  11934. if (!Suspicious) return;
  11935. // ...but it's currently ignored...
  11936. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  11937. return;
  11938. // ...then check whether it would have warned about either of the
  11939. // candidates for a signedness conversion to the condition type.
  11940. if (E->getType() == T) return;
  11941. Suspicious = false;
  11942. CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
  11943. E->getType(), CC, &Suspicious);
  11944. if (!Suspicious)
  11945. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  11946. E->getType(), CC, &Suspicious);
  11947. }
  11948. /// Check conversion of given expression to boolean.
  11949. /// Input argument E is a logical expression.
  11950. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  11951. if (S.getLangOpts().Bool)
  11952. return;
  11953. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  11954. return;
  11955. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  11956. }
  11957. namespace {
  11958. struct AnalyzeImplicitConversionsWorkItem {
  11959. Expr *E;
  11960. SourceLocation CC;
  11961. bool IsListInit;
  11962. };
  11963. }
  11964. /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
  11965. /// that should be visited are added to WorkList.
  11966. static void AnalyzeImplicitConversions(
  11967. Sema &S, AnalyzeImplicitConversionsWorkItem Item,
  11968. llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
  11969. Expr *OrigE = Item.E;
  11970. SourceLocation CC = Item.CC;
  11971. QualType T = OrigE->getType();
  11972. Expr *E = OrigE->IgnoreParenImpCasts();
  11973. // Propagate whether we are in a C++ list initialization expression.
  11974. // If so, we do not issue warnings for implicit int-float conversion
  11975. // precision loss, because C++11 narrowing already handles it.
  11976. bool IsListInit = Item.IsListInit ||
  11977. (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
  11978. if (E->isTypeDependent() || E->isValueDependent())
  11979. return;
  11980. Expr *SourceExpr = E;
  11981. // Examine, but don't traverse into the source expression of an
  11982. // OpaqueValueExpr, since it may have multiple parents and we don't want to
  11983. // emit duplicate diagnostics. Its fine to examine the form or attempt to
  11984. // evaluate it in the context of checking the specific conversion to T though.
  11985. if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  11986. if (auto *Src = OVE->getSourceExpr())
  11987. SourceExpr = Src;
  11988. if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
  11989. if (UO->getOpcode() == UO_Not &&
  11990. UO->getSubExpr()->isKnownToHaveBooleanValue())
  11991. S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
  11992. << OrigE->getSourceRange() << T->isBooleanType()
  11993. << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
  11994. if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
  11995. if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
  11996. BO->getLHS()->isKnownToHaveBooleanValue() &&
  11997. BO->getRHS()->isKnownToHaveBooleanValue() &&
  11998. BO->getLHS()->HasSideEffects(S.Context) &&
  11999. BO->getRHS()->HasSideEffects(S.Context)) {
  12000. S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
  12001. << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
  12002. << FixItHint::CreateReplacement(
  12003. BO->getOperatorLoc(),
  12004. (BO->getOpcode() == BO_And ? "&&" : "||"));
  12005. S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
  12006. }
  12007. // For conditional operators, we analyze the arguments as if they
  12008. // were being fed directly into the output.
  12009. if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
  12010. CheckConditionalOperator(S, CO, CC, T);
  12011. return;
  12012. }
  12013. // Check implicit argument conversions for function calls.
  12014. if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
  12015. CheckImplicitArgumentConversions(S, Call, CC);
  12016. // Go ahead and check any implicit conversions we might have skipped.
  12017. // The non-canonical typecheck is just an optimization;
  12018. // CheckImplicitConversion will filter out dead implicit conversions.
  12019. if (SourceExpr->getType() != T)
  12020. CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
  12021. // Now continue drilling into this expression.
  12022. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  12023. // The bound subexpressions in a PseudoObjectExpr are not reachable
  12024. // as transitive children.
  12025. // FIXME: Use a more uniform representation for this.
  12026. for (auto *SE : POE->semantics())
  12027. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  12028. WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
  12029. }
  12030. // Skip past explicit casts.
  12031. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  12032. E = CE->getSubExpr()->IgnoreParenImpCasts();
  12033. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  12034. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  12035. WorkList.push_back({E, CC, IsListInit});
  12036. return;
  12037. }
  12038. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  12039. // Do a somewhat different check with comparison operators.
  12040. if (BO->isComparisonOp())
  12041. return AnalyzeComparison(S, BO);
  12042. // And with simple assignments.
  12043. if (BO->getOpcode() == BO_Assign)
  12044. return AnalyzeAssignment(S, BO);
  12045. // And with compound assignments.
  12046. if (BO->isAssignmentOp())
  12047. return AnalyzeCompoundAssignment(S, BO);
  12048. }
  12049. // These break the otherwise-useful invariant below. Fortunately,
  12050. // we don't really need to recurse into them, because any internal
  12051. // expressions should have been analyzed already when they were
  12052. // built into statements.
  12053. if (isa<StmtExpr>(E)) return;
  12054. // Don't descend into unevaluated contexts.
  12055. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  12056. // Now just recurse over the expression's children.
  12057. CC = E->getExprLoc();
  12058. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  12059. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  12060. for (Stmt *SubStmt : E->children()) {
  12061. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  12062. if (!ChildExpr)
  12063. continue;
  12064. if (IsLogicalAndOperator &&
  12065. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  12066. // Ignore checking string literals that are in logical and operators.
  12067. // This is a common pattern for asserts.
  12068. continue;
  12069. WorkList.push_back({ChildExpr, CC, IsListInit});
  12070. }
  12071. if (BO && BO->isLogicalOp()) {
  12072. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  12073. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  12074. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  12075. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  12076. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  12077. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  12078. }
  12079. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  12080. if (U->getOpcode() == UO_LNot) {
  12081. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  12082. } else if (U->getOpcode() != UO_AddrOf) {
  12083. if (U->getSubExpr()->getType()->isAtomicType())
  12084. S.Diag(U->getSubExpr()->getBeginLoc(),
  12085. diag::warn_atomic_implicit_seq_cst);
  12086. }
  12087. }
  12088. }
  12089. /// AnalyzeImplicitConversions - Find and report any interesting
  12090. /// implicit conversions in the given expression. There are a couple
  12091. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  12092. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
  12093. bool IsListInit/*= false*/) {
  12094. llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
  12095. WorkList.push_back({OrigE, CC, IsListInit});
  12096. while (!WorkList.empty())
  12097. AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
  12098. }
  12099. /// Diagnose integer type and any valid implicit conversion to it.
  12100. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  12101. // Taking into account implicit conversions,
  12102. // allow any integer.
  12103. if (!E->getType()->isIntegerType()) {
  12104. S.Diag(E->getBeginLoc(),
  12105. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  12106. return true;
  12107. }
  12108. // Potentially emit standard warnings for implicit conversions if enabled
  12109. // using -Wconversion.
  12110. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  12111. return false;
  12112. }
  12113. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  12114. // Returns true when emitting a warning about taking the address of a reference.
  12115. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  12116. const PartialDiagnostic &PD) {
  12117. E = E->IgnoreParenImpCasts();
  12118. const FunctionDecl *FD = nullptr;
  12119. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  12120. if (!DRE->getDecl()->getType()->isReferenceType())
  12121. return false;
  12122. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  12123. if (!M->getMemberDecl()->getType()->isReferenceType())
  12124. return false;
  12125. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  12126. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  12127. return false;
  12128. FD = Call->getDirectCallee();
  12129. } else {
  12130. return false;
  12131. }
  12132. SemaRef.Diag(E->getExprLoc(), PD);
  12133. // If possible, point to location of function.
  12134. if (FD) {
  12135. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  12136. }
  12137. return true;
  12138. }
  12139. // Returns true if the SourceLocation is expanded from any macro body.
  12140. // Returns false if the SourceLocation is invalid, is from not in a macro
  12141. // expansion, or is from expanded from a top-level macro argument.
  12142. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  12143. if (Loc.isInvalid())
  12144. return false;
  12145. while (Loc.isMacroID()) {
  12146. if (SM.isMacroBodyExpansion(Loc))
  12147. return true;
  12148. Loc = SM.getImmediateMacroCallerLoc(Loc);
  12149. }
  12150. return false;
  12151. }
  12152. /// Diagnose pointers that are always non-null.
  12153. /// \param E the expression containing the pointer
  12154. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  12155. /// compared to a null pointer
  12156. /// \param IsEqual True when the comparison is equal to a null pointer
  12157. /// \param Range Extra SourceRange to highlight in the diagnostic
  12158. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  12159. Expr::NullPointerConstantKind NullKind,
  12160. bool IsEqual, SourceRange Range) {
  12161. if (!E)
  12162. return;
  12163. // Don't warn inside macros.
  12164. if (E->getExprLoc().isMacroID()) {
  12165. const SourceManager &SM = getSourceManager();
  12166. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  12167. IsInAnyMacroBody(SM, Range.getBegin()))
  12168. return;
  12169. }
  12170. E = E->IgnoreImpCasts();
  12171. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  12172. if (isa<CXXThisExpr>(E)) {
  12173. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  12174. : diag::warn_this_bool_conversion;
  12175. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  12176. return;
  12177. }
  12178. bool IsAddressOf = false;
  12179. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  12180. if (UO->getOpcode() != UO_AddrOf)
  12181. return;
  12182. IsAddressOf = true;
  12183. E = UO->getSubExpr();
  12184. }
  12185. if (IsAddressOf) {
  12186. unsigned DiagID = IsCompare
  12187. ? diag::warn_address_of_reference_null_compare
  12188. : diag::warn_address_of_reference_bool_conversion;
  12189. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  12190. << IsEqual;
  12191. if (CheckForReference(*this, E, PD)) {
  12192. return;
  12193. }
  12194. }
  12195. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  12196. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  12197. std::string Str;
  12198. llvm::raw_string_ostream S(Str);
  12199. E->printPretty(S, nullptr, getPrintingPolicy());
  12200. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  12201. : diag::warn_cast_nonnull_to_bool;
  12202. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  12203. << E->getSourceRange() << Range << IsEqual;
  12204. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  12205. };
  12206. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  12207. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  12208. if (auto *Callee = Call->getDirectCallee()) {
  12209. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  12210. ComplainAboutNonnullParamOrCall(A);
  12211. return;
  12212. }
  12213. }
  12214. }
  12215. // Expect to find a single Decl. Skip anything more complicated.
  12216. ValueDecl *D = nullptr;
  12217. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  12218. D = R->getDecl();
  12219. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  12220. D = M->getMemberDecl();
  12221. }
  12222. // Weak Decls can be null.
  12223. if (!D || D->isWeak())
  12224. return;
  12225. // Check for parameter decl with nonnull attribute
  12226. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  12227. if (getCurFunction() &&
  12228. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  12229. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  12230. ComplainAboutNonnullParamOrCall(A);
  12231. return;
  12232. }
  12233. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  12234. // Skip function template not specialized yet.
  12235. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  12236. return;
  12237. auto ParamIter = llvm::find(FD->parameters(), PV);
  12238. assert(ParamIter != FD->param_end());
  12239. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  12240. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  12241. if (!NonNull->args_size()) {
  12242. ComplainAboutNonnullParamOrCall(NonNull);
  12243. return;
  12244. }
  12245. for (const ParamIdx &ArgNo : NonNull->args()) {
  12246. if (ArgNo.getASTIndex() == ParamNo) {
  12247. ComplainAboutNonnullParamOrCall(NonNull);
  12248. return;
  12249. }
  12250. }
  12251. }
  12252. }
  12253. }
  12254. }
  12255. QualType T = D->getType();
  12256. const bool IsArray = T->isArrayType();
  12257. const bool IsFunction = T->isFunctionType();
  12258. // Address of function is used to silence the function warning.
  12259. if (IsAddressOf && IsFunction) {
  12260. return;
  12261. }
  12262. // Found nothing.
  12263. if (!IsAddressOf && !IsFunction && !IsArray)
  12264. return;
  12265. // Pretty print the expression for the diagnostic.
  12266. std::string Str;
  12267. llvm::raw_string_ostream S(Str);
  12268. E->printPretty(S, nullptr, getPrintingPolicy());
  12269. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  12270. : diag::warn_impcast_pointer_to_bool;
  12271. enum {
  12272. AddressOf,
  12273. FunctionPointer,
  12274. ArrayPointer
  12275. } DiagType;
  12276. if (IsAddressOf)
  12277. DiagType = AddressOf;
  12278. else if (IsFunction)
  12279. DiagType = FunctionPointer;
  12280. else if (IsArray)
  12281. DiagType = ArrayPointer;
  12282. else
  12283. llvm_unreachable("Could not determine diagnostic.");
  12284. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  12285. << Range << IsEqual;
  12286. if (!IsFunction)
  12287. return;
  12288. // Suggest '&' to silence the function warning.
  12289. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  12290. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  12291. // Check to see if '()' fixit should be emitted.
  12292. QualType ReturnType;
  12293. UnresolvedSet<4> NonTemplateOverloads;
  12294. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  12295. if (ReturnType.isNull())
  12296. return;
  12297. if (IsCompare) {
  12298. // There are two cases here. If there is null constant, the only suggest
  12299. // for a pointer return type. If the null is 0, then suggest if the return
  12300. // type is a pointer or an integer type.
  12301. if (!ReturnType->isPointerType()) {
  12302. if (NullKind == Expr::NPCK_ZeroExpression ||
  12303. NullKind == Expr::NPCK_ZeroLiteral) {
  12304. if (!ReturnType->isIntegerType())
  12305. return;
  12306. } else {
  12307. return;
  12308. }
  12309. }
  12310. } else { // !IsCompare
  12311. // For function to bool, only suggest if the function pointer has bool
  12312. // return type.
  12313. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  12314. return;
  12315. }
  12316. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  12317. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  12318. }
  12319. /// Diagnoses "dangerous" implicit conversions within the given
  12320. /// expression (which is a full expression). Implements -Wconversion
  12321. /// and -Wsign-compare.
  12322. ///
  12323. /// \param CC the "context" location of the implicit conversion, i.e.
  12324. /// the most location of the syntactic entity requiring the implicit
  12325. /// conversion
  12326. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  12327. // Don't diagnose in unevaluated contexts.
  12328. if (isUnevaluatedContext())
  12329. return;
  12330. // Don't diagnose for value- or type-dependent expressions.
  12331. if (E->isTypeDependent() || E->isValueDependent())
  12332. return;
  12333. // Check for array bounds violations in cases where the check isn't triggered
  12334. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  12335. // ArraySubscriptExpr is on the RHS of a variable initialization.
  12336. CheckArrayAccess(E);
  12337. // This is not the right CC for (e.g.) a variable initialization.
  12338. AnalyzeImplicitConversions(*this, E, CC);
  12339. }
  12340. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  12341. /// Input argument E is a logical expression.
  12342. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  12343. ::CheckBoolLikeConversion(*this, E, CC);
  12344. }
  12345. /// Diagnose when expression is an integer constant expression and its evaluation
  12346. /// results in integer overflow
  12347. void Sema::CheckForIntOverflow (Expr *E) {
  12348. // Use a work list to deal with nested struct initializers.
  12349. SmallVector<Expr *, 2> Exprs(1, E);
  12350. do {
  12351. Expr *OriginalE = Exprs.pop_back_val();
  12352. Expr *E = OriginalE->IgnoreParenCasts();
  12353. if (isa<BinaryOperator>(E)) {
  12354. E->EvaluateForOverflow(Context);
  12355. continue;
  12356. }
  12357. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  12358. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  12359. else if (isa<ObjCBoxedExpr>(OriginalE))
  12360. E->EvaluateForOverflow(Context);
  12361. else if (auto Call = dyn_cast<CallExpr>(E))
  12362. Exprs.append(Call->arg_begin(), Call->arg_end());
  12363. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  12364. Exprs.append(Message->arg_begin(), Message->arg_end());
  12365. } while (!Exprs.empty());
  12366. }
  12367. namespace {
  12368. /// Visitor for expressions which looks for unsequenced operations on the
  12369. /// same object.
  12370. class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
  12371. using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
  12372. /// A tree of sequenced regions within an expression. Two regions are
  12373. /// unsequenced if one is an ancestor or a descendent of the other. When we
  12374. /// finish processing an expression with sequencing, such as a comma
  12375. /// expression, we fold its tree nodes into its parent, since they are
  12376. /// unsequenced with respect to nodes we will visit later.
  12377. class SequenceTree {
  12378. struct Value {
  12379. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  12380. unsigned Parent : 31;
  12381. unsigned Merged : 1;
  12382. };
  12383. SmallVector<Value, 8> Values;
  12384. public:
  12385. /// A region within an expression which may be sequenced with respect
  12386. /// to some other region.
  12387. class Seq {
  12388. friend class SequenceTree;
  12389. unsigned Index;
  12390. explicit Seq(unsigned N) : Index(N) {}
  12391. public:
  12392. Seq() : Index(0) {}
  12393. };
  12394. SequenceTree() { Values.push_back(Value(0)); }
  12395. Seq root() const { return Seq(0); }
  12396. /// Create a new sequence of operations, which is an unsequenced
  12397. /// subset of \p Parent. This sequence of operations is sequenced with
  12398. /// respect to other children of \p Parent.
  12399. Seq allocate(Seq Parent) {
  12400. Values.push_back(Value(Parent.Index));
  12401. return Seq(Values.size() - 1);
  12402. }
  12403. /// Merge a sequence of operations into its parent.
  12404. void merge(Seq S) {
  12405. Values[S.Index].Merged = true;
  12406. }
  12407. /// Determine whether two operations are unsequenced. This operation
  12408. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  12409. /// should have been merged into its parent as appropriate.
  12410. bool isUnsequenced(Seq Cur, Seq Old) {
  12411. unsigned C = representative(Cur.Index);
  12412. unsigned Target = representative(Old.Index);
  12413. while (C >= Target) {
  12414. if (C == Target)
  12415. return true;
  12416. C = Values[C].Parent;
  12417. }
  12418. return false;
  12419. }
  12420. private:
  12421. /// Pick a representative for a sequence.
  12422. unsigned representative(unsigned K) {
  12423. if (Values[K].Merged)
  12424. // Perform path compression as we go.
  12425. return Values[K].Parent = representative(Values[K].Parent);
  12426. return K;
  12427. }
  12428. };
  12429. /// An object for which we can track unsequenced uses.
  12430. using Object = const NamedDecl *;
  12431. /// Different flavors of object usage which we track. We only track the
  12432. /// least-sequenced usage of each kind.
  12433. enum UsageKind {
  12434. /// A read of an object. Multiple unsequenced reads are OK.
  12435. UK_Use,
  12436. /// A modification of an object which is sequenced before the value
  12437. /// computation of the expression, such as ++n in C++.
  12438. UK_ModAsValue,
  12439. /// A modification of an object which is not sequenced before the value
  12440. /// computation of the expression, such as n++.
  12441. UK_ModAsSideEffect,
  12442. UK_Count = UK_ModAsSideEffect + 1
  12443. };
  12444. /// Bundle together a sequencing region and the expression corresponding
  12445. /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
  12446. struct Usage {
  12447. const Expr *UsageExpr;
  12448. SequenceTree::Seq Seq;
  12449. Usage() : UsageExpr(nullptr) {}
  12450. };
  12451. struct UsageInfo {
  12452. Usage Uses[UK_Count];
  12453. /// Have we issued a diagnostic for this object already?
  12454. bool Diagnosed;
  12455. UsageInfo() : Diagnosed(false) {}
  12456. };
  12457. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  12458. Sema &SemaRef;
  12459. /// Sequenced regions within the expression.
  12460. SequenceTree Tree;
  12461. /// Declaration modifications and references which we have seen.
  12462. UsageInfoMap UsageMap;
  12463. /// The region we are currently within.
  12464. SequenceTree::Seq Region;
  12465. /// Filled in with declarations which were modified as a side-effect
  12466. /// (that is, post-increment operations).
  12467. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  12468. /// Expressions to check later. We defer checking these to reduce
  12469. /// stack usage.
  12470. SmallVectorImpl<const Expr *> &WorkList;
  12471. /// RAII object wrapping the visitation of a sequenced subexpression of an
  12472. /// expression. At the end of this process, the side-effects of the evaluation
  12473. /// become sequenced with respect to the value computation of the result, so
  12474. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  12475. /// UK_ModAsValue.
  12476. struct SequencedSubexpression {
  12477. SequencedSubexpression(SequenceChecker &Self)
  12478. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  12479. Self.ModAsSideEffect = &ModAsSideEffect;
  12480. }
  12481. ~SequencedSubexpression() {
  12482. for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
  12483. // Add a new usage with usage kind UK_ModAsValue, and then restore
  12484. // the previous usage with UK_ModAsSideEffect (thus clearing it if
  12485. // the previous one was empty).
  12486. UsageInfo &UI = Self.UsageMap[M.first];
  12487. auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
  12488. Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
  12489. SideEffectUsage = M.second;
  12490. }
  12491. Self.ModAsSideEffect = OldModAsSideEffect;
  12492. }
  12493. SequenceChecker &Self;
  12494. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  12495. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  12496. };
  12497. /// RAII object wrapping the visitation of a subexpression which we might
  12498. /// choose to evaluate as a constant. If any subexpression is evaluated and
  12499. /// found to be non-constant, this allows us to suppress the evaluation of
  12500. /// the outer expression.
  12501. class EvaluationTracker {
  12502. public:
  12503. EvaluationTracker(SequenceChecker &Self)
  12504. : Self(Self), Prev(Self.EvalTracker) {
  12505. Self.EvalTracker = this;
  12506. }
  12507. ~EvaluationTracker() {
  12508. Self.EvalTracker = Prev;
  12509. if (Prev)
  12510. Prev->EvalOK &= EvalOK;
  12511. }
  12512. bool evaluate(const Expr *E, bool &Result) {
  12513. if (!EvalOK || E->isValueDependent())
  12514. return false;
  12515. EvalOK = E->EvaluateAsBooleanCondition(
  12516. Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
  12517. return EvalOK;
  12518. }
  12519. private:
  12520. SequenceChecker &Self;
  12521. EvaluationTracker *Prev;
  12522. bool EvalOK = true;
  12523. } *EvalTracker = nullptr;
  12524. /// Find the object which is produced by the specified expression,
  12525. /// if any.
  12526. Object getObject(const Expr *E, bool Mod) const {
  12527. E = E->IgnoreParenCasts();
  12528. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  12529. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  12530. return getObject(UO->getSubExpr(), Mod);
  12531. } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  12532. if (BO->getOpcode() == BO_Comma)
  12533. return getObject(BO->getRHS(), Mod);
  12534. if (Mod && BO->isAssignmentOp())
  12535. return getObject(BO->getLHS(), Mod);
  12536. } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  12537. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  12538. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  12539. return ME->getMemberDecl();
  12540. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  12541. // FIXME: If this is a reference, map through to its value.
  12542. return DRE->getDecl();
  12543. return nullptr;
  12544. }
  12545. /// Note that an object \p O was modified or used by an expression
  12546. /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
  12547. /// the object \p O as obtained via the \p UsageMap.
  12548. void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
  12549. // Get the old usage for the given object and usage kind.
  12550. Usage &U = UI.Uses[UK];
  12551. if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
  12552. // If we have a modification as side effect and are in a sequenced
  12553. // subexpression, save the old Usage so that we can restore it later
  12554. // in SequencedSubexpression::~SequencedSubexpression.
  12555. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  12556. ModAsSideEffect->push_back(std::make_pair(O, U));
  12557. // Then record the new usage with the current sequencing region.
  12558. U.UsageExpr = UsageExpr;
  12559. U.Seq = Region;
  12560. }
  12561. }
  12562. /// Check whether a modification or use of an object \p O in an expression
  12563. /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
  12564. /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
  12565. /// \p IsModMod is true when we are checking for a mod-mod unsequenced
  12566. /// usage and false we are checking for a mod-use unsequenced usage.
  12567. void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
  12568. UsageKind OtherKind, bool IsModMod) {
  12569. if (UI.Diagnosed)
  12570. return;
  12571. const Usage &U = UI.Uses[OtherKind];
  12572. if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
  12573. return;
  12574. const Expr *Mod = U.UsageExpr;
  12575. const Expr *ModOrUse = UsageExpr;
  12576. if (OtherKind == UK_Use)
  12577. std::swap(Mod, ModOrUse);
  12578. SemaRef.DiagRuntimeBehavior(
  12579. Mod->getExprLoc(), {Mod, ModOrUse},
  12580. SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
  12581. : diag::warn_unsequenced_mod_use)
  12582. << O << SourceRange(ModOrUse->getExprLoc()));
  12583. UI.Diagnosed = true;
  12584. }
  12585. // A note on note{Pre, Post}{Use, Mod}:
  12586. //
  12587. // (It helps to follow the algorithm with an expression such as
  12588. // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
  12589. // operations before C++17 and both are well-defined in C++17).
  12590. //
  12591. // When visiting a node which uses/modify an object we first call notePreUse
  12592. // or notePreMod before visiting its sub-expression(s). At this point the
  12593. // children of the current node have not yet been visited and so the eventual
  12594. // uses/modifications resulting from the children of the current node have not
  12595. // been recorded yet.
  12596. //
  12597. // We then visit the children of the current node. After that notePostUse or
  12598. // notePostMod is called. These will 1) detect an unsequenced modification
  12599. // as side effect (as in "k++ + k") and 2) add a new usage with the
  12600. // appropriate usage kind.
  12601. //
  12602. // We also have to be careful that some operation sequences modification as
  12603. // side effect as well (for example: || or ,). To account for this we wrap
  12604. // the visitation of such a sub-expression (for example: the LHS of || or ,)
  12605. // with SequencedSubexpression. SequencedSubexpression is an RAII object
  12606. // which record usages which are modifications as side effect, and then
  12607. // downgrade them (or more accurately restore the previous usage which was a
  12608. // modification as side effect) when exiting the scope of the sequenced
  12609. // subexpression.
  12610. void notePreUse(Object O, const Expr *UseExpr) {
  12611. UsageInfo &UI = UsageMap[O];
  12612. // Uses conflict with other modifications.
  12613. checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
  12614. }
  12615. void notePostUse(Object O, const Expr *UseExpr) {
  12616. UsageInfo &UI = UsageMap[O];
  12617. checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
  12618. /*IsModMod=*/false);
  12619. addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
  12620. }
  12621. void notePreMod(Object O, const Expr *ModExpr) {
  12622. UsageInfo &UI = UsageMap[O];
  12623. // Modifications conflict with other modifications and with uses.
  12624. checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
  12625. checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
  12626. }
  12627. void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
  12628. UsageInfo &UI = UsageMap[O];
  12629. checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
  12630. /*IsModMod=*/true);
  12631. addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
  12632. }
  12633. public:
  12634. SequenceChecker(Sema &S, const Expr *E,
  12635. SmallVectorImpl<const Expr *> &WorkList)
  12636. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  12637. Visit(E);
  12638. // Silence a -Wunused-private-field since WorkList is now unused.
  12639. // TODO: Evaluate if it can be used, and if not remove it.
  12640. (void)this->WorkList;
  12641. }
  12642. void VisitStmt(const Stmt *S) {
  12643. // Skip all statements which aren't expressions for now.
  12644. }
  12645. void VisitExpr(const Expr *E) {
  12646. // By default, just recurse to evaluated subexpressions.
  12647. Base::VisitStmt(E);
  12648. }
  12649. void VisitCastExpr(const CastExpr *E) {
  12650. Object O = Object();
  12651. if (E->getCastKind() == CK_LValueToRValue)
  12652. O = getObject(E->getSubExpr(), false);
  12653. if (O)
  12654. notePreUse(O, E);
  12655. VisitExpr(E);
  12656. if (O)
  12657. notePostUse(O, E);
  12658. }
  12659. void VisitSequencedExpressions(const Expr *SequencedBefore,
  12660. const Expr *SequencedAfter) {
  12661. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  12662. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  12663. SequenceTree::Seq OldRegion = Region;
  12664. {
  12665. SequencedSubexpression SeqBefore(*this);
  12666. Region = BeforeRegion;
  12667. Visit(SequencedBefore);
  12668. }
  12669. Region = AfterRegion;
  12670. Visit(SequencedAfter);
  12671. Region = OldRegion;
  12672. Tree.merge(BeforeRegion);
  12673. Tree.merge(AfterRegion);
  12674. }
  12675. void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
  12676. // C++17 [expr.sub]p1:
  12677. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  12678. // expression E1 is sequenced before the expression E2.
  12679. if (SemaRef.getLangOpts().CPlusPlus17)
  12680. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  12681. else {
  12682. Visit(ASE->getLHS());
  12683. Visit(ASE->getRHS());
  12684. }
  12685. }
  12686. void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
  12687. void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
  12688. void VisitBinPtrMem(const BinaryOperator *BO) {
  12689. // C++17 [expr.mptr.oper]p4:
  12690. // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
  12691. // the expression E1 is sequenced before the expression E2.
  12692. if (SemaRef.getLangOpts().CPlusPlus17)
  12693. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  12694. else {
  12695. Visit(BO->getLHS());
  12696. Visit(BO->getRHS());
  12697. }
  12698. }
  12699. void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
  12700. void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
  12701. void VisitBinShlShr(const BinaryOperator *BO) {
  12702. // C++17 [expr.shift]p4:
  12703. // The expression E1 is sequenced before the expression E2.
  12704. if (SemaRef.getLangOpts().CPlusPlus17)
  12705. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  12706. else {
  12707. Visit(BO->getLHS());
  12708. Visit(BO->getRHS());
  12709. }
  12710. }
  12711. void VisitBinComma(const BinaryOperator *BO) {
  12712. // C++11 [expr.comma]p1:
  12713. // Every value computation and side effect associated with the left
  12714. // expression is sequenced before every value computation and side
  12715. // effect associated with the right expression.
  12716. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  12717. }
  12718. void VisitBinAssign(const BinaryOperator *BO) {
  12719. SequenceTree::Seq RHSRegion;
  12720. SequenceTree::Seq LHSRegion;
  12721. if (SemaRef.getLangOpts().CPlusPlus17) {
  12722. RHSRegion = Tree.allocate(Region);
  12723. LHSRegion = Tree.allocate(Region);
  12724. } else {
  12725. RHSRegion = Region;
  12726. LHSRegion = Region;
  12727. }
  12728. SequenceTree::Seq OldRegion = Region;
  12729. // C++11 [expr.ass]p1:
  12730. // [...] the assignment is sequenced after the value computation
  12731. // of the right and left operands, [...]
  12732. //
  12733. // so check it before inspecting the operands and update the
  12734. // map afterwards.
  12735. Object O = getObject(BO->getLHS(), /*Mod=*/true);
  12736. if (O)
  12737. notePreMod(O, BO);
  12738. if (SemaRef.getLangOpts().CPlusPlus17) {
  12739. // C++17 [expr.ass]p1:
  12740. // [...] The right operand is sequenced before the left operand. [...]
  12741. {
  12742. SequencedSubexpression SeqBefore(*this);
  12743. Region = RHSRegion;
  12744. Visit(BO->getRHS());
  12745. }
  12746. Region = LHSRegion;
  12747. Visit(BO->getLHS());
  12748. if (O && isa<CompoundAssignOperator>(BO))
  12749. notePostUse(O, BO);
  12750. } else {
  12751. // C++11 does not specify any sequencing between the LHS and RHS.
  12752. Region = LHSRegion;
  12753. Visit(BO->getLHS());
  12754. if (O && isa<CompoundAssignOperator>(BO))
  12755. notePostUse(O, BO);
  12756. Region = RHSRegion;
  12757. Visit(BO->getRHS());
  12758. }
  12759. // C++11 [expr.ass]p1:
  12760. // the assignment is sequenced [...] before the value computation of the
  12761. // assignment expression.
  12762. // C11 6.5.16/3 has no such rule.
  12763. Region = OldRegion;
  12764. if (O)
  12765. notePostMod(O, BO,
  12766. SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  12767. : UK_ModAsSideEffect);
  12768. if (SemaRef.getLangOpts().CPlusPlus17) {
  12769. Tree.merge(RHSRegion);
  12770. Tree.merge(LHSRegion);
  12771. }
  12772. }
  12773. void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
  12774. VisitBinAssign(CAO);
  12775. }
  12776. void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  12777. void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  12778. void VisitUnaryPreIncDec(const UnaryOperator *UO) {
  12779. Object O = getObject(UO->getSubExpr(), true);
  12780. if (!O)
  12781. return VisitExpr(UO);
  12782. notePreMod(O, UO);
  12783. Visit(UO->getSubExpr());
  12784. // C++11 [expr.pre.incr]p1:
  12785. // the expression ++x is equivalent to x+=1
  12786. notePostMod(O, UO,
  12787. SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  12788. : UK_ModAsSideEffect);
  12789. }
  12790. void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  12791. void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  12792. void VisitUnaryPostIncDec(const UnaryOperator *UO) {
  12793. Object O = getObject(UO->getSubExpr(), true);
  12794. if (!O)
  12795. return VisitExpr(UO);
  12796. notePreMod(O, UO);
  12797. Visit(UO->getSubExpr());
  12798. notePostMod(O, UO, UK_ModAsSideEffect);
  12799. }
  12800. void VisitBinLOr(const BinaryOperator *BO) {
  12801. // C++11 [expr.log.or]p2:
  12802. // If the second expression is evaluated, every value computation and
  12803. // side effect associated with the first expression is sequenced before
  12804. // every value computation and side effect associated with the
  12805. // second expression.
  12806. SequenceTree::Seq LHSRegion = Tree.allocate(Region);
  12807. SequenceTree::Seq RHSRegion = Tree.allocate(Region);
  12808. SequenceTree::Seq OldRegion = Region;
  12809. EvaluationTracker Eval(*this);
  12810. {
  12811. SequencedSubexpression Sequenced(*this);
  12812. Region = LHSRegion;
  12813. Visit(BO->getLHS());
  12814. }
  12815. // C++11 [expr.log.or]p1:
  12816. // [...] the second operand is not evaluated if the first operand
  12817. // evaluates to true.
  12818. bool EvalResult = false;
  12819. bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
  12820. bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
  12821. if (ShouldVisitRHS) {
  12822. Region = RHSRegion;
  12823. Visit(BO->getRHS());
  12824. }
  12825. Region = OldRegion;
  12826. Tree.merge(LHSRegion);
  12827. Tree.merge(RHSRegion);
  12828. }
  12829. void VisitBinLAnd(const BinaryOperator *BO) {
  12830. // C++11 [expr.log.and]p2:
  12831. // If the second expression is evaluated, every value computation and
  12832. // side effect associated with the first expression is sequenced before
  12833. // every value computation and side effect associated with the
  12834. // second expression.
  12835. SequenceTree::Seq LHSRegion = Tree.allocate(Region);
  12836. SequenceTree::Seq RHSRegion = Tree.allocate(Region);
  12837. SequenceTree::Seq OldRegion = Region;
  12838. EvaluationTracker Eval(*this);
  12839. {
  12840. SequencedSubexpression Sequenced(*this);
  12841. Region = LHSRegion;
  12842. Visit(BO->getLHS());
  12843. }
  12844. // C++11 [expr.log.and]p1:
  12845. // [...] the second operand is not evaluated if the first operand is false.
  12846. bool EvalResult = false;
  12847. bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
  12848. bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
  12849. if (ShouldVisitRHS) {
  12850. Region = RHSRegion;
  12851. Visit(BO->getRHS());
  12852. }
  12853. Region = OldRegion;
  12854. Tree.merge(LHSRegion);
  12855. Tree.merge(RHSRegion);
  12856. }
  12857. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
  12858. // C++11 [expr.cond]p1:
  12859. // [...] Every value computation and side effect associated with the first
  12860. // expression is sequenced before every value computation and side effect
  12861. // associated with the second or third expression.
  12862. SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
  12863. // No sequencing is specified between the true and false expression.
  12864. // However since exactly one of both is going to be evaluated we can
  12865. // consider them to be sequenced. This is needed to avoid warning on
  12866. // something like "x ? y+= 1 : y += 2;" in the case where we will visit
  12867. // both the true and false expressions because we can't evaluate x.
  12868. // This will still allow us to detect an expression like (pre C++17)
  12869. // "(x ? y += 1 : y += 2) = y".
  12870. //
  12871. // We don't wrap the visitation of the true and false expression with
  12872. // SequencedSubexpression because we don't want to downgrade modifications
  12873. // as side effect in the true and false expressions after the visition
  12874. // is done. (for example in the expression "(x ? y++ : y++) + y" we should
  12875. // not warn between the two "y++", but we should warn between the "y++"
  12876. // and the "y".
  12877. SequenceTree::Seq TrueRegion = Tree.allocate(Region);
  12878. SequenceTree::Seq FalseRegion = Tree.allocate(Region);
  12879. SequenceTree::Seq OldRegion = Region;
  12880. EvaluationTracker Eval(*this);
  12881. {
  12882. SequencedSubexpression Sequenced(*this);
  12883. Region = ConditionRegion;
  12884. Visit(CO->getCond());
  12885. }
  12886. // C++11 [expr.cond]p1:
  12887. // [...] The first expression is contextually converted to bool (Clause 4).
  12888. // It is evaluated and if it is true, the result of the conditional
  12889. // expression is the value of the second expression, otherwise that of the
  12890. // third expression. Only one of the second and third expressions is
  12891. // evaluated. [...]
  12892. bool EvalResult = false;
  12893. bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
  12894. bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
  12895. bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
  12896. if (ShouldVisitTrueExpr) {
  12897. Region = TrueRegion;
  12898. Visit(CO->getTrueExpr());
  12899. }
  12900. if (ShouldVisitFalseExpr) {
  12901. Region = FalseRegion;
  12902. Visit(CO->getFalseExpr());
  12903. }
  12904. Region = OldRegion;
  12905. Tree.merge(ConditionRegion);
  12906. Tree.merge(TrueRegion);
  12907. Tree.merge(FalseRegion);
  12908. }
  12909. void VisitCallExpr(const CallExpr *CE) {
  12910. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  12911. if (CE->isUnevaluatedBuiltinCall(Context))
  12912. return;
  12913. // C++11 [intro.execution]p15:
  12914. // When calling a function [...], every value computation and side effect
  12915. // associated with any argument expression, or with the postfix expression
  12916. // designating the called function, is sequenced before execution of every
  12917. // expression or statement in the body of the function [and thus before
  12918. // the value computation of its result].
  12919. SequencedSubexpression Sequenced(*this);
  12920. SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
  12921. // C++17 [expr.call]p5
  12922. // The postfix-expression is sequenced before each expression in the
  12923. // expression-list and any default argument. [...]
  12924. SequenceTree::Seq CalleeRegion;
  12925. SequenceTree::Seq OtherRegion;
  12926. if (SemaRef.getLangOpts().CPlusPlus17) {
  12927. CalleeRegion = Tree.allocate(Region);
  12928. OtherRegion = Tree.allocate(Region);
  12929. } else {
  12930. CalleeRegion = Region;
  12931. OtherRegion = Region;
  12932. }
  12933. SequenceTree::Seq OldRegion = Region;
  12934. // Visit the callee expression first.
  12935. Region = CalleeRegion;
  12936. if (SemaRef.getLangOpts().CPlusPlus17) {
  12937. SequencedSubexpression Sequenced(*this);
  12938. Visit(CE->getCallee());
  12939. } else {
  12940. Visit(CE->getCallee());
  12941. }
  12942. // Then visit the argument expressions.
  12943. Region = OtherRegion;
  12944. for (const Expr *Argument : CE->arguments())
  12945. Visit(Argument);
  12946. Region = OldRegion;
  12947. if (SemaRef.getLangOpts().CPlusPlus17) {
  12948. Tree.merge(CalleeRegion);
  12949. Tree.merge(OtherRegion);
  12950. }
  12951. });
  12952. }
  12953. void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
  12954. // C++17 [over.match.oper]p2:
  12955. // [...] the operator notation is first transformed to the equivalent
  12956. // function-call notation as summarized in Table 12 (where @ denotes one
  12957. // of the operators covered in the specified subclause). However, the
  12958. // operands are sequenced in the order prescribed for the built-in
  12959. // operator (Clause 8).
  12960. //
  12961. // From the above only overloaded binary operators and overloaded call
  12962. // operators have sequencing rules in C++17 that we need to handle
  12963. // separately.
  12964. if (!SemaRef.getLangOpts().CPlusPlus17 ||
  12965. (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
  12966. return VisitCallExpr(CXXOCE);
  12967. enum {
  12968. NoSequencing,
  12969. LHSBeforeRHS,
  12970. RHSBeforeLHS,
  12971. LHSBeforeRest
  12972. } SequencingKind;
  12973. switch (CXXOCE->getOperator()) {
  12974. case OO_Equal:
  12975. case OO_PlusEqual:
  12976. case OO_MinusEqual:
  12977. case OO_StarEqual:
  12978. case OO_SlashEqual:
  12979. case OO_PercentEqual:
  12980. case OO_CaretEqual:
  12981. case OO_AmpEqual:
  12982. case OO_PipeEqual:
  12983. case OO_LessLessEqual:
  12984. case OO_GreaterGreaterEqual:
  12985. SequencingKind = RHSBeforeLHS;
  12986. break;
  12987. case OO_LessLess:
  12988. case OO_GreaterGreater:
  12989. case OO_AmpAmp:
  12990. case OO_PipePipe:
  12991. case OO_Comma:
  12992. case OO_ArrowStar:
  12993. case OO_Subscript:
  12994. SequencingKind = LHSBeforeRHS;
  12995. break;
  12996. case OO_Call:
  12997. SequencingKind = LHSBeforeRest;
  12998. break;
  12999. default:
  13000. SequencingKind = NoSequencing;
  13001. break;
  13002. }
  13003. if (SequencingKind == NoSequencing)
  13004. return VisitCallExpr(CXXOCE);
  13005. // This is a call, so all subexpressions are sequenced before the result.
  13006. SequencedSubexpression Sequenced(*this);
  13007. SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
  13008. assert(SemaRef.getLangOpts().CPlusPlus17 &&
  13009. "Should only get there with C++17 and above!");
  13010. assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
  13011. "Should only get there with an overloaded binary operator"
  13012. " or an overloaded call operator!");
  13013. if (SequencingKind == LHSBeforeRest) {
  13014. assert(CXXOCE->getOperator() == OO_Call &&
  13015. "We should only have an overloaded call operator here!");
  13016. // This is very similar to VisitCallExpr, except that we only have the
  13017. // C++17 case. The postfix-expression is the first argument of the
  13018. // CXXOperatorCallExpr. The expressions in the expression-list, if any,
  13019. // are in the following arguments.
  13020. //
  13021. // Note that we intentionally do not visit the callee expression since
  13022. // it is just a decayed reference to a function.
  13023. SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
  13024. SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
  13025. SequenceTree::Seq OldRegion = Region;
  13026. assert(CXXOCE->getNumArgs() >= 1 &&
  13027. "An overloaded call operator must have at least one argument"
  13028. " for the postfix-expression!");
  13029. const Expr *PostfixExpr = CXXOCE->getArgs()[0];
  13030. llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
  13031. CXXOCE->getNumArgs() - 1);
  13032. // Visit the postfix-expression first.
  13033. {
  13034. Region = PostfixExprRegion;
  13035. SequencedSubexpression Sequenced(*this);
  13036. Visit(PostfixExpr);
  13037. }
  13038. // Then visit the argument expressions.
  13039. Region = ArgsRegion;
  13040. for (const Expr *Arg : Args)
  13041. Visit(Arg);
  13042. Region = OldRegion;
  13043. Tree.merge(PostfixExprRegion);
  13044. Tree.merge(ArgsRegion);
  13045. } else {
  13046. assert(CXXOCE->getNumArgs() == 2 &&
  13047. "Should only have two arguments here!");
  13048. assert((SequencingKind == LHSBeforeRHS ||
  13049. SequencingKind == RHSBeforeLHS) &&
  13050. "Unexpected sequencing kind!");
  13051. // We do not visit the callee expression since it is just a decayed
  13052. // reference to a function.
  13053. const Expr *E1 = CXXOCE->getArg(0);
  13054. const Expr *E2 = CXXOCE->getArg(1);
  13055. if (SequencingKind == RHSBeforeLHS)
  13056. std::swap(E1, E2);
  13057. return VisitSequencedExpressions(E1, E2);
  13058. }
  13059. });
  13060. }
  13061. void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
  13062. // This is a call, so all subexpressions are sequenced before the result.
  13063. SequencedSubexpression Sequenced(*this);
  13064. if (!CCE->isListInitialization())
  13065. return VisitExpr(CCE);
  13066. // In C++11, list initializations are sequenced.
  13067. SmallVector<SequenceTree::Seq, 32> Elts;
  13068. SequenceTree::Seq Parent = Region;
  13069. for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
  13070. E = CCE->arg_end();
  13071. I != E; ++I) {
  13072. Region = Tree.allocate(Parent);
  13073. Elts.push_back(Region);
  13074. Visit(*I);
  13075. }
  13076. // Forget that the initializers are sequenced.
  13077. Region = Parent;
  13078. for (unsigned I = 0; I < Elts.size(); ++I)
  13079. Tree.merge(Elts[I]);
  13080. }
  13081. void VisitInitListExpr(const InitListExpr *ILE) {
  13082. if (!SemaRef.getLangOpts().CPlusPlus11)
  13083. return VisitExpr(ILE);
  13084. // In C++11, list initializations are sequenced.
  13085. SmallVector<SequenceTree::Seq, 32> Elts;
  13086. SequenceTree::Seq Parent = Region;
  13087. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  13088. const Expr *E = ILE->getInit(I);
  13089. if (!E)
  13090. continue;
  13091. Region = Tree.allocate(Parent);
  13092. Elts.push_back(Region);
  13093. Visit(E);
  13094. }
  13095. // Forget that the initializers are sequenced.
  13096. Region = Parent;
  13097. for (unsigned I = 0; I < Elts.size(); ++I)
  13098. Tree.merge(Elts[I]);
  13099. }
  13100. };
  13101. } // namespace
  13102. void Sema::CheckUnsequencedOperations(const Expr *E) {
  13103. SmallVector<const Expr *, 8> WorkList;
  13104. WorkList.push_back(E);
  13105. while (!WorkList.empty()) {
  13106. const Expr *Item = WorkList.pop_back_val();
  13107. SequenceChecker(*this, Item, WorkList);
  13108. }
  13109. }
  13110. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  13111. bool IsConstexpr) {
  13112. llvm::SaveAndRestore<bool> ConstantContext(
  13113. isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
  13114. CheckImplicitConversions(E, CheckLoc);
  13115. if (!E->isInstantiationDependent())
  13116. CheckUnsequencedOperations(E);
  13117. if (!IsConstexpr && !E->isValueDependent())
  13118. CheckForIntOverflow(E);
  13119. DiagnoseMisalignedMembers();
  13120. }
  13121. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  13122. FieldDecl *BitField,
  13123. Expr *Init) {
  13124. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  13125. }
  13126. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  13127. SourceLocation Loc) {
  13128. if (!PType->isVariablyModifiedType())
  13129. return;
  13130. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  13131. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  13132. return;
  13133. }
  13134. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  13135. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  13136. return;
  13137. }
  13138. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  13139. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  13140. return;
  13141. }
  13142. const ArrayType *AT = S.Context.getAsArrayType(PType);
  13143. if (!AT)
  13144. return;
  13145. if (AT->getSizeModifier() != ArrayType::Star) {
  13146. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  13147. return;
  13148. }
  13149. S.Diag(Loc, diag::err_array_star_in_function_definition);
  13150. }
  13151. /// CheckParmsForFunctionDef - Check that the parameters of the given
  13152. /// function are appropriate for the definition of a function. This
  13153. /// takes care of any checks that cannot be performed on the
  13154. /// declaration itself, e.g., that the types of each of the function
  13155. /// parameters are complete.
  13156. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  13157. bool CheckParameterNames) {
  13158. bool HasInvalidParm = false;
  13159. for (ParmVarDecl *Param : Parameters) {
  13160. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  13161. // function declarator that is part of a function definition of
  13162. // that function shall not have incomplete type.
  13163. //
  13164. // This is also C++ [dcl.fct]p6.
  13165. if (!Param->isInvalidDecl() &&
  13166. RequireCompleteType(Param->getLocation(), Param->getType(),
  13167. diag::err_typecheck_decl_incomplete_type)) {
  13168. Param->setInvalidDecl();
  13169. HasInvalidParm = true;
  13170. }
  13171. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  13172. // declaration of each parameter shall include an identifier.
  13173. if (CheckParameterNames && Param->getIdentifier() == nullptr &&
  13174. !Param->isImplicit() && !getLangOpts().CPlusPlus) {
  13175. // Diagnose this as an extension in C17 and earlier.
  13176. if (!getLangOpts().C2x)
  13177. Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
  13178. }
  13179. // C99 6.7.5.3p12:
  13180. // If the function declarator is not part of a definition of that
  13181. // function, parameters may have incomplete type and may use the [*]
  13182. // notation in their sequences of declarator specifiers to specify
  13183. // variable length array types.
  13184. QualType PType = Param->getOriginalType();
  13185. // FIXME: This diagnostic should point the '[*]' if source-location
  13186. // information is added for it.
  13187. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  13188. // If the parameter is a c++ class type and it has to be destructed in the
  13189. // callee function, declare the destructor so that it can be called by the
  13190. // callee function. Do not perform any direct access check on the dtor here.
  13191. if (!Param->isInvalidDecl()) {
  13192. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  13193. if (!ClassDecl->isInvalidDecl() &&
  13194. !ClassDecl->hasIrrelevantDestructor() &&
  13195. !ClassDecl->isDependentContext() &&
  13196. ClassDecl->isParamDestroyedInCallee()) {
  13197. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  13198. MarkFunctionReferenced(Param->getLocation(), Destructor);
  13199. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  13200. }
  13201. }
  13202. }
  13203. // Parameters with the pass_object_size attribute only need to be marked
  13204. // constant at function definitions. Because we lack information about
  13205. // whether we're on a declaration or definition when we're instantiating the
  13206. // attribute, we need to check for constness here.
  13207. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  13208. if (!Param->getType().isConstQualified())
  13209. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  13210. << Attr->getSpelling() << 1;
  13211. // Check for parameter names shadowing fields from the class.
  13212. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  13213. // The owning context for the parameter should be the function, but we
  13214. // want to see if this function's declaration context is a record.
  13215. DeclContext *DC = Param->getDeclContext();
  13216. if (DC && DC->isFunctionOrMethod()) {
  13217. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  13218. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  13219. RD, /*DeclIsField*/ false);
  13220. }
  13221. }
  13222. }
  13223. return HasInvalidParm;
  13224. }
  13225. Optional<std::pair<CharUnits, CharUnits>>
  13226. static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
  13227. /// Compute the alignment and offset of the base class object given the
  13228. /// derived-to-base cast expression and the alignment and offset of the derived
  13229. /// class object.
  13230. static std::pair<CharUnits, CharUnits>
  13231. getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
  13232. CharUnits BaseAlignment, CharUnits Offset,
  13233. ASTContext &Ctx) {
  13234. for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
  13235. ++PathI) {
  13236. const CXXBaseSpecifier *Base = *PathI;
  13237. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  13238. if (Base->isVirtual()) {
  13239. // The complete object may have a lower alignment than the non-virtual
  13240. // alignment of the base, in which case the base may be misaligned. Choose
  13241. // the smaller of the non-virtual alignment and BaseAlignment, which is a
  13242. // conservative lower bound of the complete object alignment.
  13243. CharUnits NonVirtualAlignment =
  13244. Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
  13245. BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
  13246. Offset = CharUnits::Zero();
  13247. } else {
  13248. const ASTRecordLayout &RL =
  13249. Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
  13250. Offset += RL.getBaseClassOffset(BaseDecl);
  13251. }
  13252. DerivedType = Base->getType();
  13253. }
  13254. return std::make_pair(BaseAlignment, Offset);
  13255. }
  13256. /// Compute the alignment and offset of a binary additive operator.
  13257. static Optional<std::pair<CharUnits, CharUnits>>
  13258. getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
  13259. bool IsSub, ASTContext &Ctx) {
  13260. QualType PointeeType = PtrE->getType()->getPointeeType();
  13261. if (!PointeeType->isConstantSizeType())
  13262. return llvm::None;
  13263. auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
  13264. if (!P)
  13265. return llvm::None;
  13266. CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
  13267. if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
  13268. CharUnits Offset = EltSize * IdxRes->getExtValue();
  13269. if (IsSub)
  13270. Offset = -Offset;
  13271. return std::make_pair(P->first, P->second + Offset);
  13272. }
  13273. // If the integer expression isn't a constant expression, compute the lower
  13274. // bound of the alignment using the alignment and offset of the pointer
  13275. // expression and the element size.
  13276. return std::make_pair(
  13277. P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
  13278. CharUnits::Zero());
  13279. }
  13280. /// This helper function takes an lvalue expression and returns the alignment of
  13281. /// a VarDecl and a constant offset from the VarDecl.
  13282. Optional<std::pair<CharUnits, CharUnits>>
  13283. static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
  13284. E = E->IgnoreParens();
  13285. switch (E->getStmtClass()) {
  13286. default:
  13287. break;
  13288. case Stmt::CStyleCastExprClass:
  13289. case Stmt::CXXStaticCastExprClass:
  13290. case Stmt::ImplicitCastExprClass: {
  13291. auto *CE = cast<CastExpr>(E);
  13292. const Expr *From = CE->getSubExpr();
  13293. switch (CE->getCastKind()) {
  13294. default:
  13295. break;
  13296. case CK_NoOp:
  13297. return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
  13298. case CK_UncheckedDerivedToBase:
  13299. case CK_DerivedToBase: {
  13300. auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
  13301. if (!P)
  13302. break;
  13303. return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
  13304. P->second, Ctx);
  13305. }
  13306. }
  13307. break;
  13308. }
  13309. case Stmt::ArraySubscriptExprClass: {
  13310. auto *ASE = cast<ArraySubscriptExpr>(E);
  13311. return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
  13312. false, Ctx);
  13313. }
  13314. case Stmt::DeclRefExprClass: {
  13315. if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
  13316. // FIXME: If VD is captured by copy or is an escaping __block variable,
  13317. // use the alignment of VD's type.
  13318. if (!VD->getType()->isReferenceType())
  13319. return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
  13320. if (VD->hasInit())
  13321. return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
  13322. }
  13323. break;
  13324. }
  13325. case Stmt::MemberExprClass: {
  13326. auto *ME = cast<MemberExpr>(E);
  13327. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  13328. if (!FD || FD->getType()->isReferenceType() ||
  13329. FD->getParent()->isInvalidDecl())
  13330. break;
  13331. Optional<std::pair<CharUnits, CharUnits>> P;
  13332. if (ME->isArrow())
  13333. P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
  13334. else
  13335. P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
  13336. if (!P)
  13337. break;
  13338. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
  13339. uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
  13340. return std::make_pair(P->first,
  13341. P->second + CharUnits::fromQuantity(Offset));
  13342. }
  13343. case Stmt::UnaryOperatorClass: {
  13344. auto *UO = cast<UnaryOperator>(E);
  13345. switch (UO->getOpcode()) {
  13346. default:
  13347. break;
  13348. case UO_Deref:
  13349. return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
  13350. }
  13351. break;
  13352. }
  13353. case Stmt::BinaryOperatorClass: {
  13354. auto *BO = cast<BinaryOperator>(E);
  13355. auto Opcode = BO->getOpcode();
  13356. switch (Opcode) {
  13357. default:
  13358. break;
  13359. case BO_Comma:
  13360. return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
  13361. }
  13362. break;
  13363. }
  13364. }
  13365. return llvm::None;
  13366. }
  13367. /// This helper function takes a pointer expression and returns the alignment of
  13368. /// a VarDecl and a constant offset from the VarDecl.
  13369. Optional<std::pair<CharUnits, CharUnits>>
  13370. static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
  13371. E = E->IgnoreParens();
  13372. switch (E->getStmtClass()) {
  13373. default:
  13374. break;
  13375. case Stmt::CStyleCastExprClass:
  13376. case Stmt::CXXStaticCastExprClass:
  13377. case Stmt::ImplicitCastExprClass: {
  13378. auto *CE = cast<CastExpr>(E);
  13379. const Expr *From = CE->getSubExpr();
  13380. switch (CE->getCastKind()) {
  13381. default:
  13382. break;
  13383. case CK_NoOp:
  13384. return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
  13385. case CK_ArrayToPointerDecay:
  13386. return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
  13387. case CK_UncheckedDerivedToBase:
  13388. case CK_DerivedToBase: {
  13389. auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
  13390. if (!P)
  13391. break;
  13392. return getDerivedToBaseAlignmentAndOffset(
  13393. CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
  13394. }
  13395. }
  13396. break;
  13397. }
  13398. case Stmt::CXXThisExprClass: {
  13399. auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
  13400. CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
  13401. return std::make_pair(Alignment, CharUnits::Zero());
  13402. }
  13403. case Stmt::UnaryOperatorClass: {
  13404. auto *UO = cast<UnaryOperator>(E);
  13405. if (UO->getOpcode() == UO_AddrOf)
  13406. return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
  13407. break;
  13408. }
  13409. case Stmt::BinaryOperatorClass: {
  13410. auto *BO = cast<BinaryOperator>(E);
  13411. auto Opcode = BO->getOpcode();
  13412. switch (Opcode) {
  13413. default:
  13414. break;
  13415. case BO_Add:
  13416. case BO_Sub: {
  13417. const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
  13418. if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
  13419. std::swap(LHS, RHS);
  13420. return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
  13421. Ctx);
  13422. }
  13423. case BO_Comma:
  13424. return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
  13425. }
  13426. break;
  13427. }
  13428. }
  13429. return llvm::None;
  13430. }
  13431. static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
  13432. // See if we can compute the alignment of a VarDecl and an offset from it.
  13433. Optional<std::pair<CharUnits, CharUnits>> P =
  13434. getBaseAlignmentAndOffsetFromPtr(E, S.Context);
  13435. if (P)
  13436. return P->first.alignmentAtOffset(P->second);
  13437. // If that failed, return the type's alignment.
  13438. return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
  13439. }
  13440. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  13441. /// pointer cast increases the alignment requirements.
  13442. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  13443. // This is actually a lot of work to potentially be doing on every
  13444. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  13445. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  13446. return;
  13447. // Ignore dependent types.
  13448. if (T->isDependentType() || Op->getType()->isDependentType())
  13449. return;
  13450. // Require that the destination be a pointer type.
  13451. const PointerType *DestPtr = T->getAs<PointerType>();
  13452. if (!DestPtr) return;
  13453. // If the destination has alignment 1, we're done.
  13454. QualType DestPointee = DestPtr->getPointeeType();
  13455. if (DestPointee->isIncompleteType()) return;
  13456. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  13457. if (DestAlign.isOne()) return;
  13458. // Require that the source be a pointer type.
  13459. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  13460. if (!SrcPtr) return;
  13461. QualType SrcPointee = SrcPtr->getPointeeType();
  13462. // Explicitly allow casts from cv void*. We already implicitly
  13463. // allowed casts to cv void*, since they have alignment 1.
  13464. // Also allow casts involving incomplete types, which implicitly
  13465. // includes 'void'.
  13466. if (SrcPointee->isIncompleteType()) return;
  13467. CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
  13468. if (SrcAlign >= DestAlign) return;
  13469. Diag(TRange.getBegin(), diag::warn_cast_align)
  13470. << Op->getType() << T
  13471. << static_cast<unsigned>(SrcAlign.getQuantity())
  13472. << static_cast<unsigned>(DestAlign.getQuantity())
  13473. << TRange << Op->getSourceRange();
  13474. }
  13475. /// Check whether this array fits the idiom of a size-one tail padded
  13476. /// array member of a struct.
  13477. ///
  13478. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  13479. /// commonly used to emulate flexible arrays in C89 code.
  13480. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  13481. const NamedDecl *ND) {
  13482. if (Size != 1 || !ND) return false;
  13483. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  13484. if (!FD) return false;
  13485. // Don't consider sizes resulting from macro expansions or template argument
  13486. // substitution to form C89 tail-padded arrays.
  13487. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  13488. while (TInfo) {
  13489. TypeLoc TL = TInfo->getTypeLoc();
  13490. // Look through typedefs.
  13491. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  13492. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  13493. TInfo = TDL->getTypeSourceInfo();
  13494. continue;
  13495. }
  13496. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  13497. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  13498. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  13499. return false;
  13500. }
  13501. break;
  13502. }
  13503. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  13504. if (!RD) return false;
  13505. if (RD->isUnion()) return false;
  13506. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  13507. if (!CRD->isStandardLayout()) return false;
  13508. }
  13509. // See if this is the last field decl in the record.
  13510. const Decl *D = FD;
  13511. while ((D = D->getNextDeclInContext()))
  13512. if (isa<FieldDecl>(D))
  13513. return false;
  13514. return true;
  13515. }
  13516. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  13517. const ArraySubscriptExpr *ASE,
  13518. bool AllowOnePastEnd, bool IndexNegated) {
  13519. // Already diagnosed by the constant evaluator.
  13520. if (isConstantEvaluated())
  13521. return;
  13522. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  13523. if (IndexExpr->isValueDependent())
  13524. return;
  13525. const Type *EffectiveType =
  13526. BaseExpr->getType()->getPointeeOrArrayElementType();
  13527. BaseExpr = BaseExpr->IgnoreParenCasts();
  13528. const ConstantArrayType *ArrayTy =
  13529. Context.getAsConstantArrayType(BaseExpr->getType());
  13530. const Type *BaseType =
  13531. ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
  13532. bool IsUnboundedArray = (BaseType == nullptr);
  13533. if (EffectiveType->isDependentType() ||
  13534. (!IsUnboundedArray && BaseType->isDependentType()))
  13535. return;
  13536. Expr::EvalResult Result;
  13537. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  13538. return;
  13539. llvm::APSInt index = Result.Val.getInt();
  13540. if (IndexNegated) {
  13541. index.setIsUnsigned(false);
  13542. index = -index;
  13543. }
  13544. const NamedDecl *ND = nullptr;
  13545. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  13546. ND = DRE->getDecl();
  13547. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  13548. ND = ME->getMemberDecl();
  13549. if (IsUnboundedArray) {
  13550. if (index.isUnsigned() || !index.isNegative()) {
  13551. const auto &ASTC = getASTContext();
  13552. unsigned AddrBits =
  13553. ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
  13554. EffectiveType->getCanonicalTypeInternal()));
  13555. if (index.getBitWidth() < AddrBits)
  13556. index = index.zext(AddrBits);
  13557. Optional<CharUnits> ElemCharUnits =
  13558. ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
  13559. // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
  13560. // pointer) bounds-checking isn't meaningful.
  13561. if (!ElemCharUnits)
  13562. return;
  13563. llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
  13564. // If index has more active bits than address space, we already know
  13565. // we have a bounds violation to warn about. Otherwise, compute
  13566. // address of (index + 1)th element, and warn about bounds violation
  13567. // only if that address exceeds address space.
  13568. if (index.getActiveBits() <= AddrBits) {
  13569. bool Overflow;
  13570. llvm::APInt Product(index);
  13571. Product += 1;
  13572. Product = Product.umul_ov(ElemBytes, Overflow);
  13573. if (!Overflow && Product.getActiveBits() <= AddrBits)
  13574. return;
  13575. }
  13576. // Need to compute max possible elements in address space, since that
  13577. // is included in diag message.
  13578. llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
  13579. MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
  13580. MaxElems += 1;
  13581. ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
  13582. MaxElems = MaxElems.udiv(ElemBytes);
  13583. unsigned DiagID =
  13584. ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
  13585. : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
  13586. // Diag message shows element size in bits and in "bytes" (platform-
  13587. // dependent CharUnits)
  13588. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  13589. PDiag(DiagID)
  13590. << toString(index, 10, true) << AddrBits
  13591. << (unsigned)ASTC.toBits(*ElemCharUnits)
  13592. << toString(ElemBytes, 10, false)
  13593. << toString(MaxElems, 10, false)
  13594. << (unsigned)MaxElems.getLimitedValue(~0U)
  13595. << IndexExpr->getSourceRange());
  13596. if (!ND) {
  13597. // Try harder to find a NamedDecl to point at in the note.
  13598. while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
  13599. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  13600. if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  13601. ND = DRE->getDecl();
  13602. if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
  13603. ND = ME->getMemberDecl();
  13604. }
  13605. if (ND)
  13606. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  13607. PDiag(diag::note_array_declared_here) << ND);
  13608. }
  13609. return;
  13610. }
  13611. if (index.isUnsigned() || !index.isNegative()) {
  13612. // It is possible that the type of the base expression after
  13613. // IgnoreParenCasts is incomplete, even though the type of the base
  13614. // expression before IgnoreParenCasts is complete (see PR39746 for an
  13615. // example). In this case we have no information about whether the array
  13616. // access exceeds the array bounds. However we can still diagnose an array
  13617. // access which precedes the array bounds.
  13618. if (BaseType->isIncompleteType())
  13619. return;
  13620. llvm::APInt size = ArrayTy->getSize();
  13621. if (!size.isStrictlyPositive())
  13622. return;
  13623. if (BaseType != EffectiveType) {
  13624. // Make sure we're comparing apples to apples when comparing index to size
  13625. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  13626. uint64_t array_typesize = Context.getTypeSize(BaseType);
  13627. // Handle ptrarith_typesize being zero, such as when casting to void*
  13628. if (!ptrarith_typesize) ptrarith_typesize = 1;
  13629. if (ptrarith_typesize != array_typesize) {
  13630. // There's a cast to a different size type involved
  13631. uint64_t ratio = array_typesize / ptrarith_typesize;
  13632. // TODO: Be smarter about handling cases where array_typesize is not a
  13633. // multiple of ptrarith_typesize
  13634. if (ptrarith_typesize * ratio == array_typesize)
  13635. size *= llvm::APInt(size.getBitWidth(), ratio);
  13636. }
  13637. }
  13638. if (size.getBitWidth() > index.getBitWidth())
  13639. index = index.zext(size.getBitWidth());
  13640. else if (size.getBitWidth() < index.getBitWidth())
  13641. size = size.zext(index.getBitWidth());
  13642. // For array subscripting the index must be less than size, but for pointer
  13643. // arithmetic also allow the index (offset) to be equal to size since
  13644. // computing the next address after the end of the array is legal and
  13645. // commonly done e.g. in C++ iterators and range-based for loops.
  13646. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  13647. return;
  13648. // Also don't warn for arrays of size 1 which are members of some
  13649. // structure. These are often used to approximate flexible arrays in C89
  13650. // code.
  13651. if (IsTailPaddedMemberArray(*this, size, ND))
  13652. return;
  13653. // Suppress the warning if the subscript expression (as identified by the
  13654. // ']' location) and the index expression are both from macro expansions
  13655. // within a system header.
  13656. if (ASE) {
  13657. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  13658. ASE->getRBracketLoc());
  13659. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  13660. SourceLocation IndexLoc =
  13661. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  13662. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  13663. return;
  13664. }
  13665. }
  13666. unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
  13667. : diag::warn_ptr_arith_exceeds_bounds;
  13668. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  13669. PDiag(DiagID) << toString(index, 10, true)
  13670. << toString(size, 10, true)
  13671. << (unsigned)size.getLimitedValue(~0U)
  13672. << IndexExpr->getSourceRange());
  13673. } else {
  13674. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  13675. if (!ASE) {
  13676. DiagID = diag::warn_ptr_arith_precedes_bounds;
  13677. if (index.isNegative()) index = -index;
  13678. }
  13679. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  13680. PDiag(DiagID) << toString(index, 10, true)
  13681. << IndexExpr->getSourceRange());
  13682. }
  13683. if (!ND) {
  13684. // Try harder to find a NamedDecl to point at in the note.
  13685. while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
  13686. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  13687. if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  13688. ND = DRE->getDecl();
  13689. if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
  13690. ND = ME->getMemberDecl();
  13691. }
  13692. if (ND)
  13693. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  13694. PDiag(diag::note_array_declared_here) << ND);
  13695. }
  13696. void Sema::CheckArrayAccess(const Expr *expr) {
  13697. int AllowOnePastEnd = 0;
  13698. while (expr) {
  13699. expr = expr->IgnoreParenImpCasts();
  13700. switch (expr->getStmtClass()) {
  13701. case Stmt::ArraySubscriptExprClass: {
  13702. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  13703. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  13704. AllowOnePastEnd > 0);
  13705. expr = ASE->getBase();
  13706. break;
  13707. }
  13708. case Stmt::MemberExprClass: {
  13709. expr = cast<MemberExpr>(expr)->getBase();
  13710. break;
  13711. }
  13712. case Stmt::OMPArraySectionExprClass: {
  13713. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  13714. if (ASE->getLowerBound())
  13715. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  13716. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  13717. return;
  13718. }
  13719. case Stmt::UnaryOperatorClass: {
  13720. // Only unwrap the * and & unary operators
  13721. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  13722. expr = UO->getSubExpr();
  13723. switch (UO->getOpcode()) {
  13724. case UO_AddrOf:
  13725. AllowOnePastEnd++;
  13726. break;
  13727. case UO_Deref:
  13728. AllowOnePastEnd--;
  13729. break;
  13730. default:
  13731. return;
  13732. }
  13733. break;
  13734. }
  13735. case Stmt::ConditionalOperatorClass: {
  13736. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  13737. if (const Expr *lhs = cond->getLHS())
  13738. CheckArrayAccess(lhs);
  13739. if (const Expr *rhs = cond->getRHS())
  13740. CheckArrayAccess(rhs);
  13741. return;
  13742. }
  13743. case Stmt::CXXOperatorCallExprClass: {
  13744. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  13745. for (const auto *Arg : OCE->arguments())
  13746. CheckArrayAccess(Arg);
  13747. return;
  13748. }
  13749. default:
  13750. return;
  13751. }
  13752. }
  13753. }
  13754. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  13755. namespace {
  13756. struct RetainCycleOwner {
  13757. VarDecl *Variable = nullptr;
  13758. SourceRange Range;
  13759. SourceLocation Loc;
  13760. bool Indirect = false;
  13761. RetainCycleOwner() = default;
  13762. void setLocsFrom(Expr *e) {
  13763. Loc = e->getExprLoc();
  13764. Range = e->getSourceRange();
  13765. }
  13766. };
  13767. } // namespace
  13768. /// Consider whether capturing the given variable can possibly lead to
  13769. /// a retain cycle.
  13770. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  13771. // In ARC, it's captured strongly iff the variable has __strong
  13772. // lifetime. In MRR, it's captured strongly if the variable is
  13773. // __block and has an appropriate type.
  13774. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  13775. return false;
  13776. owner.Variable = var;
  13777. if (ref)
  13778. owner.setLocsFrom(ref);
  13779. return true;
  13780. }
  13781. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  13782. while (true) {
  13783. e = e->IgnoreParens();
  13784. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  13785. switch (cast->getCastKind()) {
  13786. case CK_BitCast:
  13787. case CK_LValueBitCast:
  13788. case CK_LValueToRValue:
  13789. case CK_ARCReclaimReturnedObject:
  13790. e = cast->getSubExpr();
  13791. continue;
  13792. default:
  13793. return false;
  13794. }
  13795. }
  13796. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  13797. ObjCIvarDecl *ivar = ref->getDecl();
  13798. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  13799. return false;
  13800. // Try to find a retain cycle in the base.
  13801. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  13802. return false;
  13803. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  13804. owner.Indirect = true;
  13805. return true;
  13806. }
  13807. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  13808. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  13809. if (!var) return false;
  13810. return considerVariable(var, ref, owner);
  13811. }
  13812. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  13813. if (member->isArrow()) return false;
  13814. // Don't count this as an indirect ownership.
  13815. e = member->getBase();
  13816. continue;
  13817. }
  13818. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  13819. // Only pay attention to pseudo-objects on property references.
  13820. ObjCPropertyRefExpr *pre
  13821. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  13822. ->IgnoreParens());
  13823. if (!pre) return false;
  13824. if (pre->isImplicitProperty()) return false;
  13825. ObjCPropertyDecl *property = pre->getExplicitProperty();
  13826. if (!property->isRetaining() &&
  13827. !(property->getPropertyIvarDecl() &&
  13828. property->getPropertyIvarDecl()->getType()
  13829. .getObjCLifetime() == Qualifiers::OCL_Strong))
  13830. return false;
  13831. owner.Indirect = true;
  13832. if (pre->isSuperReceiver()) {
  13833. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  13834. if (!owner.Variable)
  13835. return false;
  13836. owner.Loc = pre->getLocation();
  13837. owner.Range = pre->getSourceRange();
  13838. return true;
  13839. }
  13840. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  13841. ->getSourceExpr());
  13842. continue;
  13843. }
  13844. // Array ivars?
  13845. return false;
  13846. }
  13847. }
  13848. namespace {
  13849. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  13850. ASTContext &Context;
  13851. VarDecl *Variable;
  13852. Expr *Capturer = nullptr;
  13853. bool VarWillBeReased = false;
  13854. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  13855. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  13856. Context(Context), Variable(variable) {}
  13857. void VisitDeclRefExpr(DeclRefExpr *ref) {
  13858. if (ref->getDecl() == Variable && !Capturer)
  13859. Capturer = ref;
  13860. }
  13861. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  13862. if (Capturer) return;
  13863. Visit(ref->getBase());
  13864. if (Capturer && ref->isFreeIvar())
  13865. Capturer = ref;
  13866. }
  13867. void VisitBlockExpr(BlockExpr *block) {
  13868. // Look inside nested blocks
  13869. if (block->getBlockDecl()->capturesVariable(Variable))
  13870. Visit(block->getBlockDecl()->getBody());
  13871. }
  13872. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  13873. if (Capturer) return;
  13874. if (OVE->getSourceExpr())
  13875. Visit(OVE->getSourceExpr());
  13876. }
  13877. void VisitBinaryOperator(BinaryOperator *BinOp) {
  13878. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  13879. return;
  13880. Expr *LHS = BinOp->getLHS();
  13881. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  13882. if (DRE->getDecl() != Variable)
  13883. return;
  13884. if (Expr *RHS = BinOp->getRHS()) {
  13885. RHS = RHS->IgnoreParenCasts();
  13886. Optional<llvm::APSInt> Value;
  13887. VarWillBeReased =
  13888. (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
  13889. *Value == 0);
  13890. }
  13891. }
  13892. }
  13893. };
  13894. } // namespace
  13895. /// Check whether the given argument is a block which captures a
  13896. /// variable.
  13897. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  13898. assert(owner.Variable && owner.Loc.isValid());
  13899. e = e->IgnoreParenCasts();
  13900. // Look through [^{...} copy] and Block_copy(^{...}).
  13901. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  13902. Selector Cmd = ME->getSelector();
  13903. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  13904. e = ME->getInstanceReceiver();
  13905. if (!e)
  13906. return nullptr;
  13907. e = e->IgnoreParenCasts();
  13908. }
  13909. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  13910. if (CE->getNumArgs() == 1) {
  13911. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  13912. if (Fn) {
  13913. const IdentifierInfo *FnI = Fn->getIdentifier();
  13914. if (FnI && FnI->isStr("_Block_copy")) {
  13915. e = CE->getArg(0)->IgnoreParenCasts();
  13916. }
  13917. }
  13918. }
  13919. }
  13920. BlockExpr *block = dyn_cast<BlockExpr>(e);
  13921. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  13922. return nullptr;
  13923. FindCaptureVisitor visitor(S.Context, owner.Variable);
  13924. visitor.Visit(block->getBlockDecl()->getBody());
  13925. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  13926. }
  13927. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  13928. RetainCycleOwner &owner) {
  13929. assert(capturer);
  13930. assert(owner.Variable && owner.Loc.isValid());
  13931. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  13932. << owner.Variable << capturer->getSourceRange();
  13933. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  13934. << owner.Indirect << owner.Range;
  13935. }
  13936. /// Check for a keyword selector that starts with the word 'add' or
  13937. /// 'set'.
  13938. static bool isSetterLikeSelector(Selector sel) {
  13939. if (sel.isUnarySelector()) return false;
  13940. StringRef str = sel.getNameForSlot(0);
  13941. while (!str.empty() && str.front() == '_') str = str.substr(1);
  13942. if (str.startswith("set"))
  13943. str = str.substr(3);
  13944. else if (str.startswith("add")) {
  13945. // Specially allow 'addOperationWithBlock:'.
  13946. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  13947. return false;
  13948. str = str.substr(3);
  13949. }
  13950. else
  13951. return false;
  13952. if (str.empty()) return true;
  13953. return !isLowercase(str.front());
  13954. }
  13955. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  13956. ObjCMessageExpr *Message) {
  13957. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  13958. Message->getReceiverInterface(),
  13959. NSAPI::ClassId_NSMutableArray);
  13960. if (!IsMutableArray) {
  13961. return None;
  13962. }
  13963. Selector Sel = Message->getSelector();
  13964. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  13965. S.NSAPIObj->getNSArrayMethodKind(Sel);
  13966. if (!MKOpt) {
  13967. return None;
  13968. }
  13969. NSAPI::NSArrayMethodKind MK = *MKOpt;
  13970. switch (MK) {
  13971. case NSAPI::NSMutableArr_addObject:
  13972. case NSAPI::NSMutableArr_insertObjectAtIndex:
  13973. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  13974. return 0;
  13975. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  13976. return 1;
  13977. default:
  13978. return None;
  13979. }
  13980. return None;
  13981. }
  13982. static
  13983. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  13984. ObjCMessageExpr *Message) {
  13985. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  13986. Message->getReceiverInterface(),
  13987. NSAPI::ClassId_NSMutableDictionary);
  13988. if (!IsMutableDictionary) {
  13989. return None;
  13990. }
  13991. Selector Sel = Message->getSelector();
  13992. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  13993. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  13994. if (!MKOpt) {
  13995. return None;
  13996. }
  13997. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  13998. switch (MK) {
  13999. case NSAPI::NSMutableDict_setObjectForKey:
  14000. case NSAPI::NSMutableDict_setValueForKey:
  14001. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  14002. return 0;
  14003. default:
  14004. return None;
  14005. }
  14006. return None;
  14007. }
  14008. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  14009. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  14010. Message->getReceiverInterface(),
  14011. NSAPI::ClassId_NSMutableSet);
  14012. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  14013. Message->getReceiverInterface(),
  14014. NSAPI::ClassId_NSMutableOrderedSet);
  14015. if (!IsMutableSet && !IsMutableOrderedSet) {
  14016. return None;
  14017. }
  14018. Selector Sel = Message->getSelector();
  14019. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  14020. if (!MKOpt) {
  14021. return None;
  14022. }
  14023. NSAPI::NSSetMethodKind MK = *MKOpt;
  14024. switch (MK) {
  14025. case NSAPI::NSMutableSet_addObject:
  14026. case NSAPI::NSOrderedSet_setObjectAtIndex:
  14027. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  14028. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  14029. return 0;
  14030. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  14031. return 1;
  14032. }
  14033. return None;
  14034. }
  14035. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  14036. if (!Message->isInstanceMessage()) {
  14037. return;
  14038. }
  14039. Optional<int> ArgOpt;
  14040. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  14041. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  14042. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  14043. return;
  14044. }
  14045. int ArgIndex = *ArgOpt;
  14046. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  14047. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  14048. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  14049. }
  14050. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  14051. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  14052. if (ArgRE->isObjCSelfExpr()) {
  14053. Diag(Message->getSourceRange().getBegin(),
  14054. diag::warn_objc_circular_container)
  14055. << ArgRE->getDecl() << StringRef("'super'");
  14056. }
  14057. }
  14058. } else {
  14059. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  14060. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  14061. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  14062. }
  14063. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  14064. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  14065. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  14066. ValueDecl *Decl = ReceiverRE->getDecl();
  14067. Diag(Message->getSourceRange().getBegin(),
  14068. diag::warn_objc_circular_container)
  14069. << Decl << Decl;
  14070. if (!ArgRE->isObjCSelfExpr()) {
  14071. Diag(Decl->getLocation(),
  14072. diag::note_objc_circular_container_declared_here)
  14073. << Decl;
  14074. }
  14075. }
  14076. }
  14077. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  14078. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  14079. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  14080. ObjCIvarDecl *Decl = IvarRE->getDecl();
  14081. Diag(Message->getSourceRange().getBegin(),
  14082. diag::warn_objc_circular_container)
  14083. << Decl << Decl;
  14084. Diag(Decl->getLocation(),
  14085. diag::note_objc_circular_container_declared_here)
  14086. << Decl;
  14087. }
  14088. }
  14089. }
  14090. }
  14091. }
  14092. /// Check a message send to see if it's likely to cause a retain cycle.
  14093. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  14094. // Only check instance methods whose selector looks like a setter.
  14095. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  14096. return;
  14097. // Try to find a variable that the receiver is strongly owned by.
  14098. RetainCycleOwner owner;
  14099. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  14100. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  14101. return;
  14102. } else {
  14103. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  14104. owner.Variable = getCurMethodDecl()->getSelfDecl();
  14105. owner.Loc = msg->getSuperLoc();
  14106. owner.Range = msg->getSuperLoc();
  14107. }
  14108. // Check whether the receiver is captured by any of the arguments.
  14109. const ObjCMethodDecl *MD = msg->getMethodDecl();
  14110. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  14111. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  14112. // noescape blocks should not be retained by the method.
  14113. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  14114. continue;
  14115. return diagnoseRetainCycle(*this, capturer, owner);
  14116. }
  14117. }
  14118. }
  14119. /// Check a property assign to see if it's likely to cause a retain cycle.
  14120. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  14121. RetainCycleOwner owner;
  14122. if (!findRetainCycleOwner(*this, receiver, owner))
  14123. return;
  14124. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  14125. diagnoseRetainCycle(*this, capturer, owner);
  14126. }
  14127. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  14128. RetainCycleOwner Owner;
  14129. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  14130. return;
  14131. // Because we don't have an expression for the variable, we have to set the
  14132. // location explicitly here.
  14133. Owner.Loc = Var->getLocation();
  14134. Owner.Range = Var->getSourceRange();
  14135. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  14136. diagnoseRetainCycle(*this, Capturer, Owner);
  14137. }
  14138. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  14139. Expr *RHS, bool isProperty) {
  14140. // Check if RHS is an Objective-C object literal, which also can get
  14141. // immediately zapped in a weak reference. Note that we explicitly
  14142. // allow ObjCStringLiterals, since those are designed to never really die.
  14143. RHS = RHS->IgnoreParenImpCasts();
  14144. // This enum needs to match with the 'select' in
  14145. // warn_objc_arc_literal_assign (off-by-1).
  14146. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  14147. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  14148. return false;
  14149. S.Diag(Loc, diag::warn_arc_literal_assign)
  14150. << (unsigned) Kind
  14151. << (isProperty ? 0 : 1)
  14152. << RHS->getSourceRange();
  14153. return true;
  14154. }
  14155. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  14156. Qualifiers::ObjCLifetime LT,
  14157. Expr *RHS, bool isProperty) {
  14158. // Strip off any implicit cast added to get to the one ARC-specific.
  14159. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  14160. if (cast->getCastKind() == CK_ARCConsumeObject) {
  14161. S.Diag(Loc, diag::warn_arc_retained_assign)
  14162. << (LT == Qualifiers::OCL_ExplicitNone)
  14163. << (isProperty ? 0 : 1)
  14164. << RHS->getSourceRange();
  14165. return true;
  14166. }
  14167. RHS = cast->getSubExpr();
  14168. }
  14169. if (LT == Qualifiers::OCL_Weak &&
  14170. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  14171. return true;
  14172. return false;
  14173. }
  14174. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  14175. QualType LHS, Expr *RHS) {
  14176. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  14177. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  14178. return false;
  14179. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  14180. return true;
  14181. return false;
  14182. }
  14183. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  14184. Expr *LHS, Expr *RHS) {
  14185. QualType LHSType;
  14186. // PropertyRef on LHS type need be directly obtained from
  14187. // its declaration as it has a PseudoType.
  14188. ObjCPropertyRefExpr *PRE
  14189. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  14190. if (PRE && !PRE->isImplicitProperty()) {
  14191. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  14192. if (PD)
  14193. LHSType = PD->getType();
  14194. }
  14195. if (LHSType.isNull())
  14196. LHSType = LHS->getType();
  14197. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  14198. if (LT == Qualifiers::OCL_Weak) {
  14199. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  14200. getCurFunction()->markSafeWeakUse(LHS);
  14201. }
  14202. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  14203. return;
  14204. // FIXME. Check for other life times.
  14205. if (LT != Qualifiers::OCL_None)
  14206. return;
  14207. if (PRE) {
  14208. if (PRE->isImplicitProperty())
  14209. return;
  14210. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  14211. if (!PD)
  14212. return;
  14213. unsigned Attributes = PD->getPropertyAttributes();
  14214. if (Attributes & ObjCPropertyAttribute::kind_assign) {
  14215. // when 'assign' attribute was not explicitly specified
  14216. // by user, ignore it and rely on property type itself
  14217. // for lifetime info.
  14218. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  14219. if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
  14220. LHSType->isObjCRetainableType())
  14221. return;
  14222. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  14223. if (cast->getCastKind() == CK_ARCConsumeObject) {
  14224. Diag(Loc, diag::warn_arc_retained_property_assign)
  14225. << RHS->getSourceRange();
  14226. return;
  14227. }
  14228. RHS = cast->getSubExpr();
  14229. }
  14230. } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
  14231. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  14232. return;
  14233. }
  14234. }
  14235. }
  14236. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  14237. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  14238. SourceLocation StmtLoc,
  14239. const NullStmt *Body) {
  14240. // Do not warn if the body is a macro that expands to nothing, e.g:
  14241. //
  14242. // #define CALL(x)
  14243. // if (condition)
  14244. // CALL(0);
  14245. if (Body->hasLeadingEmptyMacro())
  14246. return false;
  14247. // Get line numbers of statement and body.
  14248. bool StmtLineInvalid;
  14249. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  14250. &StmtLineInvalid);
  14251. if (StmtLineInvalid)
  14252. return false;
  14253. bool BodyLineInvalid;
  14254. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  14255. &BodyLineInvalid);
  14256. if (BodyLineInvalid)
  14257. return false;
  14258. // Warn if null statement and body are on the same line.
  14259. if (StmtLine != BodyLine)
  14260. return false;
  14261. return true;
  14262. }
  14263. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  14264. const Stmt *Body,
  14265. unsigned DiagID) {
  14266. // Since this is a syntactic check, don't emit diagnostic for template
  14267. // instantiations, this just adds noise.
  14268. if (CurrentInstantiationScope)
  14269. return;
  14270. // The body should be a null statement.
  14271. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  14272. if (!NBody)
  14273. return;
  14274. // Do the usual checks.
  14275. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  14276. return;
  14277. Diag(NBody->getSemiLoc(), DiagID);
  14278. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  14279. }
  14280. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  14281. const Stmt *PossibleBody) {
  14282. assert(!CurrentInstantiationScope); // Ensured by caller
  14283. SourceLocation StmtLoc;
  14284. const Stmt *Body;
  14285. unsigned DiagID;
  14286. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  14287. StmtLoc = FS->getRParenLoc();
  14288. Body = FS->getBody();
  14289. DiagID = diag::warn_empty_for_body;
  14290. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  14291. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  14292. Body = WS->getBody();
  14293. DiagID = diag::warn_empty_while_body;
  14294. } else
  14295. return; // Neither `for' nor `while'.
  14296. // The body should be a null statement.
  14297. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  14298. if (!NBody)
  14299. return;
  14300. // Skip expensive checks if diagnostic is disabled.
  14301. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  14302. return;
  14303. // Do the usual checks.
  14304. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  14305. return;
  14306. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  14307. // noise level low, emit diagnostics only if for/while is followed by a
  14308. // CompoundStmt, e.g.:
  14309. // for (int i = 0; i < n; i++);
  14310. // {
  14311. // a(i);
  14312. // }
  14313. // or if for/while is followed by a statement with more indentation
  14314. // than for/while itself:
  14315. // for (int i = 0; i < n; i++);
  14316. // a(i);
  14317. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  14318. if (!ProbableTypo) {
  14319. bool BodyColInvalid;
  14320. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  14321. PossibleBody->getBeginLoc(), &BodyColInvalid);
  14322. if (BodyColInvalid)
  14323. return;
  14324. bool StmtColInvalid;
  14325. unsigned StmtCol =
  14326. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  14327. if (StmtColInvalid)
  14328. return;
  14329. if (BodyCol > StmtCol)
  14330. ProbableTypo = true;
  14331. }
  14332. if (ProbableTypo) {
  14333. Diag(NBody->getSemiLoc(), DiagID);
  14334. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  14335. }
  14336. }
  14337. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  14338. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  14339. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  14340. SourceLocation OpLoc) {
  14341. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  14342. return;
  14343. if (inTemplateInstantiation())
  14344. return;
  14345. // Strip parens and casts away.
  14346. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  14347. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  14348. // Check for a call expression
  14349. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  14350. if (!CE || CE->getNumArgs() != 1)
  14351. return;
  14352. // Check for a call to std::move
  14353. if (!CE->isCallToStdMove())
  14354. return;
  14355. // Get argument from std::move
  14356. RHSExpr = CE->getArg(0);
  14357. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  14358. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  14359. // Two DeclRefExpr's, check that the decls are the same.
  14360. if (LHSDeclRef && RHSDeclRef) {
  14361. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  14362. return;
  14363. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  14364. RHSDeclRef->getDecl()->getCanonicalDecl())
  14365. return;
  14366. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  14367. << LHSExpr->getSourceRange()
  14368. << RHSExpr->getSourceRange();
  14369. return;
  14370. }
  14371. // Member variables require a different approach to check for self moves.
  14372. // MemberExpr's are the same if every nested MemberExpr refers to the same
  14373. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  14374. // the base Expr's are CXXThisExpr's.
  14375. const Expr *LHSBase = LHSExpr;
  14376. const Expr *RHSBase = RHSExpr;
  14377. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  14378. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  14379. if (!LHSME || !RHSME)
  14380. return;
  14381. while (LHSME && RHSME) {
  14382. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  14383. RHSME->getMemberDecl()->getCanonicalDecl())
  14384. return;
  14385. LHSBase = LHSME->getBase();
  14386. RHSBase = RHSME->getBase();
  14387. LHSME = dyn_cast<MemberExpr>(LHSBase);
  14388. RHSME = dyn_cast<MemberExpr>(RHSBase);
  14389. }
  14390. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  14391. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  14392. if (LHSDeclRef && RHSDeclRef) {
  14393. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  14394. return;
  14395. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  14396. RHSDeclRef->getDecl()->getCanonicalDecl())
  14397. return;
  14398. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  14399. << LHSExpr->getSourceRange()
  14400. << RHSExpr->getSourceRange();
  14401. return;
  14402. }
  14403. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  14404. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  14405. << LHSExpr->getSourceRange()
  14406. << RHSExpr->getSourceRange();
  14407. }
  14408. //===--- Layout compatibility ----------------------------------------------//
  14409. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  14410. /// Check if two enumeration types are layout-compatible.
  14411. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  14412. // C++11 [dcl.enum] p8:
  14413. // Two enumeration types are layout-compatible if they have the same
  14414. // underlying type.
  14415. return ED1->isComplete() && ED2->isComplete() &&
  14416. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  14417. }
  14418. /// Check if two fields are layout-compatible.
  14419. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  14420. FieldDecl *Field2) {
  14421. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  14422. return false;
  14423. if (Field1->isBitField() != Field2->isBitField())
  14424. return false;
  14425. if (Field1->isBitField()) {
  14426. // Make sure that the bit-fields are the same length.
  14427. unsigned Bits1 = Field1->getBitWidthValue(C);
  14428. unsigned Bits2 = Field2->getBitWidthValue(C);
  14429. if (Bits1 != Bits2)
  14430. return false;
  14431. }
  14432. return true;
  14433. }
  14434. /// Check if two standard-layout structs are layout-compatible.
  14435. /// (C++11 [class.mem] p17)
  14436. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  14437. RecordDecl *RD2) {
  14438. // If both records are C++ classes, check that base classes match.
  14439. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  14440. // If one of records is a CXXRecordDecl we are in C++ mode,
  14441. // thus the other one is a CXXRecordDecl, too.
  14442. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  14443. // Check number of base classes.
  14444. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  14445. return false;
  14446. // Check the base classes.
  14447. for (CXXRecordDecl::base_class_const_iterator
  14448. Base1 = D1CXX->bases_begin(),
  14449. BaseEnd1 = D1CXX->bases_end(),
  14450. Base2 = D2CXX->bases_begin();
  14451. Base1 != BaseEnd1;
  14452. ++Base1, ++Base2) {
  14453. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  14454. return false;
  14455. }
  14456. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  14457. // If only RD2 is a C++ class, it should have zero base classes.
  14458. if (D2CXX->getNumBases() > 0)
  14459. return false;
  14460. }
  14461. // Check the fields.
  14462. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  14463. Field2End = RD2->field_end(),
  14464. Field1 = RD1->field_begin(),
  14465. Field1End = RD1->field_end();
  14466. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  14467. if (!isLayoutCompatible(C, *Field1, *Field2))
  14468. return false;
  14469. }
  14470. if (Field1 != Field1End || Field2 != Field2End)
  14471. return false;
  14472. return true;
  14473. }
  14474. /// Check if two standard-layout unions are layout-compatible.
  14475. /// (C++11 [class.mem] p18)
  14476. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  14477. RecordDecl *RD2) {
  14478. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  14479. for (auto *Field2 : RD2->fields())
  14480. UnmatchedFields.insert(Field2);
  14481. for (auto *Field1 : RD1->fields()) {
  14482. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  14483. I = UnmatchedFields.begin(),
  14484. E = UnmatchedFields.end();
  14485. for ( ; I != E; ++I) {
  14486. if (isLayoutCompatible(C, Field1, *I)) {
  14487. bool Result = UnmatchedFields.erase(*I);
  14488. (void) Result;
  14489. assert(Result);
  14490. break;
  14491. }
  14492. }
  14493. if (I == E)
  14494. return false;
  14495. }
  14496. return UnmatchedFields.empty();
  14497. }
  14498. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  14499. RecordDecl *RD2) {
  14500. if (RD1->isUnion() != RD2->isUnion())
  14501. return false;
  14502. if (RD1->isUnion())
  14503. return isLayoutCompatibleUnion(C, RD1, RD2);
  14504. else
  14505. return isLayoutCompatibleStruct(C, RD1, RD2);
  14506. }
  14507. /// Check if two types are layout-compatible in C++11 sense.
  14508. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  14509. if (T1.isNull() || T2.isNull())
  14510. return false;
  14511. // C++11 [basic.types] p11:
  14512. // If two types T1 and T2 are the same type, then T1 and T2 are
  14513. // layout-compatible types.
  14514. if (C.hasSameType(T1, T2))
  14515. return true;
  14516. T1 = T1.getCanonicalType().getUnqualifiedType();
  14517. T2 = T2.getCanonicalType().getUnqualifiedType();
  14518. const Type::TypeClass TC1 = T1->getTypeClass();
  14519. const Type::TypeClass TC2 = T2->getTypeClass();
  14520. if (TC1 != TC2)
  14521. return false;
  14522. if (TC1 == Type::Enum) {
  14523. return isLayoutCompatible(C,
  14524. cast<EnumType>(T1)->getDecl(),
  14525. cast<EnumType>(T2)->getDecl());
  14526. } else if (TC1 == Type::Record) {
  14527. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  14528. return false;
  14529. return isLayoutCompatible(C,
  14530. cast<RecordType>(T1)->getDecl(),
  14531. cast<RecordType>(T2)->getDecl());
  14532. }
  14533. return false;
  14534. }
  14535. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  14536. /// Given a type tag expression find the type tag itself.
  14537. ///
  14538. /// \param TypeExpr Type tag expression, as it appears in user's code.
  14539. ///
  14540. /// \param VD Declaration of an identifier that appears in a type tag.
  14541. ///
  14542. /// \param MagicValue Type tag magic value.
  14543. ///
  14544. /// \param isConstantEvaluated whether the evalaution should be performed in
  14545. /// constant context.
  14546. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  14547. const ValueDecl **VD, uint64_t *MagicValue,
  14548. bool isConstantEvaluated) {
  14549. while(true) {
  14550. if (!TypeExpr)
  14551. return false;
  14552. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  14553. switch (TypeExpr->getStmtClass()) {
  14554. case Stmt::UnaryOperatorClass: {
  14555. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  14556. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  14557. TypeExpr = UO->getSubExpr();
  14558. continue;
  14559. }
  14560. return false;
  14561. }
  14562. case Stmt::DeclRefExprClass: {
  14563. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  14564. *VD = DRE->getDecl();
  14565. return true;
  14566. }
  14567. case Stmt::IntegerLiteralClass: {
  14568. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  14569. llvm::APInt MagicValueAPInt = IL->getValue();
  14570. if (MagicValueAPInt.getActiveBits() <= 64) {
  14571. *MagicValue = MagicValueAPInt.getZExtValue();
  14572. return true;
  14573. } else
  14574. return false;
  14575. }
  14576. case Stmt::BinaryConditionalOperatorClass:
  14577. case Stmt::ConditionalOperatorClass: {
  14578. const AbstractConditionalOperator *ACO =
  14579. cast<AbstractConditionalOperator>(TypeExpr);
  14580. bool Result;
  14581. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
  14582. isConstantEvaluated)) {
  14583. if (Result)
  14584. TypeExpr = ACO->getTrueExpr();
  14585. else
  14586. TypeExpr = ACO->getFalseExpr();
  14587. continue;
  14588. }
  14589. return false;
  14590. }
  14591. case Stmt::BinaryOperatorClass: {
  14592. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  14593. if (BO->getOpcode() == BO_Comma) {
  14594. TypeExpr = BO->getRHS();
  14595. continue;
  14596. }
  14597. return false;
  14598. }
  14599. default:
  14600. return false;
  14601. }
  14602. }
  14603. }
  14604. /// Retrieve the C type corresponding to type tag TypeExpr.
  14605. ///
  14606. /// \param TypeExpr Expression that specifies a type tag.
  14607. ///
  14608. /// \param MagicValues Registered magic values.
  14609. ///
  14610. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  14611. /// kind.
  14612. ///
  14613. /// \param TypeInfo Information about the corresponding C type.
  14614. ///
  14615. /// \param isConstantEvaluated whether the evalaution should be performed in
  14616. /// constant context.
  14617. ///
  14618. /// \returns true if the corresponding C type was found.
  14619. static bool GetMatchingCType(
  14620. const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
  14621. const ASTContext &Ctx,
  14622. const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
  14623. *MagicValues,
  14624. bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
  14625. bool isConstantEvaluated) {
  14626. FoundWrongKind = false;
  14627. // Variable declaration that has type_tag_for_datatype attribute.
  14628. const ValueDecl *VD = nullptr;
  14629. uint64_t MagicValue;
  14630. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
  14631. return false;
  14632. if (VD) {
  14633. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  14634. if (I->getArgumentKind() != ArgumentKind) {
  14635. FoundWrongKind = true;
  14636. return false;
  14637. }
  14638. TypeInfo.Type = I->getMatchingCType();
  14639. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  14640. TypeInfo.MustBeNull = I->getMustBeNull();
  14641. return true;
  14642. }
  14643. return false;
  14644. }
  14645. if (!MagicValues)
  14646. return false;
  14647. llvm::DenseMap<Sema::TypeTagMagicValue,
  14648. Sema::TypeTagData>::const_iterator I =
  14649. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  14650. if (I == MagicValues->end())
  14651. return false;
  14652. TypeInfo = I->second;
  14653. return true;
  14654. }
  14655. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  14656. uint64_t MagicValue, QualType Type,
  14657. bool LayoutCompatible,
  14658. bool MustBeNull) {
  14659. if (!TypeTagForDatatypeMagicValues)
  14660. TypeTagForDatatypeMagicValues.reset(
  14661. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  14662. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  14663. (*TypeTagForDatatypeMagicValues)[Magic] =
  14664. TypeTagData(Type, LayoutCompatible, MustBeNull);
  14665. }
  14666. static bool IsSameCharType(QualType T1, QualType T2) {
  14667. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  14668. if (!BT1)
  14669. return false;
  14670. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  14671. if (!BT2)
  14672. return false;
  14673. BuiltinType::Kind T1Kind = BT1->getKind();
  14674. BuiltinType::Kind T2Kind = BT2->getKind();
  14675. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  14676. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  14677. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  14678. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  14679. }
  14680. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  14681. const ArrayRef<const Expr *> ExprArgs,
  14682. SourceLocation CallSiteLoc) {
  14683. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  14684. bool IsPointerAttr = Attr->getIsPointer();
  14685. // Retrieve the argument representing the 'type_tag'.
  14686. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  14687. if (TypeTagIdxAST >= ExprArgs.size()) {
  14688. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  14689. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  14690. return;
  14691. }
  14692. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  14693. bool FoundWrongKind;
  14694. TypeTagData TypeInfo;
  14695. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  14696. TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
  14697. TypeInfo, isConstantEvaluated())) {
  14698. if (FoundWrongKind)
  14699. Diag(TypeTagExpr->getExprLoc(),
  14700. diag::warn_type_tag_for_datatype_wrong_kind)
  14701. << TypeTagExpr->getSourceRange();
  14702. return;
  14703. }
  14704. // Retrieve the argument representing the 'arg_idx'.
  14705. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  14706. if (ArgumentIdxAST >= ExprArgs.size()) {
  14707. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  14708. << 1 << Attr->getArgumentIdx().getSourceIndex();
  14709. return;
  14710. }
  14711. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  14712. if (IsPointerAttr) {
  14713. // Skip implicit cast of pointer to `void *' (as a function argument).
  14714. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  14715. if (ICE->getType()->isVoidPointerType() &&
  14716. ICE->getCastKind() == CK_BitCast)
  14717. ArgumentExpr = ICE->getSubExpr();
  14718. }
  14719. QualType ArgumentType = ArgumentExpr->getType();
  14720. // Passing a `void*' pointer shouldn't trigger a warning.
  14721. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  14722. return;
  14723. if (TypeInfo.MustBeNull) {
  14724. // Type tag with matching void type requires a null pointer.
  14725. if (!ArgumentExpr->isNullPointerConstant(Context,
  14726. Expr::NPC_ValueDependentIsNotNull)) {
  14727. Diag(ArgumentExpr->getExprLoc(),
  14728. diag::warn_type_safety_null_pointer_required)
  14729. << ArgumentKind->getName()
  14730. << ArgumentExpr->getSourceRange()
  14731. << TypeTagExpr->getSourceRange();
  14732. }
  14733. return;
  14734. }
  14735. QualType RequiredType = TypeInfo.Type;
  14736. if (IsPointerAttr)
  14737. RequiredType = Context.getPointerType(RequiredType);
  14738. bool mismatch = false;
  14739. if (!TypeInfo.LayoutCompatible) {
  14740. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  14741. // C++11 [basic.fundamental] p1:
  14742. // Plain char, signed char, and unsigned char are three distinct types.
  14743. //
  14744. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  14745. // char' depending on the current char signedness mode.
  14746. if (mismatch)
  14747. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  14748. RequiredType->getPointeeType())) ||
  14749. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  14750. mismatch = false;
  14751. } else
  14752. if (IsPointerAttr)
  14753. mismatch = !isLayoutCompatible(Context,
  14754. ArgumentType->getPointeeType(),
  14755. RequiredType->getPointeeType());
  14756. else
  14757. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  14758. if (mismatch)
  14759. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  14760. << ArgumentType << ArgumentKind
  14761. << TypeInfo.LayoutCompatible << RequiredType
  14762. << ArgumentExpr->getSourceRange()
  14763. << TypeTagExpr->getSourceRange();
  14764. }
  14765. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  14766. CharUnits Alignment) {
  14767. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  14768. }
  14769. void Sema::DiagnoseMisalignedMembers() {
  14770. for (MisalignedMember &m : MisalignedMembers) {
  14771. const NamedDecl *ND = m.RD;
  14772. if (ND->getName().empty()) {
  14773. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  14774. ND = TD;
  14775. }
  14776. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  14777. << m.MD << ND << m.E->getSourceRange();
  14778. }
  14779. MisalignedMembers.clear();
  14780. }
  14781. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  14782. E = E->IgnoreParens();
  14783. if (!T->isPointerType() && !T->isIntegerType())
  14784. return;
  14785. if (isa<UnaryOperator>(E) &&
  14786. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  14787. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  14788. if (isa<MemberExpr>(Op)) {
  14789. auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
  14790. if (MA != MisalignedMembers.end() &&
  14791. (T->isIntegerType() ||
  14792. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  14793. Context.getTypeAlignInChars(
  14794. T->getPointeeType()) <= MA->Alignment))))
  14795. MisalignedMembers.erase(MA);
  14796. }
  14797. }
  14798. }
  14799. void Sema::RefersToMemberWithReducedAlignment(
  14800. Expr *E,
  14801. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  14802. Action) {
  14803. const auto *ME = dyn_cast<MemberExpr>(E);
  14804. if (!ME)
  14805. return;
  14806. // No need to check expressions with an __unaligned-qualified type.
  14807. if (E->getType().getQualifiers().hasUnaligned())
  14808. return;
  14809. // For a chain of MemberExpr like "a.b.c.d" this list
  14810. // will keep FieldDecl's like [d, c, b].
  14811. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  14812. const MemberExpr *TopME = nullptr;
  14813. bool AnyIsPacked = false;
  14814. do {
  14815. QualType BaseType = ME->getBase()->getType();
  14816. if (BaseType->isDependentType())
  14817. return;
  14818. if (ME->isArrow())
  14819. BaseType = BaseType->getPointeeType();
  14820. RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
  14821. if (RD->isInvalidDecl())
  14822. return;
  14823. ValueDecl *MD = ME->getMemberDecl();
  14824. auto *FD = dyn_cast<FieldDecl>(MD);
  14825. // We do not care about non-data members.
  14826. if (!FD || FD->isInvalidDecl())
  14827. return;
  14828. AnyIsPacked =
  14829. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  14830. ReverseMemberChain.push_back(FD);
  14831. TopME = ME;
  14832. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  14833. } while (ME);
  14834. assert(TopME && "We did not compute a topmost MemberExpr!");
  14835. // Not the scope of this diagnostic.
  14836. if (!AnyIsPacked)
  14837. return;
  14838. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  14839. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  14840. // TODO: The innermost base of the member expression may be too complicated.
  14841. // For now, just disregard these cases. This is left for future
  14842. // improvement.
  14843. if (!DRE && !isa<CXXThisExpr>(TopBase))
  14844. return;
  14845. // Alignment expected by the whole expression.
  14846. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  14847. // No need to do anything else with this case.
  14848. if (ExpectedAlignment.isOne())
  14849. return;
  14850. // Synthesize offset of the whole access.
  14851. CharUnits Offset;
  14852. for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
  14853. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
  14854. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  14855. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  14856. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  14857. // The base expression of the innermost MemberExpr may give
  14858. // stronger guarantees than the class containing the member.
  14859. if (DRE && !TopME->isArrow()) {
  14860. const ValueDecl *VD = DRE->getDecl();
  14861. if (!VD->getType()->isReferenceType())
  14862. CompleteObjectAlignment =
  14863. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  14864. }
  14865. // Check if the synthesized offset fulfills the alignment.
  14866. if (Offset % ExpectedAlignment != 0 ||
  14867. // It may fulfill the offset it but the effective alignment may still be
  14868. // lower than the expected expression alignment.
  14869. CompleteObjectAlignment < ExpectedAlignment) {
  14870. // If this happens, we want to determine a sensible culprit of this.
  14871. // Intuitively, watching the chain of member expressions from right to
  14872. // left, we start with the required alignment (as required by the field
  14873. // type) but some packed attribute in that chain has reduced the alignment.
  14874. // It may happen that another packed structure increases it again. But if
  14875. // we are here such increase has not been enough. So pointing the first
  14876. // FieldDecl that either is packed or else its RecordDecl is,
  14877. // seems reasonable.
  14878. FieldDecl *FD = nullptr;
  14879. CharUnits Alignment;
  14880. for (FieldDecl *FDI : ReverseMemberChain) {
  14881. if (FDI->hasAttr<PackedAttr>() ||
  14882. FDI->getParent()->hasAttr<PackedAttr>()) {
  14883. FD = FDI;
  14884. Alignment = std::min(
  14885. Context.getTypeAlignInChars(FD->getType()),
  14886. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  14887. break;
  14888. }
  14889. }
  14890. assert(FD && "We did not find a packed FieldDecl!");
  14891. Action(E, FD->getParent(), FD, Alignment);
  14892. }
  14893. }
  14894. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  14895. using namespace std::placeholders;
  14896. RefersToMemberWithReducedAlignment(
  14897. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  14898. _2, _3, _4));
  14899. }
  14900. // Check if \p Ty is a valid type for the elementwise math builtins. If it is
  14901. // not a valid type, emit an error message and return true. Otherwise return
  14902. // false.
  14903. static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
  14904. QualType Ty) {
  14905. if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
  14906. S.Diag(Loc, diag::err_builtin_invalid_arg_type)
  14907. << 1 << /* vector, integer or float ty*/ 0 << Ty;
  14908. return true;
  14909. }
  14910. return false;
  14911. }
  14912. bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
  14913. if (checkArgCount(*this, TheCall, 1))
  14914. return true;
  14915. ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
  14916. if (A.isInvalid())
  14917. return true;
  14918. TheCall->setArg(0, A.get());
  14919. QualType TyA = A.get()->getType();
  14920. if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
  14921. return true;
  14922. TheCall->setType(TyA);
  14923. return false;
  14924. }
  14925. bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
  14926. if (checkArgCount(*this, TheCall, 2))
  14927. return true;
  14928. ExprResult A = TheCall->getArg(0);
  14929. ExprResult B = TheCall->getArg(1);
  14930. // Do standard promotions between the two arguments, returning their common
  14931. // type.
  14932. QualType Res =
  14933. UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
  14934. if (A.isInvalid() || B.isInvalid())
  14935. return true;
  14936. QualType TyA = A.get()->getType();
  14937. QualType TyB = B.get()->getType();
  14938. if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
  14939. return Diag(A.get()->getBeginLoc(),
  14940. diag::err_typecheck_call_different_arg_types)
  14941. << TyA << TyB;
  14942. if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
  14943. return true;
  14944. TheCall->setArg(0, A.get());
  14945. TheCall->setArg(1, B.get());
  14946. TheCall->setType(Res);
  14947. return false;
  14948. }
  14949. bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
  14950. if (checkArgCount(*this, TheCall, 1))
  14951. return true;
  14952. ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
  14953. if (A.isInvalid())
  14954. return true;
  14955. TheCall->setArg(0, A.get());
  14956. return false;
  14957. }
  14958. ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
  14959. ExprResult CallResult) {
  14960. if (checkArgCount(*this, TheCall, 1))
  14961. return ExprError();
  14962. ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
  14963. if (MatrixArg.isInvalid())
  14964. return MatrixArg;
  14965. Expr *Matrix = MatrixArg.get();
  14966. auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
  14967. if (!MType) {
  14968. Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  14969. << 1 << /* matrix ty*/ 1 << Matrix->getType();
  14970. return ExprError();
  14971. }
  14972. // Create returned matrix type by swapping rows and columns of the argument
  14973. // matrix type.
  14974. QualType ResultType = Context.getConstantMatrixType(
  14975. MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
  14976. // Change the return type to the type of the returned matrix.
  14977. TheCall->setType(ResultType);
  14978. // Update call argument to use the possibly converted matrix argument.
  14979. TheCall->setArg(0, Matrix);
  14980. return CallResult;
  14981. }
  14982. // Get and verify the matrix dimensions.
  14983. static llvm::Optional<unsigned>
  14984. getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
  14985. SourceLocation ErrorPos;
  14986. Optional<llvm::APSInt> Value =
  14987. Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
  14988. if (!Value) {
  14989. S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
  14990. << Name;
  14991. return {};
  14992. }
  14993. uint64_t Dim = Value->getZExtValue();
  14994. if (!ConstantMatrixType::isDimensionValid(Dim)) {
  14995. S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
  14996. << Name << ConstantMatrixType::getMaxElementsPerDimension();
  14997. return {};
  14998. }
  14999. return Dim;
  15000. }
  15001. ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
  15002. ExprResult CallResult) {
  15003. if (!getLangOpts().MatrixTypes) {
  15004. Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
  15005. return ExprError();
  15006. }
  15007. if (checkArgCount(*this, TheCall, 4))
  15008. return ExprError();
  15009. unsigned PtrArgIdx = 0;
  15010. Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
  15011. Expr *RowsExpr = TheCall->getArg(1);
  15012. Expr *ColumnsExpr = TheCall->getArg(2);
  15013. Expr *StrideExpr = TheCall->getArg(3);
  15014. bool ArgError = false;
  15015. // Check pointer argument.
  15016. {
  15017. ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
  15018. if (PtrConv.isInvalid())
  15019. return PtrConv;
  15020. PtrExpr = PtrConv.get();
  15021. TheCall->setArg(0, PtrExpr);
  15022. if (PtrExpr->isTypeDependent()) {
  15023. TheCall->setType(Context.DependentTy);
  15024. return TheCall;
  15025. }
  15026. }
  15027. auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
  15028. QualType ElementTy;
  15029. if (!PtrTy) {
  15030. Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  15031. << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
  15032. ArgError = true;
  15033. } else {
  15034. ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
  15035. if (!ConstantMatrixType::isValidElementType(ElementTy)) {
  15036. Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  15037. << PtrArgIdx + 1 << /* pointer to element ty*/ 2
  15038. << PtrExpr->getType();
  15039. ArgError = true;
  15040. }
  15041. }
  15042. // Apply default Lvalue conversions and convert the expression to size_t.
  15043. auto ApplyArgumentConversions = [this](Expr *E) {
  15044. ExprResult Conv = DefaultLvalueConversion(E);
  15045. if (Conv.isInvalid())
  15046. return Conv;
  15047. return tryConvertExprToType(Conv.get(), Context.getSizeType());
  15048. };
  15049. // Apply conversion to row and column expressions.
  15050. ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
  15051. if (!RowsConv.isInvalid()) {
  15052. RowsExpr = RowsConv.get();
  15053. TheCall->setArg(1, RowsExpr);
  15054. } else
  15055. RowsExpr = nullptr;
  15056. ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
  15057. if (!ColumnsConv.isInvalid()) {
  15058. ColumnsExpr = ColumnsConv.get();
  15059. TheCall->setArg(2, ColumnsExpr);
  15060. } else
  15061. ColumnsExpr = nullptr;
  15062. // If any any part of the result matrix type is still pending, just use
  15063. // Context.DependentTy, until all parts are resolved.
  15064. if ((RowsExpr && RowsExpr->isTypeDependent()) ||
  15065. (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
  15066. TheCall->setType(Context.DependentTy);
  15067. return CallResult;
  15068. }
  15069. // Check row and column dimensions.
  15070. llvm::Optional<unsigned> MaybeRows;
  15071. if (RowsExpr)
  15072. MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
  15073. llvm::Optional<unsigned> MaybeColumns;
  15074. if (ColumnsExpr)
  15075. MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
  15076. // Check stride argument.
  15077. ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
  15078. if (StrideConv.isInvalid())
  15079. return ExprError();
  15080. StrideExpr = StrideConv.get();
  15081. TheCall->setArg(3, StrideExpr);
  15082. if (MaybeRows) {
  15083. if (Optional<llvm::APSInt> Value =
  15084. StrideExpr->getIntegerConstantExpr(Context)) {
  15085. uint64_t Stride = Value->getZExtValue();
  15086. if (Stride < *MaybeRows) {
  15087. Diag(StrideExpr->getBeginLoc(),
  15088. diag::err_builtin_matrix_stride_too_small);
  15089. ArgError = true;
  15090. }
  15091. }
  15092. }
  15093. if (ArgError || !MaybeRows || !MaybeColumns)
  15094. return ExprError();
  15095. TheCall->setType(
  15096. Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
  15097. return CallResult;
  15098. }
  15099. ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
  15100. ExprResult CallResult) {
  15101. if (checkArgCount(*this, TheCall, 3))
  15102. return ExprError();
  15103. unsigned PtrArgIdx = 1;
  15104. Expr *MatrixExpr = TheCall->getArg(0);
  15105. Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
  15106. Expr *StrideExpr = TheCall->getArg(2);
  15107. bool ArgError = false;
  15108. {
  15109. ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
  15110. if (MatrixConv.isInvalid())
  15111. return MatrixConv;
  15112. MatrixExpr = MatrixConv.get();
  15113. TheCall->setArg(0, MatrixExpr);
  15114. }
  15115. if (MatrixExpr->isTypeDependent()) {
  15116. TheCall->setType(Context.DependentTy);
  15117. return TheCall;
  15118. }
  15119. auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
  15120. if (!MatrixTy) {
  15121. Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  15122. << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
  15123. ArgError = true;
  15124. }
  15125. {
  15126. ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
  15127. if (PtrConv.isInvalid())
  15128. return PtrConv;
  15129. PtrExpr = PtrConv.get();
  15130. TheCall->setArg(1, PtrExpr);
  15131. if (PtrExpr->isTypeDependent()) {
  15132. TheCall->setType(Context.DependentTy);
  15133. return TheCall;
  15134. }
  15135. }
  15136. // Check pointer argument.
  15137. auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
  15138. if (!PtrTy) {
  15139. Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  15140. << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
  15141. ArgError = true;
  15142. } else {
  15143. QualType ElementTy = PtrTy->getPointeeType();
  15144. if (ElementTy.isConstQualified()) {
  15145. Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
  15146. ArgError = true;
  15147. }
  15148. ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
  15149. if (MatrixTy &&
  15150. !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
  15151. Diag(PtrExpr->getBeginLoc(),
  15152. diag::err_builtin_matrix_pointer_arg_mismatch)
  15153. << ElementTy << MatrixTy->getElementType();
  15154. ArgError = true;
  15155. }
  15156. }
  15157. // Apply default Lvalue conversions and convert the stride expression to
  15158. // size_t.
  15159. {
  15160. ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
  15161. if (StrideConv.isInvalid())
  15162. return StrideConv;
  15163. StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
  15164. if (StrideConv.isInvalid())
  15165. return StrideConv;
  15166. StrideExpr = StrideConv.get();
  15167. TheCall->setArg(2, StrideExpr);
  15168. }
  15169. // Check stride argument.
  15170. if (MatrixTy) {
  15171. if (Optional<llvm::APSInt> Value =
  15172. StrideExpr->getIntegerConstantExpr(Context)) {
  15173. uint64_t Stride = Value->getZExtValue();
  15174. if (Stride < MatrixTy->getNumRows()) {
  15175. Diag(StrideExpr->getBeginLoc(),
  15176. diag::err_builtin_matrix_stride_too_small);
  15177. ArgError = true;
  15178. }
  15179. }
  15180. }
  15181. if (ArgError)
  15182. return ExprError();
  15183. return CallResult;
  15184. }
  15185. /// \brief Enforce the bounds of a TCB
  15186. /// CheckTCBEnforcement - Enforces that every function in a named TCB only
  15187. /// directly calls other functions in the same TCB as marked by the enforce_tcb
  15188. /// and enforce_tcb_leaf attributes.
  15189. void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
  15190. const FunctionDecl *Callee) {
  15191. const FunctionDecl *Caller = getCurFunctionDecl();
  15192. // Calls to builtins are not enforced.
  15193. if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
  15194. Callee->getBuiltinID() != 0)
  15195. return;
  15196. // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
  15197. // all TCBs the callee is a part of.
  15198. llvm::StringSet<> CalleeTCBs;
  15199. for_each(Callee->specific_attrs<EnforceTCBAttr>(),
  15200. [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
  15201. for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
  15202. [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
  15203. // Go through the TCBs the caller is a part of and emit warnings if Caller
  15204. // is in a TCB that the Callee is not.
  15205. for_each(
  15206. Caller->specific_attrs<EnforceTCBAttr>(),
  15207. [&](const auto *A) {
  15208. StringRef CallerTCB = A->getTCBName();
  15209. if (CalleeTCBs.count(CallerTCB) == 0) {
  15210. this->Diag(TheCall->getExprLoc(),
  15211. diag::warn_tcb_enforcement_violation) << Callee
  15212. << CallerTCB;
  15213. }
  15214. });
  15215. }