SemaChecking.cpp 573 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676
  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/Stmt.h"
  33. #include "clang/AST/TemplateBase.h"
  34. #include "clang/AST/Type.h"
  35. #include "clang/AST/TypeLoc.h"
  36. #include "clang/AST/UnresolvedSet.h"
  37. #include "clang/Basic/AddressSpaces.h"
  38. #include "clang/Basic/CharInfo.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/IdentifierTable.h"
  41. #include "clang/Basic/LLVM.h"
  42. #include "clang/Basic/LangOptions.h"
  43. #include "clang/Basic/OpenCLOptions.h"
  44. #include "clang/Basic/OperatorKinds.h"
  45. #include "clang/Basic/PartialDiagnostic.h"
  46. #include "clang/Basic/SourceLocation.h"
  47. #include "clang/Basic/SourceManager.h"
  48. #include "clang/Basic/Specifiers.h"
  49. #include "clang/Basic/SyncScope.h"
  50. #include "clang/Basic/TargetBuiltins.h"
  51. #include "clang/Basic/TargetCXXABI.h"
  52. #include "clang/Basic/TargetInfo.h"
  53. #include "clang/Basic/TypeTraits.h"
  54. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  55. #include "clang/Sema/Initialization.h"
  56. #include "clang/Sema/Lookup.h"
  57. #include "clang/Sema/Ownership.h"
  58. #include "clang/Sema/Scope.h"
  59. #include "clang/Sema/ScopeInfo.h"
  60. #include "clang/Sema/Sema.h"
  61. #include "clang/Sema/SemaInternal.h"
  62. #include "llvm/ADT/APFloat.h"
  63. #include "llvm/ADT/APInt.h"
  64. #include "llvm/ADT/APSInt.h"
  65. #include "llvm/ADT/ArrayRef.h"
  66. #include "llvm/ADT/DenseMap.h"
  67. #include "llvm/ADT/FoldingSet.h"
  68. #include "llvm/ADT/None.h"
  69. #include "llvm/ADT/Optional.h"
  70. #include "llvm/ADT/STLExtras.h"
  71. #include "llvm/ADT/SmallBitVector.h"
  72. #include "llvm/ADT/SmallPtrSet.h"
  73. #include "llvm/ADT/SmallString.h"
  74. #include "llvm/ADT/SmallVector.h"
  75. #include "llvm/ADT/StringRef.h"
  76. #include "llvm/ADT/StringSwitch.h"
  77. #include "llvm/ADT/Triple.h"
  78. #include "llvm/Support/AtomicOrdering.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/Compiler.h"
  81. #include "llvm/Support/ConvertUTF.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/Format.h"
  84. #include "llvm/Support/Locale.h"
  85. #include "llvm/Support/MathExtras.h"
  86. #include "llvm/Support/SaveAndRestore.h"
  87. #include "llvm/Support/raw_ostream.h"
  88. #include <algorithm>
  89. #include <cassert>
  90. #include <cstddef>
  91. #include <cstdint>
  92. #include <functional>
  93. #include <limits>
  94. #include <string>
  95. #include <tuple>
  96. #include <utility>
  97. using namespace clang;
  98. using namespace sema;
  99. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  100. unsigned ByteNo) const {
  101. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  102. Context.getTargetInfo());
  103. }
  104. /// Checks that a call expression's argument count is the desired number.
  105. /// This is useful when doing custom type-checking. Returns true on error.
  106. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  107. unsigned argCount = call->getNumArgs();
  108. if (argCount == desiredArgCount) return false;
  109. if (argCount < desiredArgCount)
  110. return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
  111. << 0 /*function call*/ << desiredArgCount << argCount
  112. << call->getSourceRange();
  113. // Highlight all the excess arguments.
  114. SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
  115. call->getArg(argCount - 1)->getEndLoc());
  116. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  117. << 0 /*function call*/ << desiredArgCount << argCount
  118. << call->getArg(1)->getSourceRange();
  119. }
  120. /// Check that the first argument to __builtin_annotation is an integer
  121. /// and the second argument is a non-wide string literal.
  122. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  123. if (checkArgCount(S, TheCall, 2))
  124. return true;
  125. // First argument should be an integer.
  126. Expr *ValArg = TheCall->getArg(0);
  127. QualType Ty = ValArg->getType();
  128. if (!Ty->isIntegerType()) {
  129. S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
  130. << ValArg->getSourceRange();
  131. return true;
  132. }
  133. // Second argument should be a constant string.
  134. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  135. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  136. if (!Literal || !Literal->isAscii()) {
  137. S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
  138. << StrArg->getSourceRange();
  139. return true;
  140. }
  141. TheCall->setType(Ty);
  142. return false;
  143. }
  144. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  145. // We need at least one argument.
  146. if (TheCall->getNumArgs() < 1) {
  147. S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  148. << 0 << 1 << TheCall->getNumArgs()
  149. << TheCall->getCallee()->getSourceRange();
  150. return true;
  151. }
  152. // All arguments should be wide string literals.
  153. for (Expr *Arg : TheCall->arguments()) {
  154. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  155. if (!Literal || !Literal->isWide()) {
  156. S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
  157. << Arg->getSourceRange();
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  164. /// result type to the corresponding pointer type.
  165. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  166. if (checkArgCount(S, TheCall, 1))
  167. return true;
  168. ExprResult Arg(TheCall->getArg(0));
  169. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
  170. if (ResultType.isNull())
  171. return true;
  172. TheCall->setArg(0, Arg.get());
  173. TheCall->setType(ResultType);
  174. return false;
  175. }
  176. /// Check the number of arguments and set the result type to
  177. /// the argument type.
  178. static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
  179. if (checkArgCount(S, TheCall, 1))
  180. return true;
  181. TheCall->setType(TheCall->getArg(0)->getType());
  182. return false;
  183. }
  184. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  185. if (checkArgCount(S, TheCall, 3))
  186. return true;
  187. // First two arguments should be integers.
  188. for (unsigned I = 0; I < 2; ++I) {
  189. ExprResult Arg = TheCall->getArg(I);
  190. QualType Ty = Arg.get()->getType();
  191. if (!Ty->isIntegerType()) {
  192. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  193. << Ty << Arg.get()->getSourceRange();
  194. return true;
  195. }
  196. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  197. S.getASTContext(), Ty, /*consume*/ false);
  198. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  199. if (Arg.isInvalid())
  200. return true;
  201. TheCall->setArg(I, Arg.get());
  202. }
  203. // Third argument should be a pointer to a non-const integer.
  204. // IRGen correctly handles volatile, restrict, and address spaces, and
  205. // the other qualifiers aren't possible.
  206. {
  207. ExprResult Arg = TheCall->getArg(2);
  208. QualType Ty = Arg.get()->getType();
  209. const auto *PtrTy = Ty->getAs<PointerType>();
  210. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  211. !PtrTy->getPointeeType().isConstQualified())) {
  212. S.Diag(Arg.get()->getBeginLoc(),
  213. diag::err_overflow_builtin_must_be_ptr_int)
  214. << Ty << Arg.get()->getSourceRange();
  215. return true;
  216. }
  217. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  218. S.getASTContext(), Ty, /*consume*/ false);
  219. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  220. if (Arg.isInvalid())
  221. return true;
  222. TheCall->setArg(2, Arg.get());
  223. }
  224. return false;
  225. }
  226. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  227. if (checkArgCount(S, BuiltinCall, 2))
  228. return true;
  229. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  230. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  231. Expr *Call = BuiltinCall->getArg(0);
  232. Expr *Chain = BuiltinCall->getArg(1);
  233. if (Call->getStmtClass() != Stmt::CallExprClass) {
  234. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  235. << Call->getSourceRange();
  236. return true;
  237. }
  238. auto CE = cast<CallExpr>(Call);
  239. if (CE->getCallee()->getType()->isBlockPointerType()) {
  240. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  241. << Call->getSourceRange();
  242. return true;
  243. }
  244. const Decl *TargetDecl = CE->getCalleeDecl();
  245. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  246. if (FD->getBuiltinID()) {
  247. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  248. << Call->getSourceRange();
  249. return true;
  250. }
  251. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  252. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  253. << Call->getSourceRange();
  254. return true;
  255. }
  256. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  257. if (ChainResult.isInvalid())
  258. return true;
  259. if (!ChainResult.get()->getType()->isPointerType()) {
  260. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  261. << Chain->getSourceRange();
  262. return true;
  263. }
  264. QualType ReturnTy = CE->getCallReturnType(S.Context);
  265. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  266. QualType BuiltinTy = S.Context.getFunctionType(
  267. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  268. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  269. Builtin =
  270. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  271. BuiltinCall->setType(CE->getType());
  272. BuiltinCall->setValueKind(CE->getValueKind());
  273. BuiltinCall->setObjectKind(CE->getObjectKind());
  274. BuiltinCall->setCallee(Builtin);
  275. BuiltinCall->setArg(1, ChainResult.get());
  276. return false;
  277. }
  278. /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
  279. /// __builtin_*_chk function, then use the object size argument specified in the
  280. /// source. Otherwise, infer the object size using __builtin_object_size.
  281. void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
  282. CallExpr *TheCall) {
  283. // FIXME: There are some more useful checks we could be doing here:
  284. // - Analyze the format string of sprintf to see how much of buffer is used.
  285. // - Evaluate strlen of strcpy arguments, use as object size.
  286. if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
  287. isConstantEvaluated())
  288. return;
  289. unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
  290. if (!BuiltinID)
  291. return;
  292. unsigned DiagID = 0;
  293. bool IsChkVariant = false;
  294. unsigned SizeIndex, ObjectIndex;
  295. switch (BuiltinID) {
  296. default:
  297. return;
  298. case Builtin::BI__builtin___memcpy_chk:
  299. case Builtin::BI__builtin___memmove_chk:
  300. case Builtin::BI__builtin___memset_chk:
  301. case Builtin::BI__builtin___strlcat_chk:
  302. case Builtin::BI__builtin___strlcpy_chk:
  303. case Builtin::BI__builtin___strncat_chk:
  304. case Builtin::BI__builtin___strncpy_chk:
  305. case Builtin::BI__builtin___stpncpy_chk:
  306. case Builtin::BI__builtin___memccpy_chk: {
  307. DiagID = diag::warn_builtin_chk_overflow;
  308. IsChkVariant = true;
  309. SizeIndex = TheCall->getNumArgs() - 2;
  310. ObjectIndex = TheCall->getNumArgs() - 1;
  311. break;
  312. }
  313. case Builtin::BI__builtin___snprintf_chk:
  314. case Builtin::BI__builtin___vsnprintf_chk: {
  315. DiagID = diag::warn_builtin_chk_overflow;
  316. IsChkVariant = true;
  317. SizeIndex = 1;
  318. ObjectIndex = 3;
  319. break;
  320. }
  321. case Builtin::BIstrncat:
  322. case Builtin::BI__builtin_strncat:
  323. case Builtin::BIstrncpy:
  324. case Builtin::BI__builtin_strncpy:
  325. case Builtin::BIstpncpy:
  326. case Builtin::BI__builtin_stpncpy: {
  327. // Whether these functions overflow depends on the runtime strlen of the
  328. // string, not just the buffer size, so emitting the "always overflow"
  329. // diagnostic isn't quite right. We should still diagnose passing a buffer
  330. // size larger than the destination buffer though; this is a runtime abort
  331. // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
  332. DiagID = diag::warn_fortify_source_size_mismatch;
  333. SizeIndex = TheCall->getNumArgs() - 1;
  334. ObjectIndex = 0;
  335. break;
  336. }
  337. case Builtin::BImemcpy:
  338. case Builtin::BI__builtin_memcpy:
  339. case Builtin::BImemmove:
  340. case Builtin::BI__builtin_memmove:
  341. case Builtin::BImemset:
  342. case Builtin::BI__builtin_memset: {
  343. DiagID = diag::warn_fortify_source_overflow;
  344. SizeIndex = TheCall->getNumArgs() - 1;
  345. ObjectIndex = 0;
  346. break;
  347. }
  348. case Builtin::BIsnprintf:
  349. case Builtin::BI__builtin_snprintf:
  350. case Builtin::BIvsnprintf:
  351. case Builtin::BI__builtin_vsnprintf: {
  352. DiagID = diag::warn_fortify_source_size_mismatch;
  353. SizeIndex = 1;
  354. ObjectIndex = 0;
  355. break;
  356. }
  357. }
  358. llvm::APSInt ObjectSize;
  359. // For __builtin___*_chk, the object size is explicitly provided by the caller
  360. // (usually using __builtin_object_size). Use that value to check this call.
  361. if (IsChkVariant) {
  362. Expr::EvalResult Result;
  363. Expr *SizeArg = TheCall->getArg(ObjectIndex);
  364. if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
  365. return;
  366. ObjectSize = Result.Val.getInt();
  367. // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
  368. } else {
  369. // If the parameter has a pass_object_size attribute, then we should use its
  370. // (potentially) more strict checking mode. Otherwise, conservatively assume
  371. // type 0.
  372. int BOSType = 0;
  373. if (const auto *POS =
  374. FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
  375. BOSType = POS->getType();
  376. Expr *ObjArg = TheCall->getArg(ObjectIndex);
  377. uint64_t Result;
  378. if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
  379. return;
  380. // Get the object size in the target's size_t width.
  381. const TargetInfo &TI = getASTContext().getTargetInfo();
  382. unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
  383. ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
  384. }
  385. // Evaluate the number of bytes of the object that this call will use.
  386. Expr::EvalResult Result;
  387. Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
  388. if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
  389. return;
  390. llvm::APSInt UsedSize = Result.Val.getInt();
  391. if (UsedSize.ule(ObjectSize))
  392. return;
  393. StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
  394. // Skim off the details of whichever builtin was called to produce a better
  395. // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
  396. if (IsChkVariant) {
  397. FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
  398. FunctionName = FunctionName.drop_back(std::strlen("_chk"));
  399. } else if (FunctionName.startswith("__builtin_")) {
  400. FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
  401. }
  402. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  403. PDiag(DiagID)
  404. << FunctionName << ObjectSize.toString(/*Radix=*/10)
  405. << UsedSize.toString(/*Radix=*/10));
  406. }
  407. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  408. Scope::ScopeFlags NeededScopeFlags,
  409. unsigned DiagID) {
  410. // Scopes aren't available during instantiation. Fortunately, builtin
  411. // functions cannot be template args so they cannot be formed through template
  412. // instantiation. Therefore checking once during the parse is sufficient.
  413. if (SemaRef.inTemplateInstantiation())
  414. return false;
  415. Scope *S = SemaRef.getCurScope();
  416. while (S && !S->isSEHExceptScope())
  417. S = S->getParent();
  418. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  419. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  420. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  421. << DRE->getDecl()->getIdentifier();
  422. return true;
  423. }
  424. return false;
  425. }
  426. static inline bool isBlockPointer(Expr *Arg) {
  427. return Arg->getType()->isBlockPointerType();
  428. }
  429. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  430. /// void*, which is a requirement of device side enqueue.
  431. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  432. const BlockPointerType *BPT =
  433. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  434. ArrayRef<QualType> Params =
  435. BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
  436. unsigned ArgCounter = 0;
  437. bool IllegalParams = false;
  438. // Iterate through the block parameters until either one is found that is not
  439. // a local void*, or the block is valid.
  440. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  441. I != E; ++I, ++ArgCounter) {
  442. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  443. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  444. LangAS::opencl_local) {
  445. // Get the location of the error. If a block literal has been passed
  446. // (BlockExpr) then we can point straight to the offending argument,
  447. // else we just point to the variable reference.
  448. SourceLocation ErrorLoc;
  449. if (isa<BlockExpr>(BlockArg)) {
  450. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  451. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  452. } else if (isa<DeclRefExpr>(BlockArg)) {
  453. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  454. }
  455. S.Diag(ErrorLoc,
  456. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  457. IllegalParams = true;
  458. }
  459. }
  460. return IllegalParams;
  461. }
  462. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  463. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  464. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  465. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  466. return true;
  467. }
  468. return false;
  469. }
  470. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  471. if (checkArgCount(S, TheCall, 2))
  472. return true;
  473. if (checkOpenCLSubgroupExt(S, TheCall))
  474. return true;
  475. // First argument is an ndrange_t type.
  476. Expr *NDRangeArg = TheCall->getArg(0);
  477. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  478. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  479. << TheCall->getDirectCallee() << "'ndrange_t'";
  480. return true;
  481. }
  482. Expr *BlockArg = TheCall->getArg(1);
  483. if (!isBlockPointer(BlockArg)) {
  484. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  485. << TheCall->getDirectCallee() << "block";
  486. return true;
  487. }
  488. return checkOpenCLBlockArgs(S, BlockArg);
  489. }
  490. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  491. /// get_kernel_work_group_size
  492. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  493. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  494. if (checkArgCount(S, TheCall, 1))
  495. return true;
  496. Expr *BlockArg = TheCall->getArg(0);
  497. if (!isBlockPointer(BlockArg)) {
  498. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  499. << TheCall->getDirectCallee() << "block";
  500. return true;
  501. }
  502. return checkOpenCLBlockArgs(S, BlockArg);
  503. }
  504. /// Diagnose integer type and any valid implicit conversion to it.
  505. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  506. const QualType &IntType);
  507. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  508. unsigned Start, unsigned End) {
  509. bool IllegalParams = false;
  510. for (unsigned I = Start; I <= End; ++I)
  511. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  512. S.Context.getSizeType());
  513. return IllegalParams;
  514. }
  515. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  516. /// 'local void*' parameter of passed block.
  517. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  518. Expr *BlockArg,
  519. unsigned NumNonVarArgs) {
  520. const BlockPointerType *BPT =
  521. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  522. unsigned NumBlockParams =
  523. BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
  524. unsigned TotalNumArgs = TheCall->getNumArgs();
  525. // For each argument passed to the block, a corresponding uint needs to
  526. // be passed to describe the size of the local memory.
  527. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  528. S.Diag(TheCall->getBeginLoc(),
  529. diag::err_opencl_enqueue_kernel_local_size_args);
  530. return true;
  531. }
  532. // Check that the sizes of the local memory are specified by integers.
  533. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  534. TotalNumArgs - 1);
  535. }
  536. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  537. /// overload formats specified in Table 6.13.17.1.
  538. /// int enqueue_kernel(queue_t queue,
  539. /// kernel_enqueue_flags_t flags,
  540. /// const ndrange_t ndrange,
  541. /// void (^block)(void))
  542. /// int enqueue_kernel(queue_t queue,
  543. /// kernel_enqueue_flags_t flags,
  544. /// const ndrange_t ndrange,
  545. /// uint num_events_in_wait_list,
  546. /// clk_event_t *event_wait_list,
  547. /// clk_event_t *event_ret,
  548. /// void (^block)(void))
  549. /// int enqueue_kernel(queue_t queue,
  550. /// kernel_enqueue_flags_t flags,
  551. /// const ndrange_t ndrange,
  552. /// void (^block)(local void*, ...),
  553. /// uint size0, ...)
  554. /// int enqueue_kernel(queue_t queue,
  555. /// kernel_enqueue_flags_t flags,
  556. /// const ndrange_t ndrange,
  557. /// uint num_events_in_wait_list,
  558. /// clk_event_t *event_wait_list,
  559. /// clk_event_t *event_ret,
  560. /// void (^block)(local void*, ...),
  561. /// uint size0, ...)
  562. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  563. unsigned NumArgs = TheCall->getNumArgs();
  564. if (NumArgs < 4) {
  565. S.Diag(TheCall->getBeginLoc(),
  566. diag::err_typecheck_call_too_few_args_at_least)
  567. << 0 << 4 << NumArgs;
  568. return true;
  569. }
  570. Expr *Arg0 = TheCall->getArg(0);
  571. Expr *Arg1 = TheCall->getArg(1);
  572. Expr *Arg2 = TheCall->getArg(2);
  573. Expr *Arg3 = TheCall->getArg(3);
  574. // First argument always needs to be a queue_t type.
  575. if (!Arg0->getType()->isQueueT()) {
  576. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  577. diag::err_opencl_builtin_expected_type)
  578. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  579. return true;
  580. }
  581. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  582. if (!Arg1->getType()->isIntegerType()) {
  583. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  584. diag::err_opencl_builtin_expected_type)
  585. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  586. return true;
  587. }
  588. // Third argument is always an ndrange_t type.
  589. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  590. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  591. diag::err_opencl_builtin_expected_type)
  592. << TheCall->getDirectCallee() << "'ndrange_t'";
  593. return true;
  594. }
  595. // With four arguments, there is only one form that the function could be
  596. // called in: no events and no variable arguments.
  597. if (NumArgs == 4) {
  598. // check that the last argument is the right block type.
  599. if (!isBlockPointer(Arg3)) {
  600. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  601. << TheCall->getDirectCallee() << "block";
  602. return true;
  603. }
  604. // we have a block type, check the prototype
  605. const BlockPointerType *BPT =
  606. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  607. if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
  608. S.Diag(Arg3->getBeginLoc(),
  609. diag::err_opencl_enqueue_kernel_blocks_no_args);
  610. return true;
  611. }
  612. return false;
  613. }
  614. // we can have block + varargs.
  615. if (isBlockPointer(Arg3))
  616. return (checkOpenCLBlockArgs(S, Arg3) ||
  617. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  618. // last two cases with either exactly 7 args or 7 args and varargs.
  619. if (NumArgs >= 7) {
  620. // check common block argument.
  621. Expr *Arg6 = TheCall->getArg(6);
  622. if (!isBlockPointer(Arg6)) {
  623. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  624. << TheCall->getDirectCallee() << "block";
  625. return true;
  626. }
  627. if (checkOpenCLBlockArgs(S, Arg6))
  628. return true;
  629. // Forth argument has to be any integer type.
  630. if (!Arg3->getType()->isIntegerType()) {
  631. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  632. diag::err_opencl_builtin_expected_type)
  633. << TheCall->getDirectCallee() << "integer";
  634. return true;
  635. }
  636. // check remaining common arguments.
  637. Expr *Arg4 = TheCall->getArg(4);
  638. Expr *Arg5 = TheCall->getArg(5);
  639. // Fifth argument is always passed as a pointer to clk_event_t.
  640. if (!Arg4->isNullPointerConstant(S.Context,
  641. Expr::NPC_ValueDependentIsNotNull) &&
  642. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  643. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  644. diag::err_opencl_builtin_expected_type)
  645. << TheCall->getDirectCallee()
  646. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  647. return true;
  648. }
  649. // Sixth argument is always passed as a pointer to clk_event_t.
  650. if (!Arg5->isNullPointerConstant(S.Context,
  651. Expr::NPC_ValueDependentIsNotNull) &&
  652. !(Arg5->getType()->isPointerType() &&
  653. Arg5->getType()->getPointeeType()->isClkEventT())) {
  654. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  655. diag::err_opencl_builtin_expected_type)
  656. << TheCall->getDirectCallee()
  657. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  658. return true;
  659. }
  660. if (NumArgs == 7)
  661. return false;
  662. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  663. }
  664. // None of the specific case has been detected, give generic error
  665. S.Diag(TheCall->getBeginLoc(),
  666. diag::err_opencl_enqueue_kernel_incorrect_args);
  667. return true;
  668. }
  669. /// Returns OpenCL access qual.
  670. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  671. return D->getAttr<OpenCLAccessAttr>();
  672. }
  673. /// Returns true if pipe element type is different from the pointer.
  674. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  675. const Expr *Arg0 = Call->getArg(0);
  676. // First argument type should always be pipe.
  677. if (!Arg0->getType()->isPipeType()) {
  678. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  679. << Call->getDirectCallee() << Arg0->getSourceRange();
  680. return true;
  681. }
  682. OpenCLAccessAttr *AccessQual =
  683. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  684. // Validates the access qualifier is compatible with the call.
  685. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  686. // read_only and write_only, and assumed to be read_only if no qualifier is
  687. // specified.
  688. switch (Call->getDirectCallee()->getBuiltinID()) {
  689. case Builtin::BIread_pipe:
  690. case Builtin::BIreserve_read_pipe:
  691. case Builtin::BIcommit_read_pipe:
  692. case Builtin::BIwork_group_reserve_read_pipe:
  693. case Builtin::BIsub_group_reserve_read_pipe:
  694. case Builtin::BIwork_group_commit_read_pipe:
  695. case Builtin::BIsub_group_commit_read_pipe:
  696. if (!(!AccessQual || AccessQual->isReadOnly())) {
  697. S.Diag(Arg0->getBeginLoc(),
  698. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  699. << "read_only" << Arg0->getSourceRange();
  700. return true;
  701. }
  702. break;
  703. case Builtin::BIwrite_pipe:
  704. case Builtin::BIreserve_write_pipe:
  705. case Builtin::BIcommit_write_pipe:
  706. case Builtin::BIwork_group_reserve_write_pipe:
  707. case Builtin::BIsub_group_reserve_write_pipe:
  708. case Builtin::BIwork_group_commit_write_pipe:
  709. case Builtin::BIsub_group_commit_write_pipe:
  710. if (!(AccessQual && AccessQual->isWriteOnly())) {
  711. S.Diag(Arg0->getBeginLoc(),
  712. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  713. << "write_only" << Arg0->getSourceRange();
  714. return true;
  715. }
  716. break;
  717. default:
  718. break;
  719. }
  720. return false;
  721. }
  722. /// Returns true if pipe element type is different from the pointer.
  723. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  724. const Expr *Arg0 = Call->getArg(0);
  725. const Expr *ArgIdx = Call->getArg(Idx);
  726. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  727. const QualType EltTy = PipeTy->getElementType();
  728. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  729. // The Idx argument should be a pointer and the type of the pointer and
  730. // the type of pipe element should also be the same.
  731. if (!ArgTy ||
  732. !S.Context.hasSameType(
  733. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  734. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  735. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  736. << ArgIdx->getType() << ArgIdx->getSourceRange();
  737. return true;
  738. }
  739. return false;
  740. }
  741. // Performs semantic analysis for the read/write_pipe call.
  742. // \param S Reference to the semantic analyzer.
  743. // \param Call A pointer to the builtin call.
  744. // \return True if a semantic error has been found, false otherwise.
  745. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  746. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  747. // functions have two forms.
  748. switch (Call->getNumArgs()) {
  749. case 2:
  750. if (checkOpenCLPipeArg(S, Call))
  751. return true;
  752. // The call with 2 arguments should be
  753. // read/write_pipe(pipe T, T*).
  754. // Check packet type T.
  755. if (checkOpenCLPipePacketType(S, Call, 1))
  756. return true;
  757. break;
  758. case 4: {
  759. if (checkOpenCLPipeArg(S, Call))
  760. return true;
  761. // The call with 4 arguments should be
  762. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  763. // Check reserve_id_t.
  764. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  765. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  766. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  767. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  768. return true;
  769. }
  770. // Check the index.
  771. const Expr *Arg2 = Call->getArg(2);
  772. if (!Arg2->getType()->isIntegerType() &&
  773. !Arg2->getType()->isUnsignedIntegerType()) {
  774. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  775. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  776. << Arg2->getType() << Arg2->getSourceRange();
  777. return true;
  778. }
  779. // Check packet type T.
  780. if (checkOpenCLPipePacketType(S, Call, 3))
  781. return true;
  782. } break;
  783. default:
  784. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  785. << Call->getDirectCallee() << Call->getSourceRange();
  786. return true;
  787. }
  788. return false;
  789. }
  790. // Performs a semantic analysis on the {work_group_/sub_group_
  791. // /_}reserve_{read/write}_pipe
  792. // \param S Reference to the semantic analyzer.
  793. // \param Call The call to the builtin function to be analyzed.
  794. // \return True if a semantic error was found, false otherwise.
  795. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  796. if (checkArgCount(S, Call, 2))
  797. return true;
  798. if (checkOpenCLPipeArg(S, Call))
  799. return true;
  800. // Check the reserve size.
  801. if (!Call->getArg(1)->getType()->isIntegerType() &&
  802. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  803. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  804. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  805. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  806. return true;
  807. }
  808. // Since return type of reserve_read/write_pipe built-in function is
  809. // reserve_id_t, which is not defined in the builtin def file , we used int
  810. // as return type and need to override the return type of these functions.
  811. Call->setType(S.Context.OCLReserveIDTy);
  812. return false;
  813. }
  814. // Performs a semantic analysis on {work_group_/sub_group_
  815. // /_}commit_{read/write}_pipe
  816. // \param S Reference to the semantic analyzer.
  817. // \param Call The call to the builtin function to be analyzed.
  818. // \return True if a semantic error was found, false otherwise.
  819. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  820. if (checkArgCount(S, Call, 2))
  821. return true;
  822. if (checkOpenCLPipeArg(S, Call))
  823. return true;
  824. // Check reserve_id_t.
  825. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  826. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  827. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  828. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  829. return true;
  830. }
  831. return false;
  832. }
  833. // Performs a semantic analysis on the call to built-in Pipe
  834. // Query Functions.
  835. // \param S Reference to the semantic analyzer.
  836. // \param Call The call to the builtin function to be analyzed.
  837. // \return True if a semantic error was found, false otherwise.
  838. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  839. if (checkArgCount(S, Call, 1))
  840. return true;
  841. if (!Call->getArg(0)->getType()->isPipeType()) {
  842. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  843. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  844. return true;
  845. }
  846. return false;
  847. }
  848. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  849. // Performs semantic analysis for the to_global/local/private call.
  850. // \param S Reference to the semantic analyzer.
  851. // \param BuiltinID ID of the builtin function.
  852. // \param Call A pointer to the builtin call.
  853. // \return True if a semantic error has been found, false otherwise.
  854. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  855. CallExpr *Call) {
  856. if (Call->getNumArgs() != 1) {
  857. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
  858. << Call->getDirectCallee() << Call->getSourceRange();
  859. return true;
  860. }
  861. auto RT = Call->getArg(0)->getType();
  862. if (!RT->isPointerType() || RT->getPointeeType()
  863. .getAddressSpace() == LangAS::opencl_constant) {
  864. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  865. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  866. return true;
  867. }
  868. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  869. S.Diag(Call->getArg(0)->getBeginLoc(),
  870. diag::warn_opencl_generic_address_space_arg)
  871. << Call->getDirectCallee()->getNameInfo().getAsString()
  872. << Call->getArg(0)->getSourceRange();
  873. }
  874. RT = RT->getPointeeType();
  875. auto Qual = RT.getQualifiers();
  876. switch (BuiltinID) {
  877. case Builtin::BIto_global:
  878. Qual.setAddressSpace(LangAS::opencl_global);
  879. break;
  880. case Builtin::BIto_local:
  881. Qual.setAddressSpace(LangAS::opencl_local);
  882. break;
  883. case Builtin::BIto_private:
  884. Qual.setAddressSpace(LangAS::opencl_private);
  885. break;
  886. default:
  887. llvm_unreachable("Invalid builtin function");
  888. }
  889. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  890. RT.getUnqualifiedType(), Qual)));
  891. return false;
  892. }
  893. static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
  894. if (checkArgCount(S, TheCall, 1))
  895. return ExprError();
  896. // Compute __builtin_launder's parameter type from the argument.
  897. // The parameter type is:
  898. // * The type of the argument if it's not an array or function type,
  899. // Otherwise,
  900. // * The decayed argument type.
  901. QualType ParamTy = [&]() {
  902. QualType ArgTy = TheCall->getArg(0)->getType();
  903. if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
  904. return S.Context.getPointerType(Ty->getElementType());
  905. if (ArgTy->isFunctionType()) {
  906. return S.Context.getPointerType(ArgTy);
  907. }
  908. return ArgTy;
  909. }();
  910. TheCall->setType(ParamTy);
  911. auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
  912. if (!ParamTy->isPointerType())
  913. return 0;
  914. if (ParamTy->isFunctionPointerType())
  915. return 1;
  916. if (ParamTy->isVoidPointerType())
  917. return 2;
  918. return llvm::Optional<unsigned>{};
  919. }();
  920. if (DiagSelect.hasValue()) {
  921. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
  922. << DiagSelect.getValue() << TheCall->getSourceRange();
  923. return ExprError();
  924. }
  925. // We either have an incomplete class type, or we have a class template
  926. // whose instantiation has not been forced. Example:
  927. //
  928. // template <class T> struct Foo { T value; };
  929. // Foo<int> *p = nullptr;
  930. // auto *d = __builtin_launder(p);
  931. if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
  932. diag::err_incomplete_type))
  933. return ExprError();
  934. assert(ParamTy->getPointeeType()->isObjectType() &&
  935. "Unhandled non-object pointer case");
  936. InitializedEntity Entity =
  937. InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
  938. ExprResult Arg =
  939. S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
  940. if (Arg.isInvalid())
  941. return ExprError();
  942. TheCall->setArg(0, Arg.get());
  943. return TheCall;
  944. }
  945. // Emit an error and return true if the current architecture is not in the list
  946. // of supported architectures.
  947. static bool
  948. CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  949. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  950. llvm::Triple::ArchType CurArch =
  951. S.getASTContext().getTargetInfo().getTriple().getArch();
  952. if (llvm::is_contained(SupportedArchs, CurArch))
  953. return false;
  954. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  955. << TheCall->getSourceRange();
  956. return true;
  957. }
  958. ExprResult
  959. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  960. CallExpr *TheCall) {
  961. ExprResult TheCallResult(TheCall);
  962. // Find out if any arguments are required to be integer constant expressions.
  963. unsigned ICEArguments = 0;
  964. ASTContext::GetBuiltinTypeError Error;
  965. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  966. if (Error != ASTContext::GE_None)
  967. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  968. // If any arguments are required to be ICE's, check and diagnose.
  969. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  970. // Skip arguments not required to be ICE's.
  971. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  972. llvm::APSInt Result;
  973. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  974. return true;
  975. ICEArguments &= ~(1 << ArgNo);
  976. }
  977. switch (BuiltinID) {
  978. case Builtin::BI__builtin___CFStringMakeConstantString:
  979. assert(TheCall->getNumArgs() == 1 &&
  980. "Wrong # arguments to builtin CFStringMakeConstantString");
  981. if (CheckObjCString(TheCall->getArg(0)))
  982. return ExprError();
  983. break;
  984. case Builtin::BI__builtin_ms_va_start:
  985. case Builtin::BI__builtin_stdarg_start:
  986. case Builtin::BI__builtin_va_start:
  987. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  988. return ExprError();
  989. break;
  990. case Builtin::BI__va_start: {
  991. switch (Context.getTargetInfo().getTriple().getArch()) {
  992. case llvm::Triple::aarch64:
  993. case llvm::Triple::arm:
  994. case llvm::Triple::thumb:
  995. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  996. return ExprError();
  997. break;
  998. default:
  999. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  1000. return ExprError();
  1001. break;
  1002. }
  1003. break;
  1004. }
  1005. // The acquire, release, and no fence variants are ARM and AArch64 only.
  1006. case Builtin::BI_interlockedbittestandset_acq:
  1007. case Builtin::BI_interlockedbittestandset_rel:
  1008. case Builtin::BI_interlockedbittestandset_nf:
  1009. case Builtin::BI_interlockedbittestandreset_acq:
  1010. case Builtin::BI_interlockedbittestandreset_rel:
  1011. case Builtin::BI_interlockedbittestandreset_nf:
  1012. if (CheckBuiltinTargetSupport(
  1013. *this, BuiltinID, TheCall,
  1014. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  1015. return ExprError();
  1016. break;
  1017. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  1018. case Builtin::BI_bittest64:
  1019. case Builtin::BI_bittestandcomplement64:
  1020. case Builtin::BI_bittestandreset64:
  1021. case Builtin::BI_bittestandset64:
  1022. case Builtin::BI_interlockedbittestandreset64:
  1023. case Builtin::BI_interlockedbittestandset64:
  1024. if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
  1025. {llvm::Triple::x86_64, llvm::Triple::arm,
  1026. llvm::Triple::thumb, llvm::Triple::aarch64}))
  1027. return ExprError();
  1028. break;
  1029. case Builtin::BI__builtin_isgreater:
  1030. case Builtin::BI__builtin_isgreaterequal:
  1031. case Builtin::BI__builtin_isless:
  1032. case Builtin::BI__builtin_islessequal:
  1033. case Builtin::BI__builtin_islessgreater:
  1034. case Builtin::BI__builtin_isunordered:
  1035. if (SemaBuiltinUnorderedCompare(TheCall))
  1036. return ExprError();
  1037. break;
  1038. case Builtin::BI__builtin_fpclassify:
  1039. if (SemaBuiltinFPClassification(TheCall, 6))
  1040. return ExprError();
  1041. break;
  1042. case Builtin::BI__builtin_isfinite:
  1043. case Builtin::BI__builtin_isinf:
  1044. case Builtin::BI__builtin_isinf_sign:
  1045. case Builtin::BI__builtin_isnan:
  1046. case Builtin::BI__builtin_isnormal:
  1047. case Builtin::BI__builtin_signbit:
  1048. case Builtin::BI__builtin_signbitf:
  1049. case Builtin::BI__builtin_signbitl:
  1050. if (SemaBuiltinFPClassification(TheCall, 1))
  1051. return ExprError();
  1052. break;
  1053. case Builtin::BI__builtin_shufflevector:
  1054. return SemaBuiltinShuffleVector(TheCall);
  1055. // TheCall will be freed by the smart pointer here, but that's fine, since
  1056. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  1057. case Builtin::BI__builtin_prefetch:
  1058. if (SemaBuiltinPrefetch(TheCall))
  1059. return ExprError();
  1060. break;
  1061. case Builtin::BI__builtin_alloca_with_align:
  1062. if (SemaBuiltinAllocaWithAlign(TheCall))
  1063. return ExprError();
  1064. LLVM_FALLTHROUGH;
  1065. case Builtin::BI__builtin_alloca:
  1066. Diag(TheCall->getBeginLoc(), diag::warn_alloca)
  1067. << TheCall->getDirectCallee();
  1068. break;
  1069. case Builtin::BI__assume:
  1070. case Builtin::BI__builtin_assume:
  1071. if (SemaBuiltinAssume(TheCall))
  1072. return ExprError();
  1073. break;
  1074. case Builtin::BI__builtin_assume_aligned:
  1075. if (SemaBuiltinAssumeAligned(TheCall))
  1076. return ExprError();
  1077. break;
  1078. case Builtin::BI__builtin_dynamic_object_size:
  1079. case Builtin::BI__builtin_object_size:
  1080. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  1081. return ExprError();
  1082. break;
  1083. case Builtin::BI__builtin_longjmp:
  1084. if (SemaBuiltinLongjmp(TheCall))
  1085. return ExprError();
  1086. break;
  1087. case Builtin::BI__builtin_setjmp:
  1088. if (SemaBuiltinSetjmp(TheCall))
  1089. return ExprError();
  1090. break;
  1091. case Builtin::BI_setjmp:
  1092. case Builtin::BI_setjmpex:
  1093. if (checkArgCount(*this, TheCall, 1))
  1094. return true;
  1095. break;
  1096. case Builtin::BI__builtin_classify_type:
  1097. if (checkArgCount(*this, TheCall, 1)) return true;
  1098. TheCall->setType(Context.IntTy);
  1099. break;
  1100. case Builtin::BI__builtin_constant_p: {
  1101. if (checkArgCount(*this, TheCall, 1)) return true;
  1102. ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  1103. if (Arg.isInvalid()) return true;
  1104. TheCall->setArg(0, Arg.get());
  1105. TheCall->setType(Context.IntTy);
  1106. break;
  1107. }
  1108. case Builtin::BI__builtin_launder:
  1109. return SemaBuiltinLaunder(*this, TheCall);
  1110. case Builtin::BI__sync_fetch_and_add:
  1111. case Builtin::BI__sync_fetch_and_add_1:
  1112. case Builtin::BI__sync_fetch_and_add_2:
  1113. case Builtin::BI__sync_fetch_and_add_4:
  1114. case Builtin::BI__sync_fetch_and_add_8:
  1115. case Builtin::BI__sync_fetch_and_add_16:
  1116. case Builtin::BI__sync_fetch_and_sub:
  1117. case Builtin::BI__sync_fetch_and_sub_1:
  1118. case Builtin::BI__sync_fetch_and_sub_2:
  1119. case Builtin::BI__sync_fetch_and_sub_4:
  1120. case Builtin::BI__sync_fetch_and_sub_8:
  1121. case Builtin::BI__sync_fetch_and_sub_16:
  1122. case Builtin::BI__sync_fetch_and_or:
  1123. case Builtin::BI__sync_fetch_and_or_1:
  1124. case Builtin::BI__sync_fetch_and_or_2:
  1125. case Builtin::BI__sync_fetch_and_or_4:
  1126. case Builtin::BI__sync_fetch_and_or_8:
  1127. case Builtin::BI__sync_fetch_and_or_16:
  1128. case Builtin::BI__sync_fetch_and_and:
  1129. case Builtin::BI__sync_fetch_and_and_1:
  1130. case Builtin::BI__sync_fetch_and_and_2:
  1131. case Builtin::BI__sync_fetch_and_and_4:
  1132. case Builtin::BI__sync_fetch_and_and_8:
  1133. case Builtin::BI__sync_fetch_and_and_16:
  1134. case Builtin::BI__sync_fetch_and_xor:
  1135. case Builtin::BI__sync_fetch_and_xor_1:
  1136. case Builtin::BI__sync_fetch_and_xor_2:
  1137. case Builtin::BI__sync_fetch_and_xor_4:
  1138. case Builtin::BI__sync_fetch_and_xor_8:
  1139. case Builtin::BI__sync_fetch_and_xor_16:
  1140. case Builtin::BI__sync_fetch_and_nand:
  1141. case Builtin::BI__sync_fetch_and_nand_1:
  1142. case Builtin::BI__sync_fetch_and_nand_2:
  1143. case Builtin::BI__sync_fetch_and_nand_4:
  1144. case Builtin::BI__sync_fetch_and_nand_8:
  1145. case Builtin::BI__sync_fetch_and_nand_16:
  1146. case Builtin::BI__sync_add_and_fetch:
  1147. case Builtin::BI__sync_add_and_fetch_1:
  1148. case Builtin::BI__sync_add_and_fetch_2:
  1149. case Builtin::BI__sync_add_and_fetch_4:
  1150. case Builtin::BI__sync_add_and_fetch_8:
  1151. case Builtin::BI__sync_add_and_fetch_16:
  1152. case Builtin::BI__sync_sub_and_fetch:
  1153. case Builtin::BI__sync_sub_and_fetch_1:
  1154. case Builtin::BI__sync_sub_and_fetch_2:
  1155. case Builtin::BI__sync_sub_and_fetch_4:
  1156. case Builtin::BI__sync_sub_and_fetch_8:
  1157. case Builtin::BI__sync_sub_and_fetch_16:
  1158. case Builtin::BI__sync_and_and_fetch:
  1159. case Builtin::BI__sync_and_and_fetch_1:
  1160. case Builtin::BI__sync_and_and_fetch_2:
  1161. case Builtin::BI__sync_and_and_fetch_4:
  1162. case Builtin::BI__sync_and_and_fetch_8:
  1163. case Builtin::BI__sync_and_and_fetch_16:
  1164. case Builtin::BI__sync_or_and_fetch:
  1165. case Builtin::BI__sync_or_and_fetch_1:
  1166. case Builtin::BI__sync_or_and_fetch_2:
  1167. case Builtin::BI__sync_or_and_fetch_4:
  1168. case Builtin::BI__sync_or_and_fetch_8:
  1169. case Builtin::BI__sync_or_and_fetch_16:
  1170. case Builtin::BI__sync_xor_and_fetch:
  1171. case Builtin::BI__sync_xor_and_fetch_1:
  1172. case Builtin::BI__sync_xor_and_fetch_2:
  1173. case Builtin::BI__sync_xor_and_fetch_4:
  1174. case Builtin::BI__sync_xor_and_fetch_8:
  1175. case Builtin::BI__sync_xor_and_fetch_16:
  1176. case Builtin::BI__sync_nand_and_fetch:
  1177. case Builtin::BI__sync_nand_and_fetch_1:
  1178. case Builtin::BI__sync_nand_and_fetch_2:
  1179. case Builtin::BI__sync_nand_and_fetch_4:
  1180. case Builtin::BI__sync_nand_and_fetch_8:
  1181. case Builtin::BI__sync_nand_and_fetch_16:
  1182. case Builtin::BI__sync_val_compare_and_swap:
  1183. case Builtin::BI__sync_val_compare_and_swap_1:
  1184. case Builtin::BI__sync_val_compare_and_swap_2:
  1185. case Builtin::BI__sync_val_compare_and_swap_4:
  1186. case Builtin::BI__sync_val_compare_and_swap_8:
  1187. case Builtin::BI__sync_val_compare_and_swap_16:
  1188. case Builtin::BI__sync_bool_compare_and_swap:
  1189. case Builtin::BI__sync_bool_compare_and_swap_1:
  1190. case Builtin::BI__sync_bool_compare_and_swap_2:
  1191. case Builtin::BI__sync_bool_compare_and_swap_4:
  1192. case Builtin::BI__sync_bool_compare_and_swap_8:
  1193. case Builtin::BI__sync_bool_compare_and_swap_16:
  1194. case Builtin::BI__sync_lock_test_and_set:
  1195. case Builtin::BI__sync_lock_test_and_set_1:
  1196. case Builtin::BI__sync_lock_test_and_set_2:
  1197. case Builtin::BI__sync_lock_test_and_set_4:
  1198. case Builtin::BI__sync_lock_test_and_set_8:
  1199. case Builtin::BI__sync_lock_test_and_set_16:
  1200. case Builtin::BI__sync_lock_release:
  1201. case Builtin::BI__sync_lock_release_1:
  1202. case Builtin::BI__sync_lock_release_2:
  1203. case Builtin::BI__sync_lock_release_4:
  1204. case Builtin::BI__sync_lock_release_8:
  1205. case Builtin::BI__sync_lock_release_16:
  1206. case Builtin::BI__sync_swap:
  1207. case Builtin::BI__sync_swap_1:
  1208. case Builtin::BI__sync_swap_2:
  1209. case Builtin::BI__sync_swap_4:
  1210. case Builtin::BI__sync_swap_8:
  1211. case Builtin::BI__sync_swap_16:
  1212. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1213. case Builtin::BI__sync_synchronize:
  1214. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  1215. << TheCall->getCallee()->getSourceRange();
  1216. break;
  1217. case Builtin::BI__builtin_nontemporal_load:
  1218. case Builtin::BI__builtin_nontemporal_store:
  1219. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1220. #define BUILTIN(ID, TYPE, ATTRS)
  1221. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1222. case Builtin::BI##ID: \
  1223. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1224. #include "clang/Basic/Builtins.def"
  1225. case Builtin::BI__annotation:
  1226. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1227. return ExprError();
  1228. break;
  1229. case Builtin::BI__builtin_annotation:
  1230. if (SemaBuiltinAnnotation(*this, TheCall))
  1231. return ExprError();
  1232. break;
  1233. case Builtin::BI__builtin_addressof:
  1234. if (SemaBuiltinAddressof(*this, TheCall))
  1235. return ExprError();
  1236. break;
  1237. case Builtin::BI__builtin_add_overflow:
  1238. case Builtin::BI__builtin_sub_overflow:
  1239. case Builtin::BI__builtin_mul_overflow:
  1240. if (SemaBuiltinOverflow(*this, TheCall))
  1241. return ExprError();
  1242. break;
  1243. case Builtin::BI__builtin_operator_new:
  1244. case Builtin::BI__builtin_operator_delete: {
  1245. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1246. ExprResult Res =
  1247. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1248. if (Res.isInvalid())
  1249. CorrectDelayedTyposInExpr(TheCallResult.get());
  1250. return Res;
  1251. }
  1252. case Builtin::BI__builtin_dump_struct: {
  1253. // We first want to ensure we are called with 2 arguments
  1254. if (checkArgCount(*this, TheCall, 2))
  1255. return ExprError();
  1256. // Ensure that the first argument is of type 'struct XX *'
  1257. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1258. const QualType PtrArgType = PtrArg->getType();
  1259. if (!PtrArgType->isPointerType() ||
  1260. !PtrArgType->getPointeeType()->isRecordType()) {
  1261. Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1262. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1263. << "structure pointer";
  1264. return ExprError();
  1265. }
  1266. // Ensure that the second argument is of type 'FunctionType'
  1267. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1268. const QualType FnPtrArgType = FnPtrArg->getType();
  1269. if (!FnPtrArgType->isPointerType()) {
  1270. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1271. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1272. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1273. return ExprError();
  1274. }
  1275. const auto *FuncType =
  1276. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1277. if (!FuncType) {
  1278. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1279. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1280. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1281. return ExprError();
  1282. }
  1283. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1284. if (!FT->getNumParams()) {
  1285. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1286. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1287. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1288. return ExprError();
  1289. }
  1290. QualType PT = FT->getParamType(0);
  1291. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1292. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1293. !PT->getPointeeType().isConstQualified()) {
  1294. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1295. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1296. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1297. return ExprError();
  1298. }
  1299. }
  1300. TheCall->setType(Context.IntTy);
  1301. break;
  1302. }
  1303. case Builtin::BI__builtin_preserve_access_index:
  1304. if (SemaBuiltinPreserveAI(*this, TheCall))
  1305. return ExprError();
  1306. break;
  1307. case Builtin::BI__builtin_call_with_static_chain:
  1308. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1309. return ExprError();
  1310. break;
  1311. case Builtin::BI__exception_code:
  1312. case Builtin::BI_exception_code:
  1313. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1314. diag::err_seh___except_block))
  1315. return ExprError();
  1316. break;
  1317. case Builtin::BI__exception_info:
  1318. case Builtin::BI_exception_info:
  1319. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1320. diag::err_seh___except_filter))
  1321. return ExprError();
  1322. break;
  1323. case Builtin::BI__GetExceptionInfo:
  1324. if (checkArgCount(*this, TheCall, 1))
  1325. return ExprError();
  1326. if (CheckCXXThrowOperand(
  1327. TheCall->getBeginLoc(),
  1328. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1329. TheCall))
  1330. return ExprError();
  1331. TheCall->setType(Context.VoidPtrTy);
  1332. break;
  1333. // OpenCL v2.0, s6.13.16 - Pipe functions
  1334. case Builtin::BIread_pipe:
  1335. case Builtin::BIwrite_pipe:
  1336. // Since those two functions are declared with var args, we need a semantic
  1337. // check for the argument.
  1338. if (SemaBuiltinRWPipe(*this, TheCall))
  1339. return ExprError();
  1340. break;
  1341. case Builtin::BIreserve_read_pipe:
  1342. case Builtin::BIreserve_write_pipe:
  1343. case Builtin::BIwork_group_reserve_read_pipe:
  1344. case Builtin::BIwork_group_reserve_write_pipe:
  1345. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1346. return ExprError();
  1347. break;
  1348. case Builtin::BIsub_group_reserve_read_pipe:
  1349. case Builtin::BIsub_group_reserve_write_pipe:
  1350. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1351. SemaBuiltinReserveRWPipe(*this, TheCall))
  1352. return ExprError();
  1353. break;
  1354. case Builtin::BIcommit_read_pipe:
  1355. case Builtin::BIcommit_write_pipe:
  1356. case Builtin::BIwork_group_commit_read_pipe:
  1357. case Builtin::BIwork_group_commit_write_pipe:
  1358. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1359. return ExprError();
  1360. break;
  1361. case Builtin::BIsub_group_commit_read_pipe:
  1362. case Builtin::BIsub_group_commit_write_pipe:
  1363. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1364. SemaBuiltinCommitRWPipe(*this, TheCall))
  1365. return ExprError();
  1366. break;
  1367. case Builtin::BIget_pipe_num_packets:
  1368. case Builtin::BIget_pipe_max_packets:
  1369. if (SemaBuiltinPipePackets(*this, TheCall))
  1370. return ExprError();
  1371. break;
  1372. case Builtin::BIto_global:
  1373. case Builtin::BIto_local:
  1374. case Builtin::BIto_private:
  1375. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1376. return ExprError();
  1377. break;
  1378. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1379. case Builtin::BIenqueue_kernel:
  1380. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1381. return ExprError();
  1382. break;
  1383. case Builtin::BIget_kernel_work_group_size:
  1384. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1385. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1386. return ExprError();
  1387. break;
  1388. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1389. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1390. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1391. return ExprError();
  1392. break;
  1393. case Builtin::BI__builtin_os_log_format:
  1394. case Builtin::BI__builtin_os_log_format_buffer_size:
  1395. if (SemaBuiltinOSLogFormat(TheCall))
  1396. return ExprError();
  1397. break;
  1398. }
  1399. // Since the target specific builtins for each arch overlap, only check those
  1400. // of the arch we are compiling for.
  1401. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1402. switch (Context.getTargetInfo().getTriple().getArch()) {
  1403. case llvm::Triple::arm:
  1404. case llvm::Triple::armeb:
  1405. case llvm::Triple::thumb:
  1406. case llvm::Triple::thumbeb:
  1407. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1408. return ExprError();
  1409. break;
  1410. case llvm::Triple::aarch64:
  1411. case llvm::Triple::aarch64_be:
  1412. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1413. return ExprError();
  1414. break;
  1415. case llvm::Triple::bpfeb:
  1416. case llvm::Triple::bpfel:
  1417. if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
  1418. return ExprError();
  1419. break;
  1420. case llvm::Triple::hexagon:
  1421. if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
  1422. return ExprError();
  1423. break;
  1424. case llvm::Triple::mips:
  1425. case llvm::Triple::mipsel:
  1426. case llvm::Triple::mips64:
  1427. case llvm::Triple::mips64el:
  1428. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1429. return ExprError();
  1430. break;
  1431. case llvm::Triple::systemz:
  1432. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1433. return ExprError();
  1434. break;
  1435. case llvm::Triple::x86:
  1436. case llvm::Triple::x86_64:
  1437. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1438. return ExprError();
  1439. break;
  1440. case llvm::Triple::ppc:
  1441. case llvm::Triple::ppc64:
  1442. case llvm::Triple::ppc64le:
  1443. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1444. return ExprError();
  1445. break;
  1446. default:
  1447. break;
  1448. }
  1449. }
  1450. return TheCallResult;
  1451. }
  1452. // Get the valid immediate range for the specified NEON type code.
  1453. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1454. NeonTypeFlags Type(t);
  1455. int IsQuad = ForceQuad ? true : Type.isQuad();
  1456. switch (Type.getEltType()) {
  1457. case NeonTypeFlags::Int8:
  1458. case NeonTypeFlags::Poly8:
  1459. return shift ? 7 : (8 << IsQuad) - 1;
  1460. case NeonTypeFlags::Int16:
  1461. case NeonTypeFlags::Poly16:
  1462. return shift ? 15 : (4 << IsQuad) - 1;
  1463. case NeonTypeFlags::Int32:
  1464. return shift ? 31 : (2 << IsQuad) - 1;
  1465. case NeonTypeFlags::Int64:
  1466. case NeonTypeFlags::Poly64:
  1467. return shift ? 63 : (1 << IsQuad) - 1;
  1468. case NeonTypeFlags::Poly128:
  1469. return shift ? 127 : (1 << IsQuad) - 1;
  1470. case NeonTypeFlags::Float16:
  1471. assert(!shift && "cannot shift float types!");
  1472. return (4 << IsQuad) - 1;
  1473. case NeonTypeFlags::Float32:
  1474. assert(!shift && "cannot shift float types!");
  1475. return (2 << IsQuad) - 1;
  1476. case NeonTypeFlags::Float64:
  1477. assert(!shift && "cannot shift float types!");
  1478. return (1 << IsQuad) - 1;
  1479. }
  1480. llvm_unreachable("Invalid NeonTypeFlag!");
  1481. }
  1482. /// getNeonEltType - Return the QualType corresponding to the elements of
  1483. /// the vector type specified by the NeonTypeFlags. This is used to check
  1484. /// the pointer arguments for Neon load/store intrinsics.
  1485. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1486. bool IsPolyUnsigned, bool IsInt64Long) {
  1487. switch (Flags.getEltType()) {
  1488. case NeonTypeFlags::Int8:
  1489. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1490. case NeonTypeFlags::Int16:
  1491. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1492. case NeonTypeFlags::Int32:
  1493. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1494. case NeonTypeFlags::Int64:
  1495. if (IsInt64Long)
  1496. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1497. else
  1498. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1499. : Context.LongLongTy;
  1500. case NeonTypeFlags::Poly8:
  1501. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1502. case NeonTypeFlags::Poly16:
  1503. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1504. case NeonTypeFlags::Poly64:
  1505. if (IsInt64Long)
  1506. return Context.UnsignedLongTy;
  1507. else
  1508. return Context.UnsignedLongLongTy;
  1509. case NeonTypeFlags::Poly128:
  1510. break;
  1511. case NeonTypeFlags::Float16:
  1512. return Context.HalfTy;
  1513. case NeonTypeFlags::Float32:
  1514. return Context.FloatTy;
  1515. case NeonTypeFlags::Float64:
  1516. return Context.DoubleTy;
  1517. }
  1518. llvm_unreachable("Invalid NeonTypeFlag!");
  1519. }
  1520. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1521. llvm::APSInt Result;
  1522. uint64_t mask = 0;
  1523. unsigned TV = 0;
  1524. int PtrArgNum = -1;
  1525. bool HasConstPtr = false;
  1526. switch (BuiltinID) {
  1527. #define GET_NEON_OVERLOAD_CHECK
  1528. #include "clang/Basic/arm_neon.inc"
  1529. #include "clang/Basic/arm_fp16.inc"
  1530. #undef GET_NEON_OVERLOAD_CHECK
  1531. }
  1532. // For NEON intrinsics which are overloaded on vector element type, validate
  1533. // the immediate which specifies which variant to emit.
  1534. unsigned ImmArg = TheCall->getNumArgs()-1;
  1535. if (mask) {
  1536. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1537. return true;
  1538. TV = Result.getLimitedValue(64);
  1539. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1540. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  1541. << TheCall->getArg(ImmArg)->getSourceRange();
  1542. }
  1543. if (PtrArgNum >= 0) {
  1544. // Check that pointer arguments have the specified type.
  1545. Expr *Arg = TheCall->getArg(PtrArgNum);
  1546. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1547. Arg = ICE->getSubExpr();
  1548. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1549. QualType RHSTy = RHS.get()->getType();
  1550. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1551. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1552. Arch == llvm::Triple::aarch64_be;
  1553. bool IsInt64Long =
  1554. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1555. QualType EltTy =
  1556. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1557. if (HasConstPtr)
  1558. EltTy = EltTy.withConst();
  1559. QualType LHSTy = Context.getPointerType(EltTy);
  1560. AssignConvertType ConvTy;
  1561. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1562. if (RHS.isInvalid())
  1563. return true;
  1564. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  1565. RHS.get(), AA_Assigning))
  1566. return true;
  1567. }
  1568. // For NEON intrinsics which take an immediate value as part of the
  1569. // instruction, range check them here.
  1570. unsigned i = 0, l = 0, u = 0;
  1571. switch (BuiltinID) {
  1572. default:
  1573. return false;
  1574. #define GET_NEON_IMMEDIATE_CHECK
  1575. #include "clang/Basic/arm_neon.inc"
  1576. #include "clang/Basic/arm_fp16.inc"
  1577. #undef GET_NEON_IMMEDIATE_CHECK
  1578. }
  1579. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1580. }
  1581. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1582. unsigned MaxWidth) {
  1583. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1584. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1585. BuiltinID == ARM::BI__builtin_arm_strex ||
  1586. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1587. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1588. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1589. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1590. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1591. "unexpected ARM builtin");
  1592. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1593. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1594. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1595. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1596. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1597. // Ensure that we have the proper number of arguments.
  1598. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1599. return true;
  1600. // Inspect the pointer argument of the atomic builtin. This should always be
  1601. // a pointer type, whose element is an integral scalar or pointer type.
  1602. // Because it is a pointer type, we don't have to worry about any implicit
  1603. // casts here.
  1604. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1605. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1606. if (PointerArgRes.isInvalid())
  1607. return true;
  1608. PointerArg = PointerArgRes.get();
  1609. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1610. if (!pointerType) {
  1611. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  1612. << PointerArg->getType() << PointerArg->getSourceRange();
  1613. return true;
  1614. }
  1615. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1616. // task is to insert the appropriate casts into the AST. First work out just
  1617. // what the appropriate type is.
  1618. QualType ValType = pointerType->getPointeeType();
  1619. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1620. if (IsLdrex)
  1621. AddrType.addConst();
  1622. // Issue a warning if the cast is dodgy.
  1623. CastKind CastNeeded = CK_NoOp;
  1624. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1625. CastNeeded = CK_BitCast;
  1626. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  1627. << PointerArg->getType() << Context.getPointerType(AddrType)
  1628. << AA_Passing << PointerArg->getSourceRange();
  1629. }
  1630. // Finally, do the cast and replace the argument with the corrected version.
  1631. AddrType = Context.getPointerType(AddrType);
  1632. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1633. if (PointerArgRes.isInvalid())
  1634. return true;
  1635. PointerArg = PointerArgRes.get();
  1636. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1637. // In general, we allow ints, floats and pointers to be loaded and stored.
  1638. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1639. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1640. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1641. << PointerArg->getType() << PointerArg->getSourceRange();
  1642. return true;
  1643. }
  1644. // But ARM doesn't have instructions to deal with 128-bit versions.
  1645. if (Context.getTypeSize(ValType) > MaxWidth) {
  1646. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1647. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  1648. << PointerArg->getType() << PointerArg->getSourceRange();
  1649. return true;
  1650. }
  1651. switch (ValType.getObjCLifetime()) {
  1652. case Qualifiers::OCL_None:
  1653. case Qualifiers::OCL_ExplicitNone:
  1654. // okay
  1655. break;
  1656. case Qualifiers::OCL_Weak:
  1657. case Qualifiers::OCL_Strong:
  1658. case Qualifiers::OCL_Autoreleasing:
  1659. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  1660. << ValType << PointerArg->getSourceRange();
  1661. return true;
  1662. }
  1663. if (IsLdrex) {
  1664. TheCall->setType(ValType);
  1665. return false;
  1666. }
  1667. // Initialize the argument to be stored.
  1668. ExprResult ValArg = TheCall->getArg(0);
  1669. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1670. Context, ValType, /*consume*/ false);
  1671. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1672. if (ValArg.isInvalid())
  1673. return true;
  1674. TheCall->setArg(0, ValArg.get());
  1675. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1676. // but the custom checker bypasses all default analysis.
  1677. TheCall->setType(Context.IntTy);
  1678. return false;
  1679. }
  1680. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1681. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1682. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1683. BuiltinID == ARM::BI__builtin_arm_strex ||
  1684. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1685. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1686. }
  1687. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1688. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1689. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1690. }
  1691. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1692. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1693. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1694. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1695. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1696. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1697. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1698. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1699. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1700. return true;
  1701. // For intrinsics which take an immediate value as part of the instruction,
  1702. // range check them here.
  1703. // FIXME: VFP Intrinsics should error if VFP not present.
  1704. switch (BuiltinID) {
  1705. default: return false;
  1706. case ARM::BI__builtin_arm_ssat:
  1707. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1708. case ARM::BI__builtin_arm_usat:
  1709. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1710. case ARM::BI__builtin_arm_ssat16:
  1711. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1712. case ARM::BI__builtin_arm_usat16:
  1713. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1714. case ARM::BI__builtin_arm_vcvtr_f:
  1715. case ARM::BI__builtin_arm_vcvtr_d:
  1716. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1717. case ARM::BI__builtin_arm_dmb:
  1718. case ARM::BI__builtin_arm_dsb:
  1719. case ARM::BI__builtin_arm_isb:
  1720. case ARM::BI__builtin_arm_dbg:
  1721. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1722. }
  1723. }
  1724. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1725. CallExpr *TheCall) {
  1726. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1727. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1728. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1729. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1730. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1731. }
  1732. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1733. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1734. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1735. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1736. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1737. }
  1738. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1739. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1740. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1741. // Memory Tagging Extensions (MTE) Intrinsics
  1742. if (BuiltinID == AArch64::BI__builtin_arm_irg ||
  1743. BuiltinID == AArch64::BI__builtin_arm_addg ||
  1744. BuiltinID == AArch64::BI__builtin_arm_gmi ||
  1745. BuiltinID == AArch64::BI__builtin_arm_ldg ||
  1746. BuiltinID == AArch64::BI__builtin_arm_stg ||
  1747. BuiltinID == AArch64::BI__builtin_arm_subp) {
  1748. return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
  1749. }
  1750. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1751. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1752. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1753. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1754. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1755. // Only check the valid encoding range. Any constant in this range would be
  1756. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  1757. // an exception for incorrect registers. This matches MSVC behavior.
  1758. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  1759. BuiltinID == AArch64::BI_WriteStatusReg)
  1760. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  1761. if (BuiltinID == AArch64::BI__getReg)
  1762. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  1763. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1764. return true;
  1765. // For intrinsics which take an immediate value as part of the instruction,
  1766. // range check them here.
  1767. unsigned i = 0, l = 0, u = 0;
  1768. switch (BuiltinID) {
  1769. default: return false;
  1770. case AArch64::BI__builtin_arm_dmb:
  1771. case AArch64::BI__builtin_arm_dsb:
  1772. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1773. case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
  1774. }
  1775. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1776. }
  1777. bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
  1778. CallExpr *TheCall) {
  1779. assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
  1780. "unexpected ARM builtin");
  1781. if (checkArgCount(*this, TheCall, 2))
  1782. return true;
  1783. // The first argument needs to be a record field access.
  1784. // If it is an array element access, we delay decision
  1785. // to BPF backend to check whether the access is a
  1786. // field access or not.
  1787. Expr *Arg = TheCall->getArg(0);
  1788. if (Arg->getType()->getAsPlaceholderType() ||
  1789. (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
  1790. !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
  1791. !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
  1792. Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
  1793. << 1 << Arg->getSourceRange();
  1794. return true;
  1795. }
  1796. // The second argument needs to be a constant int
  1797. llvm::APSInt Value;
  1798. if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
  1799. Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
  1800. << 2 << Arg->getSourceRange();
  1801. return true;
  1802. }
  1803. TheCall->setType(Context.UnsignedIntTy);
  1804. return false;
  1805. }
  1806. bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
  1807. struct BuiltinAndString {
  1808. unsigned BuiltinID;
  1809. const char *Str;
  1810. };
  1811. static BuiltinAndString ValidCPU[] = {
  1812. { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
  1813. { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
  1814. { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
  1815. { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
  1816. { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
  1817. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
  1818. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
  1819. { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
  1820. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
  1821. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
  1822. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
  1823. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
  1824. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
  1825. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
  1826. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
  1827. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
  1828. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
  1829. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
  1830. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
  1831. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
  1832. { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
  1833. { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
  1834. { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
  1835. };
  1836. static BuiltinAndString ValidHVX[] = {
  1837. { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
  1838. { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
  1839. { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
  1840. { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
  1841. { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
  1842. { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
  1843. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
  1844. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
  1845. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
  1846. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
  1847. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
  1848. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
  1849. { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
  1850. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
  1851. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
  1852. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
  1853. { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
  1854. { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
  1855. { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
  1856. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
  1857. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
  1858. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
  1859. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
  1860. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
  1861. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
  1862. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
  1863. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
  1864. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
  1865. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
  1866. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
  1867. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
  1868. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
  1869. { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
  1870. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
  1871. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
  1872. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
  1873. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
  1874. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
  1875. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
  1876. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
  1877. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
  1878. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
  1879. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
  1880. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
  1881. { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
  1882. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
  1883. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
  1884. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
  1885. { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
  1886. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
  1887. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
  1888. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
  1889. { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
  1890. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
  1891. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
  1892. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
  1893. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
  1894. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
  1895. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
  1896. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
  1897. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
  1898. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
  1899. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
  1900. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
  1901. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
  1902. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
  1903. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
  1904. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
  1905. { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
  1906. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
  1907. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
  1908. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
  1909. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
  1910. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
  1911. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
  1912. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
  1913. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
  1914. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
  1915. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
  1916. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
  1917. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
  1918. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
  1919. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
  1920. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
  1921. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
  1922. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
  1923. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
  1924. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
  1925. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
  1926. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
  1927. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
  1928. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
  1929. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
  1930. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
  1931. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
  1932. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
  1933. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
  1934. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
  1935. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
  1936. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
  1937. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
  1938. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
  1939. { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
  1940. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
  1941. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
  1942. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
  1943. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
  1944. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
  1945. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
  1946. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
  1947. { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
  1948. { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
  1949. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
  1950. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
  1951. { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
  1952. { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
  1953. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
  1954. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
  1955. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
  1956. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
  1957. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
  1958. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
  1959. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
  1960. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
  1961. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
  1962. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
  1963. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
  1964. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
  1965. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
  1966. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
  1967. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
  1968. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
  1969. { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
  1970. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
  1971. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
  1972. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
  1973. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
  1974. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
  1975. { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
  1976. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
  1977. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
  1978. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
  1979. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
  1980. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
  1981. { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
  1982. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
  1983. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
  1984. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
  1985. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
  1986. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
  1987. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
  1988. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
  1989. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
  1990. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
  1991. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
  1992. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
  1993. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
  1994. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
  1995. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
  1996. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
  1997. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
  1998. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
  1999. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
  2000. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
  2001. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
  2002. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
  2003. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
  2004. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
  2005. { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
  2006. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
  2007. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
  2008. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
  2009. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
  2010. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
  2011. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
  2012. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
  2013. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
  2014. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
  2015. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
  2016. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
  2017. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
  2018. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
  2019. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
  2020. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
  2021. { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
  2022. { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
  2023. { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
  2024. { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
  2025. { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
  2026. { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
  2027. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
  2028. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
  2029. { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
  2030. { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
  2031. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
  2032. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
  2033. { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
  2034. { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
  2035. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
  2036. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
  2037. { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
  2038. { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
  2039. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
  2040. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
  2041. { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
  2042. { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
  2043. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
  2044. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
  2045. { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
  2046. { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
  2047. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
  2048. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
  2049. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
  2050. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
  2051. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
  2052. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
  2053. { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
  2054. { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
  2055. { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
  2056. { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
  2057. { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
  2058. { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
  2059. { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
  2060. { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
  2061. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
  2062. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
  2063. { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
  2064. { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
  2065. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
  2066. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
  2067. { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
  2068. { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
  2069. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
  2070. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
  2071. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
  2072. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
  2073. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
  2074. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
  2075. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
  2076. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
  2077. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
  2078. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
  2079. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
  2080. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
  2081. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
  2082. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
  2083. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
  2084. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
  2085. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
  2086. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
  2087. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
  2088. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
  2089. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
  2090. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
  2091. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
  2092. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2093. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
  2094. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
  2095. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
  2096. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
  2097. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
  2098. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
  2099. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
  2100. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
  2101. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
  2102. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
  2103. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
  2104. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
  2105. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
  2106. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
  2107. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
  2108. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
  2109. { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
  2110. { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
  2111. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
  2112. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
  2113. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
  2114. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
  2115. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
  2116. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
  2117. { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
  2118. { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
  2119. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
  2120. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
  2121. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
  2122. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
  2123. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
  2124. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
  2125. { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
  2126. { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
  2127. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
  2128. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
  2129. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
  2130. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
  2131. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
  2132. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
  2133. { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
  2134. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
  2135. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
  2136. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
  2137. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
  2138. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
  2139. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
  2140. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
  2141. { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
  2142. { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
  2143. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
  2144. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
  2145. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
  2146. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
  2147. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
  2148. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
  2149. { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
  2150. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
  2151. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
  2152. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
  2153. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
  2154. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
  2155. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
  2156. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
  2157. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
  2158. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
  2159. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
  2160. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
  2161. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
  2162. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
  2163. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
  2164. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
  2165. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
  2166. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
  2167. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
  2168. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
  2169. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
  2170. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
  2171. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
  2172. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
  2173. { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
  2174. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
  2175. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
  2176. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
  2177. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
  2178. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
  2179. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
  2180. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
  2181. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
  2182. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
  2183. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
  2184. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
  2185. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
  2186. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
  2187. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
  2188. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
  2189. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
  2190. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
  2191. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
  2192. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
  2193. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
  2194. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
  2195. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
  2196. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
  2197. { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
  2198. { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
  2199. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
  2200. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
  2201. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
  2202. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
  2203. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
  2204. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
  2205. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
  2206. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
  2207. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
  2208. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
  2209. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
  2210. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
  2211. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
  2212. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
  2213. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
  2214. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
  2215. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
  2216. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
  2217. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
  2218. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
  2219. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
  2220. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
  2221. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
  2222. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
  2223. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
  2224. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
  2225. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
  2226. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
  2227. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
  2228. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
  2229. { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
  2230. { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
  2231. { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
  2232. { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
  2233. { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
  2234. { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
  2235. { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
  2236. { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
  2237. { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
  2238. { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
  2239. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
  2240. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
  2241. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
  2242. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
  2243. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
  2244. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
  2245. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
  2246. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
  2247. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
  2248. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
  2249. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
  2250. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
  2251. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
  2252. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
  2253. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
  2254. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
  2255. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
  2256. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
  2257. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
  2258. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
  2259. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
  2260. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
  2261. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
  2262. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
  2263. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
  2264. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
  2265. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
  2266. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
  2267. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
  2268. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
  2269. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
  2270. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
  2271. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
  2272. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
  2273. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
  2274. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
  2275. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
  2276. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
  2277. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
  2278. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
  2279. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
  2280. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
  2281. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
  2282. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
  2283. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
  2284. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
  2285. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
  2286. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2287. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
  2288. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
  2289. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
  2290. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
  2291. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
  2292. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
  2293. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
  2294. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
  2295. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
  2296. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
  2297. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
  2298. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
  2299. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
  2300. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
  2301. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
  2302. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
  2303. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
  2304. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
  2305. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
  2306. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
  2307. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
  2308. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
  2309. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
  2310. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
  2311. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
  2312. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
  2313. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
  2314. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
  2315. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
  2316. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
  2317. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
  2318. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
  2319. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
  2320. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
  2321. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
  2322. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
  2323. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
  2324. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
  2325. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
  2326. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
  2327. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
  2328. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
  2329. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
  2330. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
  2331. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
  2332. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
  2333. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
  2334. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
  2335. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
  2336. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
  2337. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
  2338. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
  2339. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
  2340. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
  2341. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
  2342. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
  2343. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
  2344. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
  2345. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
  2346. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
  2347. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
  2348. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
  2349. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
  2350. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
  2351. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
  2352. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
  2353. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
  2354. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
  2355. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
  2356. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
  2357. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
  2358. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
  2359. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
  2360. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
  2361. { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
  2362. { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
  2363. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
  2364. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
  2365. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
  2366. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
  2367. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
  2368. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
  2369. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
  2370. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
  2371. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
  2372. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
  2373. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
  2374. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
  2375. { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
  2376. { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
  2377. { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
  2378. { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
  2379. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
  2380. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
  2381. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
  2382. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
  2383. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
  2384. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
  2385. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
  2386. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
  2387. { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
  2388. { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
  2389. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
  2390. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
  2391. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
  2392. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
  2393. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
  2394. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
  2395. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
  2396. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
  2397. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
  2398. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
  2399. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
  2400. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
  2401. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
  2402. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
  2403. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
  2404. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
  2405. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
  2406. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
  2407. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
  2408. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
  2409. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
  2410. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
  2411. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
  2412. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
  2413. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
  2414. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
  2415. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
  2416. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
  2417. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
  2418. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
  2419. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
  2420. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
  2421. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
  2422. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
  2423. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
  2424. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
  2425. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
  2426. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
  2427. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
  2428. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
  2429. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
  2430. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
  2431. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
  2432. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
  2433. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
  2434. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
  2435. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
  2436. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
  2437. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
  2438. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
  2439. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
  2440. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
  2441. { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
  2442. { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
  2443. { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
  2444. { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
  2445. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
  2446. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
  2447. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
  2448. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
  2449. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
  2450. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
  2451. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
  2452. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
  2453. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
  2454. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
  2455. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
  2456. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
  2457. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
  2458. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
  2459. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
  2460. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
  2461. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
  2462. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
  2463. { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
  2464. { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
  2465. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
  2466. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
  2467. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
  2468. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
  2469. { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
  2470. { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
  2471. { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
  2472. { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
  2473. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
  2474. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
  2475. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
  2476. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
  2477. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
  2478. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
  2479. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
  2480. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
  2481. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
  2482. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
  2483. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
  2484. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
  2485. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
  2486. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
  2487. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
  2488. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
  2489. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
  2490. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
  2491. { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
  2492. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
  2493. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
  2494. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
  2495. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
  2496. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
  2497. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
  2498. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
  2499. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
  2500. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
  2501. { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
  2502. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
  2503. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
  2504. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
  2505. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
  2506. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
  2507. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
  2508. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
  2509. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
  2510. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
  2511. { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
  2512. { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
  2513. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
  2514. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
  2515. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
  2516. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
  2517. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
  2518. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
  2519. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
  2520. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
  2521. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
  2522. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
  2523. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
  2524. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
  2525. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
  2526. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
  2527. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
  2528. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
  2529. { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
  2530. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
  2531. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
  2532. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
  2533. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
  2534. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
  2535. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
  2536. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
  2537. { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
  2538. { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
  2539. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
  2540. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
  2541. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
  2542. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
  2543. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
  2544. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
  2545. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
  2546. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
  2547. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
  2548. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
  2549. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
  2550. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
  2551. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
  2552. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
  2553. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
  2554. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
  2555. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
  2556. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
  2557. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
  2558. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
  2559. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
  2560. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
  2561. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
  2562. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
  2563. { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
  2564. { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
  2565. { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
  2566. { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
  2567. { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
  2568. { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
  2569. };
  2570. // Sort the tables on first execution so we can binary search them.
  2571. auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
  2572. return LHS.BuiltinID < RHS.BuiltinID;
  2573. };
  2574. static const bool SortOnce =
  2575. (llvm::sort(ValidCPU, SortCmp),
  2576. llvm::sort(ValidHVX, SortCmp), true);
  2577. (void)SortOnce;
  2578. auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
  2579. return BI.BuiltinID < BuiltinID;
  2580. };
  2581. const TargetInfo &TI = Context.getTargetInfo();
  2582. const BuiltinAndString *FC =
  2583. llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
  2584. if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
  2585. const TargetOptions &Opts = TI.getTargetOpts();
  2586. StringRef CPU = Opts.CPU;
  2587. if (!CPU.empty()) {
  2588. assert(CPU.startswith("hexagon") && "Unexpected CPU name");
  2589. CPU.consume_front("hexagon");
  2590. SmallVector<StringRef, 3> CPUs;
  2591. StringRef(FC->Str).split(CPUs, ',');
  2592. if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
  2593. return Diag(TheCall->getBeginLoc(),
  2594. diag::err_hexagon_builtin_unsupported_cpu);
  2595. }
  2596. }
  2597. const BuiltinAndString *FH =
  2598. llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
  2599. if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
  2600. if (!TI.hasFeature("hvx"))
  2601. return Diag(TheCall->getBeginLoc(),
  2602. diag::err_hexagon_builtin_requires_hvx);
  2603. SmallVector<StringRef, 3> HVXs;
  2604. StringRef(FH->Str).split(HVXs, ',');
  2605. bool IsValid = llvm::any_of(HVXs,
  2606. [&TI] (StringRef V) {
  2607. std::string F = "hvx" + V.str();
  2608. return TI.hasFeature(F);
  2609. });
  2610. if (!IsValid)
  2611. return Diag(TheCall->getBeginLoc(),
  2612. diag::err_hexagon_builtin_unsupported_hvx);
  2613. }
  2614. return false;
  2615. }
  2616. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  2617. struct ArgInfo {
  2618. uint8_t OpNum;
  2619. bool IsSigned;
  2620. uint8_t BitWidth;
  2621. uint8_t Align;
  2622. };
  2623. struct BuiltinInfo {
  2624. unsigned BuiltinID;
  2625. ArgInfo Infos[2];
  2626. };
  2627. static BuiltinInfo Infos[] = {
  2628. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  2629. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  2630. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  2631. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
  2632. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  2633. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  2634. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  2635. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  2636. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  2637. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  2638. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  2639. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  2640. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  2641. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  2642. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  2643. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  2644. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  2645. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  2646. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  2647. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  2648. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  2649. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  2650. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  2651. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  2652. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  2653. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  2654. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  2655. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  2656. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  2657. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  2658. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  2659. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  2660. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  2661. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  2662. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  2663. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  2664. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  2665. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  2666. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  2667. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  2668. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  2669. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  2670. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  2671. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  2672. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  2673. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  2674. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  2675. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  2676. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  2677. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  2678. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  2679. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  2680. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  2681. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  2682. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  2683. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  2684. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  2685. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  2686. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  2687. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  2688. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  2689. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  2690. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  2691. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  2692. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  2693. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  2694. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  2695. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  2696. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  2697. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  2698. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  2699. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  2700. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  2701. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  2702. {{ 1, false, 6, 0 }} },
  2703. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  2704. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  2705. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  2706. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  2707. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  2708. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  2709. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  2710. {{ 1, false, 5, 0 }} },
  2711. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  2712. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  2713. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  2714. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  2715. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  2716. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  2717. { 2, false, 5, 0 }} },
  2718. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  2719. { 2, false, 6, 0 }} },
  2720. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  2721. { 3, false, 5, 0 }} },
  2722. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  2723. { 3, false, 6, 0 }} },
  2724. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  2725. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  2726. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  2727. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  2728. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  2729. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  2730. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  2731. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  2732. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  2733. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  2734. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  2735. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  2736. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  2737. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  2738. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  2739. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  2740. {{ 2, false, 4, 0 },
  2741. { 3, false, 5, 0 }} },
  2742. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  2743. {{ 2, false, 4, 0 },
  2744. { 3, false, 5, 0 }} },
  2745. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  2746. {{ 2, false, 4, 0 },
  2747. { 3, false, 5, 0 }} },
  2748. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  2749. {{ 2, false, 4, 0 },
  2750. { 3, false, 5, 0 }} },
  2751. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  2752. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  2753. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  2754. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  2755. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  2756. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  2757. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  2758. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  2759. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  2760. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  2761. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  2762. { 2, false, 5, 0 }} },
  2763. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  2764. { 2, false, 6, 0 }} },
  2765. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  2766. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  2767. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  2768. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  2769. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  2770. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  2771. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  2772. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  2773. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  2774. {{ 1, false, 4, 0 }} },
  2775. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  2776. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  2777. {{ 1, false, 4, 0 }} },
  2778. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  2779. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  2780. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  2781. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  2782. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  2783. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  2784. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  2785. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  2786. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  2787. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  2788. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  2789. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  2790. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  2791. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  2792. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  2793. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  2794. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  2795. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  2796. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  2797. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  2798. {{ 3, false, 1, 0 }} },
  2799. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  2800. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  2801. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  2802. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  2803. {{ 3, false, 1, 0 }} },
  2804. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  2805. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  2806. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  2807. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  2808. {{ 3, false, 1, 0 }} },
  2809. };
  2810. // Use a dynamically initialized static to sort the table exactly once on
  2811. // first run.
  2812. static const bool SortOnce =
  2813. (llvm::sort(Infos,
  2814. [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
  2815. return LHS.BuiltinID < RHS.BuiltinID;
  2816. }),
  2817. true);
  2818. (void)SortOnce;
  2819. const BuiltinInfo *F = llvm::partition_point(
  2820. Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
  2821. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  2822. return false;
  2823. bool Error = false;
  2824. for (const ArgInfo &A : F->Infos) {
  2825. // Ignore empty ArgInfo elements.
  2826. if (A.BitWidth == 0)
  2827. continue;
  2828. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  2829. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  2830. if (!A.Align) {
  2831. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2832. } else {
  2833. unsigned M = 1 << A.Align;
  2834. Min *= M;
  2835. Max *= M;
  2836. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
  2837. SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2838. }
  2839. }
  2840. return Error;
  2841. }
  2842. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2843. CallExpr *TheCall) {
  2844. return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
  2845. CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2846. }
  2847. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  2848. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  2849. // ordering for DSP is unspecified. MSA is ordered by the data format used
  2850. // by the underlying instruction i.e., df/m, df/n and then by size.
  2851. //
  2852. // FIXME: The size tests here should instead be tablegen'd along with the
  2853. // definitions from include/clang/Basic/BuiltinsMips.def.
  2854. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  2855. // be too.
  2856. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2857. unsigned i = 0, l = 0, u = 0, m = 0;
  2858. switch (BuiltinID) {
  2859. default: return false;
  2860. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  2861. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  2862. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  2863. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  2864. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  2865. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  2866. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  2867. // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
  2868. // df/m field.
  2869. // These intrinsics take an unsigned 3 bit immediate.
  2870. case Mips::BI__builtin_msa_bclri_b:
  2871. case Mips::BI__builtin_msa_bnegi_b:
  2872. case Mips::BI__builtin_msa_bseti_b:
  2873. case Mips::BI__builtin_msa_sat_s_b:
  2874. case Mips::BI__builtin_msa_sat_u_b:
  2875. case Mips::BI__builtin_msa_slli_b:
  2876. case Mips::BI__builtin_msa_srai_b:
  2877. case Mips::BI__builtin_msa_srari_b:
  2878. case Mips::BI__builtin_msa_srli_b:
  2879. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  2880. case Mips::BI__builtin_msa_binsli_b:
  2881. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  2882. // These intrinsics take an unsigned 4 bit immediate.
  2883. case Mips::BI__builtin_msa_bclri_h:
  2884. case Mips::BI__builtin_msa_bnegi_h:
  2885. case Mips::BI__builtin_msa_bseti_h:
  2886. case Mips::BI__builtin_msa_sat_s_h:
  2887. case Mips::BI__builtin_msa_sat_u_h:
  2888. case Mips::BI__builtin_msa_slli_h:
  2889. case Mips::BI__builtin_msa_srai_h:
  2890. case Mips::BI__builtin_msa_srari_h:
  2891. case Mips::BI__builtin_msa_srli_h:
  2892. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  2893. case Mips::BI__builtin_msa_binsli_h:
  2894. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  2895. // These intrinsics take an unsigned 5 bit immediate.
  2896. // The first block of intrinsics actually have an unsigned 5 bit field,
  2897. // not a df/n field.
  2898. case Mips::BI__builtin_msa_cfcmsa:
  2899. case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
  2900. case Mips::BI__builtin_msa_clei_u_b:
  2901. case Mips::BI__builtin_msa_clei_u_h:
  2902. case Mips::BI__builtin_msa_clei_u_w:
  2903. case Mips::BI__builtin_msa_clei_u_d:
  2904. case Mips::BI__builtin_msa_clti_u_b:
  2905. case Mips::BI__builtin_msa_clti_u_h:
  2906. case Mips::BI__builtin_msa_clti_u_w:
  2907. case Mips::BI__builtin_msa_clti_u_d:
  2908. case Mips::BI__builtin_msa_maxi_u_b:
  2909. case Mips::BI__builtin_msa_maxi_u_h:
  2910. case Mips::BI__builtin_msa_maxi_u_w:
  2911. case Mips::BI__builtin_msa_maxi_u_d:
  2912. case Mips::BI__builtin_msa_mini_u_b:
  2913. case Mips::BI__builtin_msa_mini_u_h:
  2914. case Mips::BI__builtin_msa_mini_u_w:
  2915. case Mips::BI__builtin_msa_mini_u_d:
  2916. case Mips::BI__builtin_msa_addvi_b:
  2917. case Mips::BI__builtin_msa_addvi_h:
  2918. case Mips::BI__builtin_msa_addvi_w:
  2919. case Mips::BI__builtin_msa_addvi_d:
  2920. case Mips::BI__builtin_msa_bclri_w:
  2921. case Mips::BI__builtin_msa_bnegi_w:
  2922. case Mips::BI__builtin_msa_bseti_w:
  2923. case Mips::BI__builtin_msa_sat_s_w:
  2924. case Mips::BI__builtin_msa_sat_u_w:
  2925. case Mips::BI__builtin_msa_slli_w:
  2926. case Mips::BI__builtin_msa_srai_w:
  2927. case Mips::BI__builtin_msa_srari_w:
  2928. case Mips::BI__builtin_msa_srli_w:
  2929. case Mips::BI__builtin_msa_srlri_w:
  2930. case Mips::BI__builtin_msa_subvi_b:
  2931. case Mips::BI__builtin_msa_subvi_h:
  2932. case Mips::BI__builtin_msa_subvi_w:
  2933. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2934. case Mips::BI__builtin_msa_binsli_w:
  2935. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2936. // These intrinsics take an unsigned 6 bit immediate.
  2937. case Mips::BI__builtin_msa_bclri_d:
  2938. case Mips::BI__builtin_msa_bnegi_d:
  2939. case Mips::BI__builtin_msa_bseti_d:
  2940. case Mips::BI__builtin_msa_sat_s_d:
  2941. case Mips::BI__builtin_msa_sat_u_d:
  2942. case Mips::BI__builtin_msa_slli_d:
  2943. case Mips::BI__builtin_msa_srai_d:
  2944. case Mips::BI__builtin_msa_srari_d:
  2945. case Mips::BI__builtin_msa_srli_d:
  2946. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2947. case Mips::BI__builtin_msa_binsli_d:
  2948. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2949. // These intrinsics take a signed 5 bit immediate.
  2950. case Mips::BI__builtin_msa_ceqi_b:
  2951. case Mips::BI__builtin_msa_ceqi_h:
  2952. case Mips::BI__builtin_msa_ceqi_w:
  2953. case Mips::BI__builtin_msa_ceqi_d:
  2954. case Mips::BI__builtin_msa_clti_s_b:
  2955. case Mips::BI__builtin_msa_clti_s_h:
  2956. case Mips::BI__builtin_msa_clti_s_w:
  2957. case Mips::BI__builtin_msa_clti_s_d:
  2958. case Mips::BI__builtin_msa_clei_s_b:
  2959. case Mips::BI__builtin_msa_clei_s_h:
  2960. case Mips::BI__builtin_msa_clei_s_w:
  2961. case Mips::BI__builtin_msa_clei_s_d:
  2962. case Mips::BI__builtin_msa_maxi_s_b:
  2963. case Mips::BI__builtin_msa_maxi_s_h:
  2964. case Mips::BI__builtin_msa_maxi_s_w:
  2965. case Mips::BI__builtin_msa_maxi_s_d:
  2966. case Mips::BI__builtin_msa_mini_s_b:
  2967. case Mips::BI__builtin_msa_mini_s_h:
  2968. case Mips::BI__builtin_msa_mini_s_w:
  2969. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2970. // These intrinsics take an unsigned 8 bit immediate.
  2971. case Mips::BI__builtin_msa_andi_b:
  2972. case Mips::BI__builtin_msa_nori_b:
  2973. case Mips::BI__builtin_msa_ori_b:
  2974. case Mips::BI__builtin_msa_shf_b:
  2975. case Mips::BI__builtin_msa_shf_h:
  2976. case Mips::BI__builtin_msa_shf_w:
  2977. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2978. case Mips::BI__builtin_msa_bseli_b:
  2979. case Mips::BI__builtin_msa_bmnzi_b:
  2980. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2981. // df/n format
  2982. // These intrinsics take an unsigned 4 bit immediate.
  2983. case Mips::BI__builtin_msa_copy_s_b:
  2984. case Mips::BI__builtin_msa_copy_u_b:
  2985. case Mips::BI__builtin_msa_insve_b:
  2986. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2987. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2988. // These intrinsics take an unsigned 3 bit immediate.
  2989. case Mips::BI__builtin_msa_copy_s_h:
  2990. case Mips::BI__builtin_msa_copy_u_h:
  2991. case Mips::BI__builtin_msa_insve_h:
  2992. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2993. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2994. // These intrinsics take an unsigned 2 bit immediate.
  2995. case Mips::BI__builtin_msa_copy_s_w:
  2996. case Mips::BI__builtin_msa_copy_u_w:
  2997. case Mips::BI__builtin_msa_insve_w:
  2998. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2999. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  3000. // These intrinsics take an unsigned 1 bit immediate.
  3001. case Mips::BI__builtin_msa_copy_s_d:
  3002. case Mips::BI__builtin_msa_copy_u_d:
  3003. case Mips::BI__builtin_msa_insve_d:
  3004. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  3005. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  3006. // Memory offsets and immediate loads.
  3007. // These intrinsics take a signed 10 bit immediate.
  3008. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  3009. case Mips::BI__builtin_msa_ldi_h:
  3010. case Mips::BI__builtin_msa_ldi_w:
  3011. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  3012. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  3013. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  3014. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  3015. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  3016. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  3017. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  3018. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  3019. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  3020. }
  3021. if (!m)
  3022. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3023. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  3024. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  3025. }
  3026. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3027. unsigned i = 0, l = 0, u = 0;
  3028. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  3029. BuiltinID == PPC::BI__builtin_divdeu ||
  3030. BuiltinID == PPC::BI__builtin_bpermd;
  3031. bool IsTarget64Bit = Context.getTargetInfo()
  3032. .getTypeWidth(Context
  3033. .getTargetInfo()
  3034. .getIntPtrType()) == 64;
  3035. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  3036. BuiltinID == PPC::BI__builtin_divweu ||
  3037. BuiltinID == PPC::BI__builtin_divde ||
  3038. BuiltinID == PPC::BI__builtin_divdeu;
  3039. if (Is64BitBltin && !IsTarget64Bit)
  3040. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  3041. << TheCall->getSourceRange();
  3042. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  3043. (BuiltinID == PPC::BI__builtin_bpermd &&
  3044. !Context.getTargetInfo().hasFeature("bpermd")))
  3045. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  3046. << TheCall->getSourceRange();
  3047. auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
  3048. if (!Context.getTargetInfo().hasFeature("vsx"))
  3049. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  3050. << TheCall->getSourceRange();
  3051. return false;
  3052. };
  3053. switch (BuiltinID) {
  3054. default: return false;
  3055. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  3056. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  3057. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  3058. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3059. case PPC::BI__builtin_altivec_dss:
  3060. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
  3061. case PPC::BI__builtin_tbegin:
  3062. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  3063. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  3064. case PPC::BI__builtin_tabortwc:
  3065. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  3066. case PPC::BI__builtin_tabortwci:
  3067. case PPC::BI__builtin_tabortdci:
  3068. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3069. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  3070. case PPC::BI__builtin_altivec_dst:
  3071. case PPC::BI__builtin_altivec_dstt:
  3072. case PPC::BI__builtin_altivec_dstst:
  3073. case PPC::BI__builtin_altivec_dststt:
  3074. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
  3075. case PPC::BI__builtin_vsx_xxpermdi:
  3076. case PPC::BI__builtin_vsx_xxsldwi:
  3077. return SemaBuiltinVSX(TheCall);
  3078. case PPC::BI__builtin_unpack_vector_int128:
  3079. return SemaVSXCheck(TheCall) ||
  3080. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3081. case PPC::BI__builtin_pack_vector_int128:
  3082. return SemaVSXCheck(TheCall);
  3083. }
  3084. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3085. }
  3086. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  3087. CallExpr *TheCall) {
  3088. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  3089. Expr *Arg = TheCall->getArg(0);
  3090. llvm::APSInt AbortCode(32);
  3091. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  3092. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  3093. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  3094. << Arg->getSourceRange();
  3095. }
  3096. // For intrinsics which take an immediate value as part of the instruction,
  3097. // range check them here.
  3098. unsigned i = 0, l = 0, u = 0;
  3099. switch (BuiltinID) {
  3100. default: return false;
  3101. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  3102. case SystemZ::BI__builtin_s390_verimb:
  3103. case SystemZ::BI__builtin_s390_verimh:
  3104. case SystemZ::BI__builtin_s390_verimf:
  3105. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  3106. case SystemZ::BI__builtin_s390_vfaeb:
  3107. case SystemZ::BI__builtin_s390_vfaeh:
  3108. case SystemZ::BI__builtin_s390_vfaef:
  3109. case SystemZ::BI__builtin_s390_vfaebs:
  3110. case SystemZ::BI__builtin_s390_vfaehs:
  3111. case SystemZ::BI__builtin_s390_vfaefs:
  3112. case SystemZ::BI__builtin_s390_vfaezb:
  3113. case SystemZ::BI__builtin_s390_vfaezh:
  3114. case SystemZ::BI__builtin_s390_vfaezf:
  3115. case SystemZ::BI__builtin_s390_vfaezbs:
  3116. case SystemZ::BI__builtin_s390_vfaezhs:
  3117. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  3118. case SystemZ::BI__builtin_s390_vfisb:
  3119. case SystemZ::BI__builtin_s390_vfidb:
  3120. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  3121. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3122. case SystemZ::BI__builtin_s390_vftcisb:
  3123. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  3124. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  3125. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  3126. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  3127. case SystemZ::BI__builtin_s390_vstrcb:
  3128. case SystemZ::BI__builtin_s390_vstrch:
  3129. case SystemZ::BI__builtin_s390_vstrcf:
  3130. case SystemZ::BI__builtin_s390_vstrczb:
  3131. case SystemZ::BI__builtin_s390_vstrczh:
  3132. case SystemZ::BI__builtin_s390_vstrczf:
  3133. case SystemZ::BI__builtin_s390_vstrcbs:
  3134. case SystemZ::BI__builtin_s390_vstrchs:
  3135. case SystemZ::BI__builtin_s390_vstrcfs:
  3136. case SystemZ::BI__builtin_s390_vstrczbs:
  3137. case SystemZ::BI__builtin_s390_vstrczhs:
  3138. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  3139. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  3140. case SystemZ::BI__builtin_s390_vfminsb:
  3141. case SystemZ::BI__builtin_s390_vfmaxsb:
  3142. case SystemZ::BI__builtin_s390_vfmindb:
  3143. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  3144. case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
  3145. case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
  3146. }
  3147. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3148. }
  3149. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  3150. /// This checks that the target supports __builtin_cpu_supports and
  3151. /// that the string argument is constant and valid.
  3152. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  3153. Expr *Arg = TheCall->getArg(0);
  3154. // Check if the argument is a string literal.
  3155. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3156. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3157. << Arg->getSourceRange();
  3158. // Check the contents of the string.
  3159. StringRef Feature =
  3160. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3161. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  3162. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  3163. << Arg->getSourceRange();
  3164. return false;
  3165. }
  3166. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  3167. /// This checks that the target supports __builtin_cpu_is and
  3168. /// that the string argument is constant and valid.
  3169. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  3170. Expr *Arg = TheCall->getArg(0);
  3171. // Check if the argument is a string literal.
  3172. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3173. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3174. << Arg->getSourceRange();
  3175. // Check the contents of the string.
  3176. StringRef Feature =
  3177. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3178. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  3179. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  3180. << Arg->getSourceRange();
  3181. return false;
  3182. }
  3183. // Check if the rounding mode is legal.
  3184. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  3185. // Indicates if this instruction has rounding control or just SAE.
  3186. bool HasRC = false;
  3187. unsigned ArgNum = 0;
  3188. switch (BuiltinID) {
  3189. default:
  3190. return false;
  3191. case X86::BI__builtin_ia32_vcvttsd2si32:
  3192. case X86::BI__builtin_ia32_vcvttsd2si64:
  3193. case X86::BI__builtin_ia32_vcvttsd2usi32:
  3194. case X86::BI__builtin_ia32_vcvttsd2usi64:
  3195. case X86::BI__builtin_ia32_vcvttss2si32:
  3196. case X86::BI__builtin_ia32_vcvttss2si64:
  3197. case X86::BI__builtin_ia32_vcvttss2usi32:
  3198. case X86::BI__builtin_ia32_vcvttss2usi64:
  3199. ArgNum = 1;
  3200. break;
  3201. case X86::BI__builtin_ia32_maxpd512:
  3202. case X86::BI__builtin_ia32_maxps512:
  3203. case X86::BI__builtin_ia32_minpd512:
  3204. case X86::BI__builtin_ia32_minps512:
  3205. ArgNum = 2;
  3206. break;
  3207. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3208. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3209. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3210. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3211. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3212. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3213. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3214. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3215. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3216. case X86::BI__builtin_ia32_exp2pd_mask:
  3217. case X86::BI__builtin_ia32_exp2ps_mask:
  3218. case X86::BI__builtin_ia32_getexppd512_mask:
  3219. case X86::BI__builtin_ia32_getexpps512_mask:
  3220. case X86::BI__builtin_ia32_rcp28pd_mask:
  3221. case X86::BI__builtin_ia32_rcp28ps_mask:
  3222. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3223. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3224. case X86::BI__builtin_ia32_vcomisd:
  3225. case X86::BI__builtin_ia32_vcomiss:
  3226. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3227. ArgNum = 3;
  3228. break;
  3229. case X86::BI__builtin_ia32_cmppd512_mask:
  3230. case X86::BI__builtin_ia32_cmpps512_mask:
  3231. case X86::BI__builtin_ia32_cmpsd_mask:
  3232. case X86::BI__builtin_ia32_cmpss_mask:
  3233. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3234. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3235. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3236. case X86::BI__builtin_ia32_getmantpd512_mask:
  3237. case X86::BI__builtin_ia32_getmantps512_mask:
  3238. case X86::BI__builtin_ia32_maxsd_round_mask:
  3239. case X86::BI__builtin_ia32_maxss_round_mask:
  3240. case X86::BI__builtin_ia32_minsd_round_mask:
  3241. case X86::BI__builtin_ia32_minss_round_mask:
  3242. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3243. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3244. case X86::BI__builtin_ia32_reducepd512_mask:
  3245. case X86::BI__builtin_ia32_reduceps512_mask:
  3246. case X86::BI__builtin_ia32_rndscalepd_mask:
  3247. case X86::BI__builtin_ia32_rndscaleps_mask:
  3248. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3249. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3250. ArgNum = 4;
  3251. break;
  3252. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3253. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3254. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3255. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3256. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3257. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3258. case X86::BI__builtin_ia32_fixupimmss_mask:
  3259. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3260. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3261. case X86::BI__builtin_ia32_getmantss_round_mask:
  3262. case X86::BI__builtin_ia32_rangepd512_mask:
  3263. case X86::BI__builtin_ia32_rangeps512_mask:
  3264. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3265. case X86::BI__builtin_ia32_rangess128_round_mask:
  3266. case X86::BI__builtin_ia32_reducesd_mask:
  3267. case X86::BI__builtin_ia32_reducess_mask:
  3268. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3269. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3270. ArgNum = 5;
  3271. break;
  3272. case X86::BI__builtin_ia32_vcvtsd2si64:
  3273. case X86::BI__builtin_ia32_vcvtsd2si32:
  3274. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3275. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3276. case X86::BI__builtin_ia32_vcvtss2si32:
  3277. case X86::BI__builtin_ia32_vcvtss2si64:
  3278. case X86::BI__builtin_ia32_vcvtss2usi32:
  3279. case X86::BI__builtin_ia32_vcvtss2usi64:
  3280. case X86::BI__builtin_ia32_sqrtpd512:
  3281. case X86::BI__builtin_ia32_sqrtps512:
  3282. ArgNum = 1;
  3283. HasRC = true;
  3284. break;
  3285. case X86::BI__builtin_ia32_addpd512:
  3286. case X86::BI__builtin_ia32_addps512:
  3287. case X86::BI__builtin_ia32_divpd512:
  3288. case X86::BI__builtin_ia32_divps512:
  3289. case X86::BI__builtin_ia32_mulpd512:
  3290. case X86::BI__builtin_ia32_mulps512:
  3291. case X86::BI__builtin_ia32_subpd512:
  3292. case X86::BI__builtin_ia32_subps512:
  3293. case X86::BI__builtin_ia32_cvtsi2sd64:
  3294. case X86::BI__builtin_ia32_cvtsi2ss32:
  3295. case X86::BI__builtin_ia32_cvtsi2ss64:
  3296. case X86::BI__builtin_ia32_cvtusi2sd64:
  3297. case X86::BI__builtin_ia32_cvtusi2ss32:
  3298. case X86::BI__builtin_ia32_cvtusi2ss64:
  3299. ArgNum = 2;
  3300. HasRC = true;
  3301. break;
  3302. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3303. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3304. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3305. case X86::BI__builtin_ia32_cvtpd2dq512_mask:
  3306. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3307. case X86::BI__builtin_ia32_cvtpd2udq512_mask:
  3308. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3309. case X86::BI__builtin_ia32_cvtps2dq512_mask:
  3310. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3311. case X86::BI__builtin_ia32_cvtps2udq512_mask:
  3312. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3313. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3314. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3315. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3316. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3317. ArgNum = 3;
  3318. HasRC = true;
  3319. break;
  3320. case X86::BI__builtin_ia32_addss_round_mask:
  3321. case X86::BI__builtin_ia32_addsd_round_mask:
  3322. case X86::BI__builtin_ia32_divss_round_mask:
  3323. case X86::BI__builtin_ia32_divsd_round_mask:
  3324. case X86::BI__builtin_ia32_mulss_round_mask:
  3325. case X86::BI__builtin_ia32_mulsd_round_mask:
  3326. case X86::BI__builtin_ia32_subss_round_mask:
  3327. case X86::BI__builtin_ia32_subsd_round_mask:
  3328. case X86::BI__builtin_ia32_scalefpd512_mask:
  3329. case X86::BI__builtin_ia32_scalefps512_mask:
  3330. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3331. case X86::BI__builtin_ia32_scalefss_round_mask:
  3332. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3333. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3334. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3335. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3336. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3337. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3338. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3339. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3340. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3341. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3342. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3343. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3344. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3345. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3346. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3347. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3348. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3349. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3350. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3351. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3352. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3353. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3354. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3355. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3356. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3357. ArgNum = 4;
  3358. HasRC = true;
  3359. break;
  3360. }
  3361. llvm::APSInt Result;
  3362. // We can't check the value of a dependent argument.
  3363. Expr *Arg = TheCall->getArg(ArgNum);
  3364. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3365. return false;
  3366. // Check constant-ness first.
  3367. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3368. return true;
  3369. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3370. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3371. // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
  3372. // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
  3373. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3374. Result == 8/*ROUND_NO_EXC*/ ||
  3375. (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
  3376. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3377. return false;
  3378. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  3379. << Arg->getSourceRange();
  3380. }
  3381. // Check if the gather/scatter scale is legal.
  3382. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3383. CallExpr *TheCall) {
  3384. unsigned ArgNum = 0;
  3385. switch (BuiltinID) {
  3386. default:
  3387. return false;
  3388. case X86::BI__builtin_ia32_gatherpfdpd:
  3389. case X86::BI__builtin_ia32_gatherpfdps:
  3390. case X86::BI__builtin_ia32_gatherpfqpd:
  3391. case X86::BI__builtin_ia32_gatherpfqps:
  3392. case X86::BI__builtin_ia32_scatterpfdpd:
  3393. case X86::BI__builtin_ia32_scatterpfdps:
  3394. case X86::BI__builtin_ia32_scatterpfqpd:
  3395. case X86::BI__builtin_ia32_scatterpfqps:
  3396. ArgNum = 3;
  3397. break;
  3398. case X86::BI__builtin_ia32_gatherd_pd:
  3399. case X86::BI__builtin_ia32_gatherd_pd256:
  3400. case X86::BI__builtin_ia32_gatherq_pd:
  3401. case X86::BI__builtin_ia32_gatherq_pd256:
  3402. case X86::BI__builtin_ia32_gatherd_ps:
  3403. case X86::BI__builtin_ia32_gatherd_ps256:
  3404. case X86::BI__builtin_ia32_gatherq_ps:
  3405. case X86::BI__builtin_ia32_gatherq_ps256:
  3406. case X86::BI__builtin_ia32_gatherd_q:
  3407. case X86::BI__builtin_ia32_gatherd_q256:
  3408. case X86::BI__builtin_ia32_gatherq_q:
  3409. case X86::BI__builtin_ia32_gatherq_q256:
  3410. case X86::BI__builtin_ia32_gatherd_d:
  3411. case X86::BI__builtin_ia32_gatherd_d256:
  3412. case X86::BI__builtin_ia32_gatherq_d:
  3413. case X86::BI__builtin_ia32_gatherq_d256:
  3414. case X86::BI__builtin_ia32_gather3div2df:
  3415. case X86::BI__builtin_ia32_gather3div2di:
  3416. case X86::BI__builtin_ia32_gather3div4df:
  3417. case X86::BI__builtin_ia32_gather3div4di:
  3418. case X86::BI__builtin_ia32_gather3div4sf:
  3419. case X86::BI__builtin_ia32_gather3div4si:
  3420. case X86::BI__builtin_ia32_gather3div8sf:
  3421. case X86::BI__builtin_ia32_gather3div8si:
  3422. case X86::BI__builtin_ia32_gather3siv2df:
  3423. case X86::BI__builtin_ia32_gather3siv2di:
  3424. case X86::BI__builtin_ia32_gather3siv4df:
  3425. case X86::BI__builtin_ia32_gather3siv4di:
  3426. case X86::BI__builtin_ia32_gather3siv4sf:
  3427. case X86::BI__builtin_ia32_gather3siv4si:
  3428. case X86::BI__builtin_ia32_gather3siv8sf:
  3429. case X86::BI__builtin_ia32_gather3siv8si:
  3430. case X86::BI__builtin_ia32_gathersiv8df:
  3431. case X86::BI__builtin_ia32_gathersiv16sf:
  3432. case X86::BI__builtin_ia32_gatherdiv8df:
  3433. case X86::BI__builtin_ia32_gatherdiv16sf:
  3434. case X86::BI__builtin_ia32_gathersiv8di:
  3435. case X86::BI__builtin_ia32_gathersiv16si:
  3436. case X86::BI__builtin_ia32_gatherdiv8di:
  3437. case X86::BI__builtin_ia32_gatherdiv16si:
  3438. case X86::BI__builtin_ia32_scatterdiv2df:
  3439. case X86::BI__builtin_ia32_scatterdiv2di:
  3440. case X86::BI__builtin_ia32_scatterdiv4df:
  3441. case X86::BI__builtin_ia32_scatterdiv4di:
  3442. case X86::BI__builtin_ia32_scatterdiv4sf:
  3443. case X86::BI__builtin_ia32_scatterdiv4si:
  3444. case X86::BI__builtin_ia32_scatterdiv8sf:
  3445. case X86::BI__builtin_ia32_scatterdiv8si:
  3446. case X86::BI__builtin_ia32_scattersiv2df:
  3447. case X86::BI__builtin_ia32_scattersiv2di:
  3448. case X86::BI__builtin_ia32_scattersiv4df:
  3449. case X86::BI__builtin_ia32_scattersiv4di:
  3450. case X86::BI__builtin_ia32_scattersiv4sf:
  3451. case X86::BI__builtin_ia32_scattersiv4si:
  3452. case X86::BI__builtin_ia32_scattersiv8sf:
  3453. case X86::BI__builtin_ia32_scattersiv8si:
  3454. case X86::BI__builtin_ia32_scattersiv8df:
  3455. case X86::BI__builtin_ia32_scattersiv16sf:
  3456. case X86::BI__builtin_ia32_scatterdiv8df:
  3457. case X86::BI__builtin_ia32_scatterdiv16sf:
  3458. case X86::BI__builtin_ia32_scattersiv8di:
  3459. case X86::BI__builtin_ia32_scattersiv16si:
  3460. case X86::BI__builtin_ia32_scatterdiv8di:
  3461. case X86::BI__builtin_ia32_scatterdiv16si:
  3462. ArgNum = 4;
  3463. break;
  3464. }
  3465. llvm::APSInt Result;
  3466. // We can't check the value of a dependent argument.
  3467. Expr *Arg = TheCall->getArg(ArgNum);
  3468. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3469. return false;
  3470. // Check constant-ness first.
  3471. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3472. return true;
  3473. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3474. return false;
  3475. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  3476. << Arg->getSourceRange();
  3477. }
  3478. static bool isX86_32Builtin(unsigned BuiltinID) {
  3479. // These builtins only work on x86-32 targets.
  3480. switch (BuiltinID) {
  3481. case X86::BI__builtin_ia32_readeflags_u32:
  3482. case X86::BI__builtin_ia32_writeeflags_u32:
  3483. return true;
  3484. }
  3485. return false;
  3486. }
  3487. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3488. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3489. return SemaBuiltinCpuSupports(*this, TheCall);
  3490. if (BuiltinID == X86::BI__builtin_cpu_is)
  3491. return SemaBuiltinCpuIs(*this, TheCall);
  3492. // Check for 32-bit only builtins on a 64-bit target.
  3493. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3494. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3495. return Diag(TheCall->getCallee()->getBeginLoc(),
  3496. diag::err_32_bit_builtin_64_bit_tgt);
  3497. // If the intrinsic has rounding or SAE make sure its valid.
  3498. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3499. return true;
  3500. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3501. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3502. return true;
  3503. // For intrinsics which take an immediate value as part of the instruction,
  3504. // range check them here.
  3505. int i = 0, l = 0, u = 0;
  3506. switch (BuiltinID) {
  3507. default:
  3508. return false;
  3509. case X86::BI__builtin_ia32_vec_ext_v2si:
  3510. case X86::BI__builtin_ia32_vec_ext_v2di:
  3511. case X86::BI__builtin_ia32_vextractf128_pd256:
  3512. case X86::BI__builtin_ia32_vextractf128_ps256:
  3513. case X86::BI__builtin_ia32_vextractf128_si256:
  3514. case X86::BI__builtin_ia32_extract128i256:
  3515. case X86::BI__builtin_ia32_extractf64x4_mask:
  3516. case X86::BI__builtin_ia32_extracti64x4_mask:
  3517. case X86::BI__builtin_ia32_extractf32x8_mask:
  3518. case X86::BI__builtin_ia32_extracti32x8_mask:
  3519. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3520. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3521. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3522. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3523. i = 1; l = 0; u = 1;
  3524. break;
  3525. case X86::BI__builtin_ia32_vec_set_v2di:
  3526. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3527. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3528. case X86::BI__builtin_ia32_vinsertf128_si256:
  3529. case X86::BI__builtin_ia32_insert128i256:
  3530. case X86::BI__builtin_ia32_insertf32x8:
  3531. case X86::BI__builtin_ia32_inserti32x8:
  3532. case X86::BI__builtin_ia32_insertf64x4:
  3533. case X86::BI__builtin_ia32_inserti64x4:
  3534. case X86::BI__builtin_ia32_insertf64x2_256:
  3535. case X86::BI__builtin_ia32_inserti64x2_256:
  3536. case X86::BI__builtin_ia32_insertf32x4_256:
  3537. case X86::BI__builtin_ia32_inserti32x4_256:
  3538. i = 2; l = 0; u = 1;
  3539. break;
  3540. case X86::BI__builtin_ia32_vpermilpd:
  3541. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3542. case X86::BI__builtin_ia32_vec_ext_v4si:
  3543. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3544. case X86::BI__builtin_ia32_vec_ext_v4di:
  3545. case X86::BI__builtin_ia32_extractf32x4_mask:
  3546. case X86::BI__builtin_ia32_extracti32x4_mask:
  3547. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3548. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3549. i = 1; l = 0; u = 3;
  3550. break;
  3551. case X86::BI_mm_prefetch:
  3552. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3553. case X86::BI__builtin_ia32_vec_ext_v8si:
  3554. i = 1; l = 0; u = 7;
  3555. break;
  3556. case X86::BI__builtin_ia32_sha1rnds4:
  3557. case X86::BI__builtin_ia32_blendpd:
  3558. case X86::BI__builtin_ia32_shufpd:
  3559. case X86::BI__builtin_ia32_vec_set_v4hi:
  3560. case X86::BI__builtin_ia32_vec_set_v4si:
  3561. case X86::BI__builtin_ia32_vec_set_v4di:
  3562. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3563. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3564. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3565. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3566. case X86::BI__builtin_ia32_insertf64x2_512:
  3567. case X86::BI__builtin_ia32_inserti64x2_512:
  3568. case X86::BI__builtin_ia32_insertf32x4:
  3569. case X86::BI__builtin_ia32_inserti32x4:
  3570. i = 2; l = 0; u = 3;
  3571. break;
  3572. case X86::BI__builtin_ia32_vpermil2pd:
  3573. case X86::BI__builtin_ia32_vpermil2pd256:
  3574. case X86::BI__builtin_ia32_vpermil2ps:
  3575. case X86::BI__builtin_ia32_vpermil2ps256:
  3576. i = 3; l = 0; u = 3;
  3577. break;
  3578. case X86::BI__builtin_ia32_cmpb128_mask:
  3579. case X86::BI__builtin_ia32_cmpw128_mask:
  3580. case X86::BI__builtin_ia32_cmpd128_mask:
  3581. case X86::BI__builtin_ia32_cmpq128_mask:
  3582. case X86::BI__builtin_ia32_cmpb256_mask:
  3583. case X86::BI__builtin_ia32_cmpw256_mask:
  3584. case X86::BI__builtin_ia32_cmpd256_mask:
  3585. case X86::BI__builtin_ia32_cmpq256_mask:
  3586. case X86::BI__builtin_ia32_cmpb512_mask:
  3587. case X86::BI__builtin_ia32_cmpw512_mask:
  3588. case X86::BI__builtin_ia32_cmpd512_mask:
  3589. case X86::BI__builtin_ia32_cmpq512_mask:
  3590. case X86::BI__builtin_ia32_ucmpb128_mask:
  3591. case X86::BI__builtin_ia32_ucmpw128_mask:
  3592. case X86::BI__builtin_ia32_ucmpd128_mask:
  3593. case X86::BI__builtin_ia32_ucmpq128_mask:
  3594. case X86::BI__builtin_ia32_ucmpb256_mask:
  3595. case X86::BI__builtin_ia32_ucmpw256_mask:
  3596. case X86::BI__builtin_ia32_ucmpd256_mask:
  3597. case X86::BI__builtin_ia32_ucmpq256_mask:
  3598. case X86::BI__builtin_ia32_ucmpb512_mask:
  3599. case X86::BI__builtin_ia32_ucmpw512_mask:
  3600. case X86::BI__builtin_ia32_ucmpd512_mask:
  3601. case X86::BI__builtin_ia32_ucmpq512_mask:
  3602. case X86::BI__builtin_ia32_vpcomub:
  3603. case X86::BI__builtin_ia32_vpcomuw:
  3604. case X86::BI__builtin_ia32_vpcomud:
  3605. case X86::BI__builtin_ia32_vpcomuq:
  3606. case X86::BI__builtin_ia32_vpcomb:
  3607. case X86::BI__builtin_ia32_vpcomw:
  3608. case X86::BI__builtin_ia32_vpcomd:
  3609. case X86::BI__builtin_ia32_vpcomq:
  3610. case X86::BI__builtin_ia32_vec_set_v8hi:
  3611. case X86::BI__builtin_ia32_vec_set_v8si:
  3612. i = 2; l = 0; u = 7;
  3613. break;
  3614. case X86::BI__builtin_ia32_vpermilpd256:
  3615. case X86::BI__builtin_ia32_roundps:
  3616. case X86::BI__builtin_ia32_roundpd:
  3617. case X86::BI__builtin_ia32_roundps256:
  3618. case X86::BI__builtin_ia32_roundpd256:
  3619. case X86::BI__builtin_ia32_getmantpd128_mask:
  3620. case X86::BI__builtin_ia32_getmantpd256_mask:
  3621. case X86::BI__builtin_ia32_getmantps128_mask:
  3622. case X86::BI__builtin_ia32_getmantps256_mask:
  3623. case X86::BI__builtin_ia32_getmantpd512_mask:
  3624. case X86::BI__builtin_ia32_getmantps512_mask:
  3625. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3626. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3627. i = 1; l = 0; u = 15;
  3628. break;
  3629. case X86::BI__builtin_ia32_pblendd128:
  3630. case X86::BI__builtin_ia32_blendps:
  3631. case X86::BI__builtin_ia32_blendpd256:
  3632. case X86::BI__builtin_ia32_shufpd256:
  3633. case X86::BI__builtin_ia32_roundss:
  3634. case X86::BI__builtin_ia32_roundsd:
  3635. case X86::BI__builtin_ia32_rangepd128_mask:
  3636. case X86::BI__builtin_ia32_rangepd256_mask:
  3637. case X86::BI__builtin_ia32_rangepd512_mask:
  3638. case X86::BI__builtin_ia32_rangeps128_mask:
  3639. case X86::BI__builtin_ia32_rangeps256_mask:
  3640. case X86::BI__builtin_ia32_rangeps512_mask:
  3641. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3642. case X86::BI__builtin_ia32_getmantss_round_mask:
  3643. case X86::BI__builtin_ia32_vec_set_v16qi:
  3644. case X86::BI__builtin_ia32_vec_set_v16hi:
  3645. i = 2; l = 0; u = 15;
  3646. break;
  3647. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3648. i = 1; l = 0; u = 31;
  3649. break;
  3650. case X86::BI__builtin_ia32_cmpps:
  3651. case X86::BI__builtin_ia32_cmpss:
  3652. case X86::BI__builtin_ia32_cmppd:
  3653. case X86::BI__builtin_ia32_cmpsd:
  3654. case X86::BI__builtin_ia32_cmpps256:
  3655. case X86::BI__builtin_ia32_cmppd256:
  3656. case X86::BI__builtin_ia32_cmpps128_mask:
  3657. case X86::BI__builtin_ia32_cmppd128_mask:
  3658. case X86::BI__builtin_ia32_cmpps256_mask:
  3659. case X86::BI__builtin_ia32_cmppd256_mask:
  3660. case X86::BI__builtin_ia32_cmpps512_mask:
  3661. case X86::BI__builtin_ia32_cmppd512_mask:
  3662. case X86::BI__builtin_ia32_cmpsd_mask:
  3663. case X86::BI__builtin_ia32_cmpss_mask:
  3664. case X86::BI__builtin_ia32_vec_set_v32qi:
  3665. i = 2; l = 0; u = 31;
  3666. break;
  3667. case X86::BI__builtin_ia32_permdf256:
  3668. case X86::BI__builtin_ia32_permdi256:
  3669. case X86::BI__builtin_ia32_permdf512:
  3670. case X86::BI__builtin_ia32_permdi512:
  3671. case X86::BI__builtin_ia32_vpermilps:
  3672. case X86::BI__builtin_ia32_vpermilps256:
  3673. case X86::BI__builtin_ia32_vpermilpd512:
  3674. case X86::BI__builtin_ia32_vpermilps512:
  3675. case X86::BI__builtin_ia32_pshufd:
  3676. case X86::BI__builtin_ia32_pshufd256:
  3677. case X86::BI__builtin_ia32_pshufd512:
  3678. case X86::BI__builtin_ia32_pshufhw:
  3679. case X86::BI__builtin_ia32_pshufhw256:
  3680. case X86::BI__builtin_ia32_pshufhw512:
  3681. case X86::BI__builtin_ia32_pshuflw:
  3682. case X86::BI__builtin_ia32_pshuflw256:
  3683. case X86::BI__builtin_ia32_pshuflw512:
  3684. case X86::BI__builtin_ia32_vcvtps2ph:
  3685. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3686. case X86::BI__builtin_ia32_vcvtps2ph256:
  3687. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3688. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3689. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3690. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3691. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3692. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3693. case X86::BI__builtin_ia32_rndscaleps_mask:
  3694. case X86::BI__builtin_ia32_rndscalepd_mask:
  3695. case X86::BI__builtin_ia32_reducepd128_mask:
  3696. case X86::BI__builtin_ia32_reducepd256_mask:
  3697. case X86::BI__builtin_ia32_reducepd512_mask:
  3698. case X86::BI__builtin_ia32_reduceps128_mask:
  3699. case X86::BI__builtin_ia32_reduceps256_mask:
  3700. case X86::BI__builtin_ia32_reduceps512_mask:
  3701. case X86::BI__builtin_ia32_prold512:
  3702. case X86::BI__builtin_ia32_prolq512:
  3703. case X86::BI__builtin_ia32_prold128:
  3704. case X86::BI__builtin_ia32_prold256:
  3705. case X86::BI__builtin_ia32_prolq128:
  3706. case X86::BI__builtin_ia32_prolq256:
  3707. case X86::BI__builtin_ia32_prord512:
  3708. case X86::BI__builtin_ia32_prorq512:
  3709. case X86::BI__builtin_ia32_prord128:
  3710. case X86::BI__builtin_ia32_prord256:
  3711. case X86::BI__builtin_ia32_prorq128:
  3712. case X86::BI__builtin_ia32_prorq256:
  3713. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3714. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3715. case X86::BI__builtin_ia32_fpclassps128_mask:
  3716. case X86::BI__builtin_ia32_fpclassps256_mask:
  3717. case X86::BI__builtin_ia32_fpclassps512_mask:
  3718. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3719. case X86::BI__builtin_ia32_fpclasssd_mask:
  3720. case X86::BI__builtin_ia32_fpclassss_mask:
  3721. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3722. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3723. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3724. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3725. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3726. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3727. case X86::BI__builtin_ia32_kshiftliqi:
  3728. case X86::BI__builtin_ia32_kshiftlihi:
  3729. case X86::BI__builtin_ia32_kshiftlisi:
  3730. case X86::BI__builtin_ia32_kshiftlidi:
  3731. case X86::BI__builtin_ia32_kshiftriqi:
  3732. case X86::BI__builtin_ia32_kshiftrihi:
  3733. case X86::BI__builtin_ia32_kshiftrisi:
  3734. case X86::BI__builtin_ia32_kshiftridi:
  3735. i = 1; l = 0; u = 255;
  3736. break;
  3737. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3738. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3739. case X86::BI__builtin_ia32_vperm2f128_si256:
  3740. case X86::BI__builtin_ia32_permti256:
  3741. case X86::BI__builtin_ia32_pblendw128:
  3742. case X86::BI__builtin_ia32_pblendw256:
  3743. case X86::BI__builtin_ia32_blendps256:
  3744. case X86::BI__builtin_ia32_pblendd256:
  3745. case X86::BI__builtin_ia32_palignr128:
  3746. case X86::BI__builtin_ia32_palignr256:
  3747. case X86::BI__builtin_ia32_palignr512:
  3748. case X86::BI__builtin_ia32_alignq512:
  3749. case X86::BI__builtin_ia32_alignd512:
  3750. case X86::BI__builtin_ia32_alignd128:
  3751. case X86::BI__builtin_ia32_alignd256:
  3752. case X86::BI__builtin_ia32_alignq128:
  3753. case X86::BI__builtin_ia32_alignq256:
  3754. case X86::BI__builtin_ia32_vcomisd:
  3755. case X86::BI__builtin_ia32_vcomiss:
  3756. case X86::BI__builtin_ia32_shuf_f32x4:
  3757. case X86::BI__builtin_ia32_shuf_f64x2:
  3758. case X86::BI__builtin_ia32_shuf_i32x4:
  3759. case X86::BI__builtin_ia32_shuf_i64x2:
  3760. case X86::BI__builtin_ia32_shufpd512:
  3761. case X86::BI__builtin_ia32_shufps:
  3762. case X86::BI__builtin_ia32_shufps256:
  3763. case X86::BI__builtin_ia32_shufps512:
  3764. case X86::BI__builtin_ia32_dbpsadbw128:
  3765. case X86::BI__builtin_ia32_dbpsadbw256:
  3766. case X86::BI__builtin_ia32_dbpsadbw512:
  3767. case X86::BI__builtin_ia32_vpshldd128:
  3768. case X86::BI__builtin_ia32_vpshldd256:
  3769. case X86::BI__builtin_ia32_vpshldd512:
  3770. case X86::BI__builtin_ia32_vpshldq128:
  3771. case X86::BI__builtin_ia32_vpshldq256:
  3772. case X86::BI__builtin_ia32_vpshldq512:
  3773. case X86::BI__builtin_ia32_vpshldw128:
  3774. case X86::BI__builtin_ia32_vpshldw256:
  3775. case X86::BI__builtin_ia32_vpshldw512:
  3776. case X86::BI__builtin_ia32_vpshrdd128:
  3777. case X86::BI__builtin_ia32_vpshrdd256:
  3778. case X86::BI__builtin_ia32_vpshrdd512:
  3779. case X86::BI__builtin_ia32_vpshrdq128:
  3780. case X86::BI__builtin_ia32_vpshrdq256:
  3781. case X86::BI__builtin_ia32_vpshrdq512:
  3782. case X86::BI__builtin_ia32_vpshrdw128:
  3783. case X86::BI__builtin_ia32_vpshrdw256:
  3784. case X86::BI__builtin_ia32_vpshrdw512:
  3785. i = 2; l = 0; u = 255;
  3786. break;
  3787. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3788. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3789. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3790. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3791. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3792. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3793. case X86::BI__builtin_ia32_fixupimmss_mask:
  3794. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3795. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3796. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3797. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3798. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3799. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3800. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3801. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3802. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3803. case X86::BI__builtin_ia32_pternlogd512_mask:
  3804. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3805. case X86::BI__builtin_ia32_pternlogq512_mask:
  3806. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3807. case X86::BI__builtin_ia32_pternlogd128_mask:
  3808. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3809. case X86::BI__builtin_ia32_pternlogd256_mask:
  3810. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3811. case X86::BI__builtin_ia32_pternlogq128_mask:
  3812. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3813. case X86::BI__builtin_ia32_pternlogq256_mask:
  3814. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3815. i = 3; l = 0; u = 255;
  3816. break;
  3817. case X86::BI__builtin_ia32_gatherpfdpd:
  3818. case X86::BI__builtin_ia32_gatherpfdps:
  3819. case X86::BI__builtin_ia32_gatherpfqpd:
  3820. case X86::BI__builtin_ia32_gatherpfqps:
  3821. case X86::BI__builtin_ia32_scatterpfdpd:
  3822. case X86::BI__builtin_ia32_scatterpfdps:
  3823. case X86::BI__builtin_ia32_scatterpfqpd:
  3824. case X86::BI__builtin_ia32_scatterpfqps:
  3825. i = 4; l = 2; u = 3;
  3826. break;
  3827. case X86::BI__builtin_ia32_reducesd_mask:
  3828. case X86::BI__builtin_ia32_reducess_mask:
  3829. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3830. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3831. i = 4; l = 0; u = 255;
  3832. break;
  3833. }
  3834. // Note that we don't force a hard error on the range check here, allowing
  3835. // template-generated or macro-generated dead code to potentially have out-of-
  3836. // range values. These need to code generate, but don't need to necessarily
  3837. // make any sense. We use a warning that defaults to an error.
  3838. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3839. }
  3840. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3841. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3842. /// Returns true when the format fits the function and the FormatStringInfo has
  3843. /// been populated.
  3844. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3845. FormatStringInfo *FSI) {
  3846. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3847. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3848. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3849. // The way the format attribute works in GCC, the implicit this argument
  3850. // of member functions is counted. However, it doesn't appear in our own
  3851. // lists, so decrement format_idx in that case.
  3852. if (IsCXXMember) {
  3853. if(FSI->FormatIdx == 0)
  3854. return false;
  3855. --FSI->FormatIdx;
  3856. if (FSI->FirstDataArg != 0)
  3857. --FSI->FirstDataArg;
  3858. }
  3859. return true;
  3860. }
  3861. /// Checks if a the given expression evaluates to null.
  3862. ///
  3863. /// Returns true if the value evaluates to null.
  3864. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3865. // If the expression has non-null type, it doesn't evaluate to null.
  3866. if (auto nullability
  3867. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3868. if (*nullability == NullabilityKind::NonNull)
  3869. return false;
  3870. }
  3871. // As a special case, transparent unions initialized with zero are
  3872. // considered null for the purposes of the nonnull attribute.
  3873. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3874. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3875. if (const CompoundLiteralExpr *CLE =
  3876. dyn_cast<CompoundLiteralExpr>(Expr))
  3877. if (const InitListExpr *ILE =
  3878. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3879. Expr = ILE->getInit(0);
  3880. }
  3881. bool Result;
  3882. return (!Expr->isValueDependent() &&
  3883. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3884. !Result);
  3885. }
  3886. static void CheckNonNullArgument(Sema &S,
  3887. const Expr *ArgExpr,
  3888. SourceLocation CallSiteLoc) {
  3889. if (CheckNonNullExpr(S, ArgExpr))
  3890. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3891. S.PDiag(diag::warn_null_arg)
  3892. << ArgExpr->getSourceRange());
  3893. }
  3894. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  3895. FormatStringInfo FSI;
  3896. if ((GetFormatStringType(Format) == FST_NSString) &&
  3897. getFormatStringInfo(Format, false, &FSI)) {
  3898. Idx = FSI.FormatIdx;
  3899. return true;
  3900. }
  3901. return false;
  3902. }
  3903. /// Diagnose use of %s directive in an NSString which is being passed
  3904. /// as formatting string to formatting method.
  3905. static void
  3906. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  3907. const NamedDecl *FDecl,
  3908. Expr **Args,
  3909. unsigned NumArgs) {
  3910. unsigned Idx = 0;
  3911. bool Format = false;
  3912. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  3913. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  3914. Idx = 2;
  3915. Format = true;
  3916. }
  3917. else
  3918. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3919. if (S.GetFormatNSStringIdx(I, Idx)) {
  3920. Format = true;
  3921. break;
  3922. }
  3923. }
  3924. if (!Format || NumArgs <= Idx)
  3925. return;
  3926. const Expr *FormatExpr = Args[Idx];
  3927. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  3928. FormatExpr = CSCE->getSubExpr();
  3929. const StringLiteral *FormatString;
  3930. if (const ObjCStringLiteral *OSL =
  3931. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  3932. FormatString = OSL->getString();
  3933. else
  3934. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  3935. if (!FormatString)
  3936. return;
  3937. if (S.FormatStringHasSArg(FormatString)) {
  3938. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  3939. << "%s" << 1 << 1;
  3940. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  3941. << FDecl->getDeclName();
  3942. }
  3943. }
  3944. /// Determine whether the given type has a non-null nullability annotation.
  3945. static bool isNonNullType(ASTContext &ctx, QualType type) {
  3946. if (auto nullability = type->getNullability(ctx))
  3947. return *nullability == NullabilityKind::NonNull;
  3948. return false;
  3949. }
  3950. static void CheckNonNullArguments(Sema &S,
  3951. const NamedDecl *FDecl,
  3952. const FunctionProtoType *Proto,
  3953. ArrayRef<const Expr *> Args,
  3954. SourceLocation CallSiteLoc) {
  3955. assert((FDecl || Proto) && "Need a function declaration or prototype");
  3956. // Already checked by by constant evaluator.
  3957. if (S.isConstantEvaluated())
  3958. return;
  3959. // Check the attributes attached to the method/function itself.
  3960. llvm::SmallBitVector NonNullArgs;
  3961. if (FDecl) {
  3962. // Handle the nonnull attribute on the function/method declaration itself.
  3963. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3964. if (!NonNull->args_size()) {
  3965. // Easy case: all pointer arguments are nonnull.
  3966. for (const auto *Arg : Args)
  3967. if (S.isValidPointerAttrType(Arg->getType()))
  3968. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3969. return;
  3970. }
  3971. for (const ParamIdx &Idx : NonNull->args()) {
  3972. unsigned IdxAST = Idx.getASTIndex();
  3973. if (IdxAST >= Args.size())
  3974. continue;
  3975. if (NonNullArgs.empty())
  3976. NonNullArgs.resize(Args.size());
  3977. NonNullArgs.set(IdxAST);
  3978. }
  3979. }
  3980. }
  3981. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3982. // Handle the nonnull attribute on the parameters of the
  3983. // function/method.
  3984. ArrayRef<ParmVarDecl*> parms;
  3985. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3986. parms = FD->parameters();
  3987. else
  3988. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3989. unsigned ParamIndex = 0;
  3990. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3991. I != E; ++I, ++ParamIndex) {
  3992. const ParmVarDecl *PVD = *I;
  3993. if (PVD->hasAttr<NonNullAttr>() ||
  3994. isNonNullType(S.Context, PVD->getType())) {
  3995. if (NonNullArgs.empty())
  3996. NonNullArgs.resize(Args.size());
  3997. NonNullArgs.set(ParamIndex);
  3998. }
  3999. }
  4000. } else {
  4001. // If we have a non-function, non-method declaration but no
  4002. // function prototype, try to dig out the function prototype.
  4003. if (!Proto) {
  4004. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  4005. QualType type = VD->getType().getNonReferenceType();
  4006. if (auto pointerType = type->getAs<PointerType>())
  4007. type = pointerType->getPointeeType();
  4008. else if (auto blockType = type->getAs<BlockPointerType>())
  4009. type = blockType->getPointeeType();
  4010. // FIXME: data member pointers?
  4011. // Dig out the function prototype, if there is one.
  4012. Proto = type->getAs<FunctionProtoType>();
  4013. }
  4014. }
  4015. // Fill in non-null argument information from the nullability
  4016. // information on the parameter types (if we have them).
  4017. if (Proto) {
  4018. unsigned Index = 0;
  4019. for (auto paramType : Proto->getParamTypes()) {
  4020. if (isNonNullType(S.Context, paramType)) {
  4021. if (NonNullArgs.empty())
  4022. NonNullArgs.resize(Args.size());
  4023. NonNullArgs.set(Index);
  4024. }
  4025. ++Index;
  4026. }
  4027. }
  4028. }
  4029. // Check for non-null arguments.
  4030. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  4031. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  4032. if (NonNullArgs[ArgIndex])
  4033. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  4034. }
  4035. }
  4036. /// Handles the checks for format strings, non-POD arguments to vararg
  4037. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  4038. /// attributes.
  4039. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  4040. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  4041. bool IsMemberFunction, SourceLocation Loc,
  4042. SourceRange Range, VariadicCallType CallType) {
  4043. // FIXME: We should check as much as we can in the template definition.
  4044. if (CurContext->isDependentContext())
  4045. return;
  4046. // Printf and scanf checking.
  4047. llvm::SmallBitVector CheckedVarArgs;
  4048. if (FDecl) {
  4049. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  4050. // Only create vector if there are format attributes.
  4051. CheckedVarArgs.resize(Args.size());
  4052. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  4053. CheckedVarArgs);
  4054. }
  4055. }
  4056. // Refuse POD arguments that weren't caught by the format string
  4057. // checks above.
  4058. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  4059. if (CallType != VariadicDoesNotApply &&
  4060. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  4061. unsigned NumParams = Proto ? Proto->getNumParams()
  4062. : FDecl && isa<FunctionDecl>(FDecl)
  4063. ? cast<FunctionDecl>(FDecl)->getNumParams()
  4064. : FDecl && isa<ObjCMethodDecl>(FDecl)
  4065. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  4066. : 0;
  4067. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  4068. // Args[ArgIdx] can be null in malformed code.
  4069. if (const Expr *Arg = Args[ArgIdx]) {
  4070. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  4071. checkVariadicArgument(Arg, CallType);
  4072. }
  4073. }
  4074. }
  4075. if (FDecl || Proto) {
  4076. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  4077. // Type safety checking.
  4078. if (FDecl) {
  4079. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  4080. CheckArgumentWithTypeTag(I, Args, Loc);
  4081. }
  4082. }
  4083. if (FD)
  4084. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  4085. }
  4086. /// CheckConstructorCall - Check a constructor call for correctness and safety
  4087. /// properties not enforced by the C type system.
  4088. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  4089. ArrayRef<const Expr *> Args,
  4090. const FunctionProtoType *Proto,
  4091. SourceLocation Loc) {
  4092. VariadicCallType CallType =
  4093. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  4094. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  4095. Loc, SourceRange(), CallType);
  4096. }
  4097. /// CheckFunctionCall - Check a direct function call for various correctness
  4098. /// and safety properties not strictly enforced by the C type system.
  4099. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  4100. const FunctionProtoType *Proto) {
  4101. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  4102. isa<CXXMethodDecl>(FDecl);
  4103. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  4104. IsMemberOperatorCall;
  4105. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  4106. TheCall->getCallee());
  4107. Expr** Args = TheCall->getArgs();
  4108. unsigned NumArgs = TheCall->getNumArgs();
  4109. Expr *ImplicitThis = nullptr;
  4110. if (IsMemberOperatorCall) {
  4111. // If this is a call to a member operator, hide the first argument
  4112. // from checkCall.
  4113. // FIXME: Our choice of AST representation here is less than ideal.
  4114. ImplicitThis = Args[0];
  4115. ++Args;
  4116. --NumArgs;
  4117. } else if (IsMemberFunction)
  4118. ImplicitThis =
  4119. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  4120. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  4121. IsMemberFunction, TheCall->getRParenLoc(),
  4122. TheCall->getCallee()->getSourceRange(), CallType);
  4123. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4124. // None of the checks below are needed for functions that don't have
  4125. // simple names (e.g., C++ conversion functions).
  4126. if (!FnInfo)
  4127. return false;
  4128. CheckAbsoluteValueFunction(TheCall, FDecl);
  4129. CheckMaxUnsignedZero(TheCall, FDecl);
  4130. if (getLangOpts().ObjC)
  4131. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  4132. unsigned CMId = FDecl->getMemoryFunctionKind();
  4133. if (CMId == 0)
  4134. return false;
  4135. // Handle memory setting and copying functions.
  4136. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  4137. CheckStrlcpycatArguments(TheCall, FnInfo);
  4138. else if (CMId == Builtin::BIstrncat)
  4139. CheckStrncatArguments(TheCall, FnInfo);
  4140. else
  4141. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  4142. return false;
  4143. }
  4144. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  4145. ArrayRef<const Expr *> Args) {
  4146. VariadicCallType CallType =
  4147. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  4148. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  4149. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  4150. CallType);
  4151. return false;
  4152. }
  4153. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  4154. const FunctionProtoType *Proto) {
  4155. QualType Ty;
  4156. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  4157. Ty = V->getType().getNonReferenceType();
  4158. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  4159. Ty = F->getType().getNonReferenceType();
  4160. else
  4161. return false;
  4162. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  4163. !Ty->isFunctionProtoType())
  4164. return false;
  4165. VariadicCallType CallType;
  4166. if (!Proto || !Proto->isVariadic()) {
  4167. CallType = VariadicDoesNotApply;
  4168. } else if (Ty->isBlockPointerType()) {
  4169. CallType = VariadicBlock;
  4170. } else { // Ty->isFunctionPointerType()
  4171. CallType = VariadicFunction;
  4172. }
  4173. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  4174. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4175. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4176. TheCall->getCallee()->getSourceRange(), CallType);
  4177. return false;
  4178. }
  4179. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  4180. /// such as function pointers returned from functions.
  4181. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  4182. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  4183. TheCall->getCallee());
  4184. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  4185. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4186. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4187. TheCall->getCallee()->getSourceRange(), CallType);
  4188. return false;
  4189. }
  4190. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  4191. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  4192. return false;
  4193. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  4194. switch (Op) {
  4195. case AtomicExpr::AO__c11_atomic_init:
  4196. case AtomicExpr::AO__opencl_atomic_init:
  4197. llvm_unreachable("There is no ordering argument for an init");
  4198. case AtomicExpr::AO__c11_atomic_load:
  4199. case AtomicExpr::AO__opencl_atomic_load:
  4200. case AtomicExpr::AO__atomic_load_n:
  4201. case AtomicExpr::AO__atomic_load:
  4202. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  4203. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4204. case AtomicExpr::AO__c11_atomic_store:
  4205. case AtomicExpr::AO__opencl_atomic_store:
  4206. case AtomicExpr::AO__atomic_store:
  4207. case AtomicExpr::AO__atomic_store_n:
  4208. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  4209. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  4210. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4211. default:
  4212. return true;
  4213. }
  4214. }
  4215. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  4216. AtomicExpr::AtomicOp Op) {
  4217. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  4218. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4219. MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
  4220. return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
  4221. DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
  4222. Op);
  4223. }
  4224. ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
  4225. SourceLocation RParenLoc, MultiExprArg Args,
  4226. AtomicExpr::AtomicOp Op,
  4227. AtomicArgumentOrder ArgOrder) {
  4228. // All the non-OpenCL operations take one of the following forms.
  4229. // The OpenCL operations take the __c11 forms with one extra argument for
  4230. // synchronization scope.
  4231. enum {
  4232. // C __c11_atomic_init(A *, C)
  4233. Init,
  4234. // C __c11_atomic_load(A *, int)
  4235. Load,
  4236. // void __atomic_load(A *, CP, int)
  4237. LoadCopy,
  4238. // void __atomic_store(A *, CP, int)
  4239. Copy,
  4240. // C __c11_atomic_add(A *, M, int)
  4241. Arithmetic,
  4242. // C __atomic_exchange_n(A *, CP, int)
  4243. Xchg,
  4244. // void __atomic_exchange(A *, C *, CP, int)
  4245. GNUXchg,
  4246. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  4247. C11CmpXchg,
  4248. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  4249. GNUCmpXchg
  4250. } Form = Init;
  4251. const unsigned NumForm = GNUCmpXchg + 1;
  4252. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  4253. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  4254. // where:
  4255. // C is an appropriate type,
  4256. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  4257. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  4258. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  4259. // the int parameters are for orderings.
  4260. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  4261. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  4262. "need to update code for modified forms");
  4263. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  4264. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  4265. AtomicExpr::AO__atomic_load,
  4266. "need to update code for modified C11 atomics");
  4267. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  4268. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  4269. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  4270. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  4271. IsOpenCL;
  4272. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  4273. Op == AtomicExpr::AO__atomic_store_n ||
  4274. Op == AtomicExpr::AO__atomic_exchange_n ||
  4275. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  4276. bool IsAddSub = false;
  4277. bool IsMinMax = false;
  4278. switch (Op) {
  4279. case AtomicExpr::AO__c11_atomic_init:
  4280. case AtomicExpr::AO__opencl_atomic_init:
  4281. Form = Init;
  4282. break;
  4283. case AtomicExpr::AO__c11_atomic_load:
  4284. case AtomicExpr::AO__opencl_atomic_load:
  4285. case AtomicExpr::AO__atomic_load_n:
  4286. Form = Load;
  4287. break;
  4288. case AtomicExpr::AO__atomic_load:
  4289. Form = LoadCopy;
  4290. break;
  4291. case AtomicExpr::AO__c11_atomic_store:
  4292. case AtomicExpr::AO__opencl_atomic_store:
  4293. case AtomicExpr::AO__atomic_store:
  4294. case AtomicExpr::AO__atomic_store_n:
  4295. Form = Copy;
  4296. break;
  4297. case AtomicExpr::AO__c11_atomic_fetch_add:
  4298. case AtomicExpr::AO__c11_atomic_fetch_sub:
  4299. case AtomicExpr::AO__opencl_atomic_fetch_add:
  4300. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  4301. case AtomicExpr::AO__opencl_atomic_fetch_min:
  4302. case AtomicExpr::AO__opencl_atomic_fetch_max:
  4303. case AtomicExpr::AO__atomic_fetch_add:
  4304. case AtomicExpr::AO__atomic_fetch_sub:
  4305. case AtomicExpr::AO__atomic_add_fetch:
  4306. case AtomicExpr::AO__atomic_sub_fetch:
  4307. IsAddSub = true;
  4308. LLVM_FALLTHROUGH;
  4309. case AtomicExpr::AO__c11_atomic_fetch_and:
  4310. case AtomicExpr::AO__c11_atomic_fetch_or:
  4311. case AtomicExpr::AO__c11_atomic_fetch_xor:
  4312. case AtomicExpr::AO__opencl_atomic_fetch_and:
  4313. case AtomicExpr::AO__opencl_atomic_fetch_or:
  4314. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  4315. case AtomicExpr::AO__atomic_fetch_and:
  4316. case AtomicExpr::AO__atomic_fetch_or:
  4317. case AtomicExpr::AO__atomic_fetch_xor:
  4318. case AtomicExpr::AO__atomic_fetch_nand:
  4319. case AtomicExpr::AO__atomic_and_fetch:
  4320. case AtomicExpr::AO__atomic_or_fetch:
  4321. case AtomicExpr::AO__atomic_xor_fetch:
  4322. case AtomicExpr::AO__atomic_nand_fetch:
  4323. Form = Arithmetic;
  4324. break;
  4325. case AtomicExpr::AO__atomic_fetch_min:
  4326. case AtomicExpr::AO__atomic_fetch_max:
  4327. IsMinMax = true;
  4328. Form = Arithmetic;
  4329. break;
  4330. case AtomicExpr::AO__c11_atomic_exchange:
  4331. case AtomicExpr::AO__opencl_atomic_exchange:
  4332. case AtomicExpr::AO__atomic_exchange_n:
  4333. Form = Xchg;
  4334. break;
  4335. case AtomicExpr::AO__atomic_exchange:
  4336. Form = GNUXchg;
  4337. break;
  4338. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4339. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4340. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4341. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4342. Form = C11CmpXchg;
  4343. break;
  4344. case AtomicExpr::AO__atomic_compare_exchange:
  4345. case AtomicExpr::AO__atomic_compare_exchange_n:
  4346. Form = GNUCmpXchg;
  4347. break;
  4348. }
  4349. unsigned AdjustedNumArgs = NumArgs[Form];
  4350. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4351. ++AdjustedNumArgs;
  4352. // Check we have the right number of arguments.
  4353. if (Args.size() < AdjustedNumArgs) {
  4354. Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
  4355. << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
  4356. << ExprRange;
  4357. return ExprError();
  4358. } else if (Args.size() > AdjustedNumArgs) {
  4359. Diag(Args[AdjustedNumArgs]->getBeginLoc(),
  4360. diag::err_typecheck_call_too_many_args)
  4361. << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
  4362. << ExprRange;
  4363. return ExprError();
  4364. }
  4365. // Inspect the first argument of the atomic operation.
  4366. Expr *Ptr = Args[0];
  4367. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4368. if (ConvertedPtr.isInvalid())
  4369. return ExprError();
  4370. Ptr = ConvertedPtr.get();
  4371. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4372. if (!pointerType) {
  4373. Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
  4374. << Ptr->getType() << Ptr->getSourceRange();
  4375. return ExprError();
  4376. }
  4377. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4378. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4379. QualType ValType = AtomTy; // 'C'
  4380. if (IsC11) {
  4381. if (!AtomTy->isAtomicType()) {
  4382. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
  4383. << Ptr->getType() << Ptr->getSourceRange();
  4384. return ExprError();
  4385. }
  4386. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4387. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4388. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
  4389. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4390. << Ptr->getSourceRange();
  4391. return ExprError();
  4392. }
  4393. ValType = AtomTy->castAs<AtomicType>()->getValueType();
  4394. } else if (Form != Load && Form != LoadCopy) {
  4395. if (ValType.isConstQualified()) {
  4396. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
  4397. << Ptr->getType() << Ptr->getSourceRange();
  4398. return ExprError();
  4399. }
  4400. }
  4401. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4402. if (Form == Arithmetic) {
  4403. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4404. if (IsAddSub && !ValType->isIntegerType()
  4405. && !ValType->isPointerType()) {
  4406. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4407. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4408. return ExprError();
  4409. }
  4410. if (IsMinMax) {
  4411. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4412. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4413. BT->getKind() != BuiltinType::UInt)) {
  4414. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_int32_or_ptr);
  4415. return ExprError();
  4416. }
  4417. }
  4418. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4419. Diag(ExprRange.getBegin(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4420. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4421. return ExprError();
  4422. }
  4423. if (IsC11 && ValType->isPointerType() &&
  4424. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  4425. diag::err_incomplete_type)) {
  4426. return ExprError();
  4427. }
  4428. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4429. // For __atomic_*_n operations, the value type must be a scalar integral or
  4430. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4431. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4432. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4433. return ExprError();
  4434. }
  4435. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4436. !AtomTy->isScalarType()) {
  4437. // For GNU atomics, require a trivially-copyable type. This is not part of
  4438. // the GNU atomics specification, but we enforce it for sanity.
  4439. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
  4440. << Ptr->getType() << Ptr->getSourceRange();
  4441. return ExprError();
  4442. }
  4443. switch (ValType.getObjCLifetime()) {
  4444. case Qualifiers::OCL_None:
  4445. case Qualifiers::OCL_ExplicitNone:
  4446. // okay
  4447. break;
  4448. case Qualifiers::OCL_Weak:
  4449. case Qualifiers::OCL_Strong:
  4450. case Qualifiers::OCL_Autoreleasing:
  4451. // FIXME: Can this happen? By this point, ValType should be known
  4452. // to be trivially copyable.
  4453. Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
  4454. << ValType << Ptr->getSourceRange();
  4455. return ExprError();
  4456. }
  4457. // All atomic operations have an overload which takes a pointer to a volatile
  4458. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4459. // into the result or the other operands. Similarly atomic_load takes a
  4460. // pointer to a const 'A'.
  4461. ValType.removeLocalVolatile();
  4462. ValType.removeLocalConst();
  4463. QualType ResultType = ValType;
  4464. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4465. Form == Init)
  4466. ResultType = Context.VoidTy;
  4467. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4468. ResultType = Context.BoolTy;
  4469. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4470. // arguments are actually passed as pointers.
  4471. QualType ByValType = ValType; // 'CP'
  4472. bool IsPassedByAddress = false;
  4473. if (!IsC11 && !IsN) {
  4474. ByValType = Ptr->getType();
  4475. IsPassedByAddress = true;
  4476. }
  4477. SmallVector<Expr *, 5> APIOrderedArgs;
  4478. if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
  4479. APIOrderedArgs.push_back(Args[0]);
  4480. switch (Form) {
  4481. case Init:
  4482. case Load:
  4483. APIOrderedArgs.push_back(Args[1]); // Val1/Order
  4484. break;
  4485. case LoadCopy:
  4486. case Copy:
  4487. case Arithmetic:
  4488. case Xchg:
  4489. APIOrderedArgs.push_back(Args[2]); // Val1
  4490. APIOrderedArgs.push_back(Args[1]); // Order
  4491. break;
  4492. case GNUXchg:
  4493. APIOrderedArgs.push_back(Args[2]); // Val1
  4494. APIOrderedArgs.push_back(Args[3]); // Val2
  4495. APIOrderedArgs.push_back(Args[1]); // Order
  4496. break;
  4497. case C11CmpXchg:
  4498. APIOrderedArgs.push_back(Args[2]); // Val1
  4499. APIOrderedArgs.push_back(Args[4]); // Val2
  4500. APIOrderedArgs.push_back(Args[1]); // Order
  4501. APIOrderedArgs.push_back(Args[3]); // OrderFail
  4502. break;
  4503. case GNUCmpXchg:
  4504. APIOrderedArgs.push_back(Args[2]); // Val1
  4505. APIOrderedArgs.push_back(Args[4]); // Val2
  4506. APIOrderedArgs.push_back(Args[5]); // Weak
  4507. APIOrderedArgs.push_back(Args[1]); // Order
  4508. APIOrderedArgs.push_back(Args[3]); // OrderFail
  4509. break;
  4510. }
  4511. } else
  4512. APIOrderedArgs.append(Args.begin(), Args.end());
  4513. // The first argument's non-CV pointer type is used to deduce the type of
  4514. // subsequent arguments, except for:
  4515. // - weak flag (always converted to bool)
  4516. // - memory order (always converted to int)
  4517. // - scope (always converted to int)
  4518. for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
  4519. QualType Ty;
  4520. if (i < NumVals[Form] + 1) {
  4521. switch (i) {
  4522. case 0:
  4523. // The first argument is always a pointer. It has a fixed type.
  4524. // It is always dereferenced, a nullptr is undefined.
  4525. CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
  4526. // Nothing else to do: we already know all we want about this pointer.
  4527. continue;
  4528. case 1:
  4529. // The second argument is the non-atomic operand. For arithmetic, this
  4530. // is always passed by value, and for a compare_exchange it is always
  4531. // passed by address. For the rest, GNU uses by-address and C11 uses
  4532. // by-value.
  4533. assert(Form != Load);
  4534. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4535. Ty = ValType;
  4536. else if (Form == Copy || Form == Xchg) {
  4537. if (IsPassedByAddress) {
  4538. // The value pointer is always dereferenced, a nullptr is undefined.
  4539. CheckNonNullArgument(*this, APIOrderedArgs[i],
  4540. ExprRange.getBegin());
  4541. }
  4542. Ty = ByValType;
  4543. } else if (Form == Arithmetic)
  4544. Ty = Context.getPointerDiffType();
  4545. else {
  4546. Expr *ValArg = APIOrderedArgs[i];
  4547. // The value pointer is always dereferenced, a nullptr is undefined.
  4548. CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
  4549. LangAS AS = LangAS::Default;
  4550. // Keep address space of non-atomic pointer type.
  4551. if (const PointerType *PtrTy =
  4552. ValArg->getType()->getAs<PointerType>()) {
  4553. AS = PtrTy->getPointeeType().getAddressSpace();
  4554. }
  4555. Ty = Context.getPointerType(
  4556. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4557. }
  4558. break;
  4559. case 2:
  4560. // The third argument to compare_exchange / GNU exchange is the desired
  4561. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4562. if (IsPassedByAddress)
  4563. CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
  4564. Ty = ByValType;
  4565. break;
  4566. case 3:
  4567. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4568. Ty = Context.BoolTy;
  4569. break;
  4570. }
  4571. } else {
  4572. // The order(s) and scope are always converted to int.
  4573. Ty = Context.IntTy;
  4574. }
  4575. InitializedEntity Entity =
  4576. InitializedEntity::InitializeParameter(Context, Ty, false);
  4577. ExprResult Arg = APIOrderedArgs[i];
  4578. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4579. if (Arg.isInvalid())
  4580. return true;
  4581. APIOrderedArgs[i] = Arg.get();
  4582. }
  4583. // Permute the arguments into a 'consistent' order.
  4584. SmallVector<Expr*, 5> SubExprs;
  4585. SubExprs.push_back(Ptr);
  4586. switch (Form) {
  4587. case Init:
  4588. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4589. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4590. break;
  4591. case Load:
  4592. SubExprs.push_back(APIOrderedArgs[1]); // Order
  4593. break;
  4594. case LoadCopy:
  4595. case Copy:
  4596. case Arithmetic:
  4597. case Xchg:
  4598. SubExprs.push_back(APIOrderedArgs[2]); // Order
  4599. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4600. break;
  4601. case GNUXchg:
  4602. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4603. SubExprs.push_back(APIOrderedArgs[3]); // Order
  4604. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4605. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  4606. break;
  4607. case C11CmpXchg:
  4608. SubExprs.push_back(APIOrderedArgs[3]); // Order
  4609. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4610. SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
  4611. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  4612. break;
  4613. case GNUCmpXchg:
  4614. SubExprs.push_back(APIOrderedArgs[4]); // Order
  4615. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  4616. SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
  4617. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  4618. SubExprs.push_back(APIOrderedArgs[3]); // Weak
  4619. break;
  4620. }
  4621. if (SubExprs.size() >= 2 && Form != Init) {
  4622. llvm::APSInt Result(32);
  4623. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4624. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4625. Diag(SubExprs[1]->getBeginLoc(),
  4626. diag::warn_atomic_op_has_invalid_memory_order)
  4627. << SubExprs[1]->getSourceRange();
  4628. }
  4629. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4630. auto *Scope = Args[Args.size() - 1];
  4631. llvm::APSInt Result(32);
  4632. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4633. !ScopeModel->isValid(Result.getZExtValue())) {
  4634. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  4635. << Scope->getSourceRange();
  4636. }
  4637. SubExprs.push_back(Scope);
  4638. }
  4639. AtomicExpr *AE = new (Context)
  4640. AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
  4641. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4642. Op == AtomicExpr::AO__c11_atomic_store ||
  4643. Op == AtomicExpr::AO__opencl_atomic_load ||
  4644. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4645. Context.AtomicUsesUnsupportedLibcall(AE))
  4646. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  4647. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4648. Op == AtomicExpr::AO__opencl_atomic_load)
  4649. ? 0
  4650. : 1);
  4651. return AE;
  4652. }
  4653. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4654. /// normal type-checking on the given argument, updating the call in
  4655. /// place. This is useful when a builtin function requires custom
  4656. /// type-checking for some of its arguments but not necessarily all of
  4657. /// them.
  4658. ///
  4659. /// Returns true on error.
  4660. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4661. FunctionDecl *Fn = E->getDirectCallee();
  4662. assert(Fn && "builtin call without direct callee!");
  4663. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4664. InitializedEntity Entity =
  4665. InitializedEntity::InitializeParameter(S.Context, Param);
  4666. ExprResult Arg = E->getArg(0);
  4667. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4668. if (Arg.isInvalid())
  4669. return true;
  4670. E->setArg(ArgIndex, Arg.get());
  4671. return false;
  4672. }
  4673. /// We have a call to a function like __sync_fetch_and_add, which is an
  4674. /// overloaded function based on the pointer type of its first argument.
  4675. /// The main BuildCallExpr routines have already promoted the types of
  4676. /// arguments because all of these calls are prototyped as void(...).
  4677. ///
  4678. /// This function goes through and does final semantic checking for these
  4679. /// builtins, as well as generating any warnings.
  4680. ExprResult
  4681. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4682. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  4683. Expr *Callee = TheCall->getCallee();
  4684. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  4685. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4686. // Ensure that we have at least one argument to do type inference from.
  4687. if (TheCall->getNumArgs() < 1) {
  4688. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4689. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  4690. return ExprError();
  4691. }
  4692. // Inspect the first argument of the atomic builtin. This should always be
  4693. // a pointer type, whose element is an integral scalar or pointer type.
  4694. // Because it is a pointer type, we don't have to worry about any implicit
  4695. // casts here.
  4696. // FIXME: We don't allow floating point scalars as input.
  4697. Expr *FirstArg = TheCall->getArg(0);
  4698. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4699. if (FirstArgResult.isInvalid())
  4700. return ExprError();
  4701. FirstArg = FirstArgResult.get();
  4702. TheCall->setArg(0, FirstArg);
  4703. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4704. if (!pointerType) {
  4705. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4706. << FirstArg->getType() << FirstArg->getSourceRange();
  4707. return ExprError();
  4708. }
  4709. QualType ValType = pointerType->getPointeeType();
  4710. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4711. !ValType->isBlockPointerType()) {
  4712. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4713. << FirstArg->getType() << FirstArg->getSourceRange();
  4714. return ExprError();
  4715. }
  4716. if (ValType.isConstQualified()) {
  4717. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  4718. << FirstArg->getType() << FirstArg->getSourceRange();
  4719. return ExprError();
  4720. }
  4721. switch (ValType.getObjCLifetime()) {
  4722. case Qualifiers::OCL_None:
  4723. case Qualifiers::OCL_ExplicitNone:
  4724. // okay
  4725. break;
  4726. case Qualifiers::OCL_Weak:
  4727. case Qualifiers::OCL_Strong:
  4728. case Qualifiers::OCL_Autoreleasing:
  4729. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4730. << ValType << FirstArg->getSourceRange();
  4731. return ExprError();
  4732. }
  4733. // Strip any qualifiers off ValType.
  4734. ValType = ValType.getUnqualifiedType();
  4735. // The majority of builtins return a value, but a few have special return
  4736. // types, so allow them to override appropriately below.
  4737. QualType ResultType = ValType;
  4738. // We need to figure out which concrete builtin this maps onto. For example,
  4739. // __sync_fetch_and_add with a 2 byte object turns into
  4740. // __sync_fetch_and_add_2.
  4741. #define BUILTIN_ROW(x) \
  4742. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4743. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4744. static const unsigned BuiltinIndices[][5] = {
  4745. BUILTIN_ROW(__sync_fetch_and_add),
  4746. BUILTIN_ROW(__sync_fetch_and_sub),
  4747. BUILTIN_ROW(__sync_fetch_and_or),
  4748. BUILTIN_ROW(__sync_fetch_and_and),
  4749. BUILTIN_ROW(__sync_fetch_and_xor),
  4750. BUILTIN_ROW(__sync_fetch_and_nand),
  4751. BUILTIN_ROW(__sync_add_and_fetch),
  4752. BUILTIN_ROW(__sync_sub_and_fetch),
  4753. BUILTIN_ROW(__sync_and_and_fetch),
  4754. BUILTIN_ROW(__sync_or_and_fetch),
  4755. BUILTIN_ROW(__sync_xor_and_fetch),
  4756. BUILTIN_ROW(__sync_nand_and_fetch),
  4757. BUILTIN_ROW(__sync_val_compare_and_swap),
  4758. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4759. BUILTIN_ROW(__sync_lock_test_and_set),
  4760. BUILTIN_ROW(__sync_lock_release),
  4761. BUILTIN_ROW(__sync_swap)
  4762. };
  4763. #undef BUILTIN_ROW
  4764. // Determine the index of the size.
  4765. unsigned SizeIndex;
  4766. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4767. case 1: SizeIndex = 0; break;
  4768. case 2: SizeIndex = 1; break;
  4769. case 4: SizeIndex = 2; break;
  4770. case 8: SizeIndex = 3; break;
  4771. case 16: SizeIndex = 4; break;
  4772. default:
  4773. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  4774. << FirstArg->getType() << FirstArg->getSourceRange();
  4775. return ExprError();
  4776. }
  4777. // Each of these builtins has one pointer argument, followed by some number of
  4778. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4779. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4780. // as the number of fixed args.
  4781. unsigned BuiltinID = FDecl->getBuiltinID();
  4782. unsigned BuiltinIndex, NumFixed = 1;
  4783. bool WarnAboutSemanticsChange = false;
  4784. switch (BuiltinID) {
  4785. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4786. case Builtin::BI__sync_fetch_and_add:
  4787. case Builtin::BI__sync_fetch_and_add_1:
  4788. case Builtin::BI__sync_fetch_and_add_2:
  4789. case Builtin::BI__sync_fetch_and_add_4:
  4790. case Builtin::BI__sync_fetch_and_add_8:
  4791. case Builtin::BI__sync_fetch_and_add_16:
  4792. BuiltinIndex = 0;
  4793. break;
  4794. case Builtin::BI__sync_fetch_and_sub:
  4795. case Builtin::BI__sync_fetch_and_sub_1:
  4796. case Builtin::BI__sync_fetch_and_sub_2:
  4797. case Builtin::BI__sync_fetch_and_sub_4:
  4798. case Builtin::BI__sync_fetch_and_sub_8:
  4799. case Builtin::BI__sync_fetch_and_sub_16:
  4800. BuiltinIndex = 1;
  4801. break;
  4802. case Builtin::BI__sync_fetch_and_or:
  4803. case Builtin::BI__sync_fetch_and_or_1:
  4804. case Builtin::BI__sync_fetch_and_or_2:
  4805. case Builtin::BI__sync_fetch_and_or_4:
  4806. case Builtin::BI__sync_fetch_and_or_8:
  4807. case Builtin::BI__sync_fetch_and_or_16:
  4808. BuiltinIndex = 2;
  4809. break;
  4810. case Builtin::BI__sync_fetch_and_and:
  4811. case Builtin::BI__sync_fetch_and_and_1:
  4812. case Builtin::BI__sync_fetch_and_and_2:
  4813. case Builtin::BI__sync_fetch_and_and_4:
  4814. case Builtin::BI__sync_fetch_and_and_8:
  4815. case Builtin::BI__sync_fetch_and_and_16:
  4816. BuiltinIndex = 3;
  4817. break;
  4818. case Builtin::BI__sync_fetch_and_xor:
  4819. case Builtin::BI__sync_fetch_and_xor_1:
  4820. case Builtin::BI__sync_fetch_and_xor_2:
  4821. case Builtin::BI__sync_fetch_and_xor_4:
  4822. case Builtin::BI__sync_fetch_and_xor_8:
  4823. case Builtin::BI__sync_fetch_and_xor_16:
  4824. BuiltinIndex = 4;
  4825. break;
  4826. case Builtin::BI__sync_fetch_and_nand:
  4827. case Builtin::BI__sync_fetch_and_nand_1:
  4828. case Builtin::BI__sync_fetch_and_nand_2:
  4829. case Builtin::BI__sync_fetch_and_nand_4:
  4830. case Builtin::BI__sync_fetch_and_nand_8:
  4831. case Builtin::BI__sync_fetch_and_nand_16:
  4832. BuiltinIndex = 5;
  4833. WarnAboutSemanticsChange = true;
  4834. break;
  4835. case Builtin::BI__sync_add_and_fetch:
  4836. case Builtin::BI__sync_add_and_fetch_1:
  4837. case Builtin::BI__sync_add_and_fetch_2:
  4838. case Builtin::BI__sync_add_and_fetch_4:
  4839. case Builtin::BI__sync_add_and_fetch_8:
  4840. case Builtin::BI__sync_add_and_fetch_16:
  4841. BuiltinIndex = 6;
  4842. break;
  4843. case Builtin::BI__sync_sub_and_fetch:
  4844. case Builtin::BI__sync_sub_and_fetch_1:
  4845. case Builtin::BI__sync_sub_and_fetch_2:
  4846. case Builtin::BI__sync_sub_and_fetch_4:
  4847. case Builtin::BI__sync_sub_and_fetch_8:
  4848. case Builtin::BI__sync_sub_and_fetch_16:
  4849. BuiltinIndex = 7;
  4850. break;
  4851. case Builtin::BI__sync_and_and_fetch:
  4852. case Builtin::BI__sync_and_and_fetch_1:
  4853. case Builtin::BI__sync_and_and_fetch_2:
  4854. case Builtin::BI__sync_and_and_fetch_4:
  4855. case Builtin::BI__sync_and_and_fetch_8:
  4856. case Builtin::BI__sync_and_and_fetch_16:
  4857. BuiltinIndex = 8;
  4858. break;
  4859. case Builtin::BI__sync_or_and_fetch:
  4860. case Builtin::BI__sync_or_and_fetch_1:
  4861. case Builtin::BI__sync_or_and_fetch_2:
  4862. case Builtin::BI__sync_or_and_fetch_4:
  4863. case Builtin::BI__sync_or_and_fetch_8:
  4864. case Builtin::BI__sync_or_and_fetch_16:
  4865. BuiltinIndex = 9;
  4866. break;
  4867. case Builtin::BI__sync_xor_and_fetch:
  4868. case Builtin::BI__sync_xor_and_fetch_1:
  4869. case Builtin::BI__sync_xor_and_fetch_2:
  4870. case Builtin::BI__sync_xor_and_fetch_4:
  4871. case Builtin::BI__sync_xor_and_fetch_8:
  4872. case Builtin::BI__sync_xor_and_fetch_16:
  4873. BuiltinIndex = 10;
  4874. break;
  4875. case Builtin::BI__sync_nand_and_fetch:
  4876. case Builtin::BI__sync_nand_and_fetch_1:
  4877. case Builtin::BI__sync_nand_and_fetch_2:
  4878. case Builtin::BI__sync_nand_and_fetch_4:
  4879. case Builtin::BI__sync_nand_and_fetch_8:
  4880. case Builtin::BI__sync_nand_and_fetch_16:
  4881. BuiltinIndex = 11;
  4882. WarnAboutSemanticsChange = true;
  4883. break;
  4884. case Builtin::BI__sync_val_compare_and_swap:
  4885. case Builtin::BI__sync_val_compare_and_swap_1:
  4886. case Builtin::BI__sync_val_compare_and_swap_2:
  4887. case Builtin::BI__sync_val_compare_and_swap_4:
  4888. case Builtin::BI__sync_val_compare_and_swap_8:
  4889. case Builtin::BI__sync_val_compare_and_swap_16:
  4890. BuiltinIndex = 12;
  4891. NumFixed = 2;
  4892. break;
  4893. case Builtin::BI__sync_bool_compare_and_swap:
  4894. case Builtin::BI__sync_bool_compare_and_swap_1:
  4895. case Builtin::BI__sync_bool_compare_and_swap_2:
  4896. case Builtin::BI__sync_bool_compare_and_swap_4:
  4897. case Builtin::BI__sync_bool_compare_and_swap_8:
  4898. case Builtin::BI__sync_bool_compare_and_swap_16:
  4899. BuiltinIndex = 13;
  4900. NumFixed = 2;
  4901. ResultType = Context.BoolTy;
  4902. break;
  4903. case Builtin::BI__sync_lock_test_and_set:
  4904. case Builtin::BI__sync_lock_test_and_set_1:
  4905. case Builtin::BI__sync_lock_test_and_set_2:
  4906. case Builtin::BI__sync_lock_test_and_set_4:
  4907. case Builtin::BI__sync_lock_test_and_set_8:
  4908. case Builtin::BI__sync_lock_test_and_set_16:
  4909. BuiltinIndex = 14;
  4910. break;
  4911. case Builtin::BI__sync_lock_release:
  4912. case Builtin::BI__sync_lock_release_1:
  4913. case Builtin::BI__sync_lock_release_2:
  4914. case Builtin::BI__sync_lock_release_4:
  4915. case Builtin::BI__sync_lock_release_8:
  4916. case Builtin::BI__sync_lock_release_16:
  4917. BuiltinIndex = 15;
  4918. NumFixed = 0;
  4919. ResultType = Context.VoidTy;
  4920. break;
  4921. case Builtin::BI__sync_swap:
  4922. case Builtin::BI__sync_swap_1:
  4923. case Builtin::BI__sync_swap_2:
  4924. case Builtin::BI__sync_swap_4:
  4925. case Builtin::BI__sync_swap_8:
  4926. case Builtin::BI__sync_swap_16:
  4927. BuiltinIndex = 16;
  4928. break;
  4929. }
  4930. // Now that we know how many fixed arguments we expect, first check that we
  4931. // have at least that many.
  4932. if (TheCall->getNumArgs() < 1+NumFixed) {
  4933. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4934. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  4935. << Callee->getSourceRange();
  4936. return ExprError();
  4937. }
  4938. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  4939. << Callee->getSourceRange();
  4940. if (WarnAboutSemanticsChange) {
  4941. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  4942. << Callee->getSourceRange();
  4943. }
  4944. // Get the decl for the concrete builtin from this, we can tell what the
  4945. // concrete integer type we should convert to is.
  4946. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4947. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4948. FunctionDecl *NewBuiltinDecl;
  4949. if (NewBuiltinID == BuiltinID)
  4950. NewBuiltinDecl = FDecl;
  4951. else {
  4952. // Perform builtin lookup to avoid redeclaring it.
  4953. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4954. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  4955. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4956. assert(Res.getFoundDecl());
  4957. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4958. if (!NewBuiltinDecl)
  4959. return ExprError();
  4960. }
  4961. // The first argument --- the pointer --- has a fixed type; we
  4962. // deduce the types of the rest of the arguments accordingly. Walk
  4963. // the remaining arguments, converting them to the deduced value type.
  4964. for (unsigned i = 0; i != NumFixed; ++i) {
  4965. ExprResult Arg = TheCall->getArg(i+1);
  4966. // GCC does an implicit conversion to the pointer or integer ValType. This
  4967. // can fail in some cases (1i -> int**), check for this error case now.
  4968. // Initialize the argument.
  4969. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4970. ValType, /*consume*/ false);
  4971. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4972. if (Arg.isInvalid())
  4973. return ExprError();
  4974. // Okay, we have something that *can* be converted to the right type. Check
  4975. // to see if there is a potentially weird extension going on here. This can
  4976. // happen when you do an atomic operation on something like an char* and
  4977. // pass in 42. The 42 gets converted to char. This is even more strange
  4978. // for things like 45.123 -> char, etc.
  4979. // FIXME: Do this check.
  4980. TheCall->setArg(i+1, Arg.get());
  4981. }
  4982. // Create a new DeclRefExpr to refer to the new decl.
  4983. DeclRefExpr *NewDRE = DeclRefExpr::Create(
  4984. Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
  4985. /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
  4986. DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
  4987. // Set the callee in the CallExpr.
  4988. // FIXME: This loses syntactic information.
  4989. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4990. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4991. CK_BuiltinFnToFnPtr);
  4992. TheCall->setCallee(PromotedCall.get());
  4993. // Change the result type of the call to match the original value type. This
  4994. // is arbitrary, but the codegen for these builtins ins design to handle it
  4995. // gracefully.
  4996. TheCall->setType(ResultType);
  4997. return TheCallResult;
  4998. }
  4999. /// SemaBuiltinNontemporalOverloaded - We have a call to
  5000. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  5001. /// overloaded function based on the pointer type of its last argument.
  5002. ///
  5003. /// This function goes through and does final semantic checking for these
  5004. /// builtins.
  5005. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  5006. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  5007. DeclRefExpr *DRE =
  5008. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5009. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5010. unsigned BuiltinID = FDecl->getBuiltinID();
  5011. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  5012. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  5013. "Unexpected nontemporal load/store builtin!");
  5014. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  5015. unsigned numArgs = isStore ? 2 : 1;
  5016. // Ensure that we have the proper number of arguments.
  5017. if (checkArgCount(*this, TheCall, numArgs))
  5018. return ExprError();
  5019. // Inspect the last argument of the nontemporal builtin. This should always
  5020. // be a pointer type, from which we imply the type of the memory access.
  5021. // Because it is a pointer type, we don't have to worry about any implicit
  5022. // casts here.
  5023. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  5024. ExprResult PointerArgResult =
  5025. DefaultFunctionArrayLvalueConversion(PointerArg);
  5026. if (PointerArgResult.isInvalid())
  5027. return ExprError();
  5028. PointerArg = PointerArgResult.get();
  5029. TheCall->setArg(numArgs - 1, PointerArg);
  5030. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  5031. if (!pointerType) {
  5032. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  5033. << PointerArg->getType() << PointerArg->getSourceRange();
  5034. return ExprError();
  5035. }
  5036. QualType ValType = pointerType->getPointeeType();
  5037. // Strip any qualifiers off ValType.
  5038. ValType = ValType.getUnqualifiedType();
  5039. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  5040. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  5041. !ValType->isVectorType()) {
  5042. Diag(DRE->getBeginLoc(),
  5043. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  5044. << PointerArg->getType() << PointerArg->getSourceRange();
  5045. return ExprError();
  5046. }
  5047. if (!isStore) {
  5048. TheCall->setType(ValType);
  5049. return TheCallResult;
  5050. }
  5051. ExprResult ValArg = TheCall->getArg(0);
  5052. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5053. Context, ValType, /*consume*/ false);
  5054. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  5055. if (ValArg.isInvalid())
  5056. return ExprError();
  5057. TheCall->setArg(0, ValArg.get());
  5058. TheCall->setType(Context.VoidTy);
  5059. return TheCallResult;
  5060. }
  5061. /// CheckObjCString - Checks that the argument to the builtin
  5062. /// CFString constructor is correct
  5063. /// Note: It might also make sense to do the UTF-16 conversion here (would
  5064. /// simplify the backend).
  5065. bool Sema::CheckObjCString(Expr *Arg) {
  5066. Arg = Arg->IgnoreParenCasts();
  5067. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  5068. if (!Literal || !Literal->isAscii()) {
  5069. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  5070. << Arg->getSourceRange();
  5071. return true;
  5072. }
  5073. if (Literal->containsNonAsciiOrNull()) {
  5074. StringRef String = Literal->getString();
  5075. unsigned NumBytes = String.size();
  5076. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  5077. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  5078. llvm::UTF16 *ToPtr = &ToBuf[0];
  5079. llvm::ConversionResult Result =
  5080. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  5081. ToPtr + NumBytes, llvm::strictConversion);
  5082. // Check for conversion failure.
  5083. if (Result != llvm::conversionOK)
  5084. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  5085. << Arg->getSourceRange();
  5086. }
  5087. return false;
  5088. }
  5089. /// CheckObjCString - Checks that the format string argument to the os_log()
  5090. /// and os_trace() functions is correct, and converts it to const char *.
  5091. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  5092. Arg = Arg->IgnoreParenCasts();
  5093. auto *Literal = dyn_cast<StringLiteral>(Arg);
  5094. if (!Literal) {
  5095. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  5096. Literal = ObjcLiteral->getString();
  5097. }
  5098. }
  5099. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  5100. return ExprError(
  5101. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  5102. << Arg->getSourceRange());
  5103. }
  5104. ExprResult Result(Literal);
  5105. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  5106. InitializedEntity Entity =
  5107. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  5108. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  5109. return Result;
  5110. }
  5111. /// Check that the user is calling the appropriate va_start builtin for the
  5112. /// target and calling convention.
  5113. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  5114. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  5115. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  5116. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  5117. bool IsWindows = TT.isOSWindows();
  5118. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  5119. if (IsX64 || IsAArch64) {
  5120. CallingConv CC = CC_C;
  5121. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  5122. CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  5123. if (IsMSVAStart) {
  5124. // Don't allow this in System V ABI functions.
  5125. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  5126. return S.Diag(Fn->getBeginLoc(),
  5127. diag::err_ms_va_start_used_in_sysv_function);
  5128. } else {
  5129. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  5130. // On x64 Windows, don't allow this in System V ABI functions.
  5131. // (Yes, that means there's no corresponding way to support variadic
  5132. // System V ABI functions on Windows.)
  5133. if ((IsWindows && CC == CC_X86_64SysV) ||
  5134. (!IsWindows && CC == CC_Win64))
  5135. return S.Diag(Fn->getBeginLoc(),
  5136. diag::err_va_start_used_in_wrong_abi_function)
  5137. << !IsWindows;
  5138. }
  5139. return false;
  5140. }
  5141. if (IsMSVAStart)
  5142. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  5143. return false;
  5144. }
  5145. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  5146. ParmVarDecl **LastParam = nullptr) {
  5147. // Determine whether the current function, block, or obj-c method is variadic
  5148. // and get its parameter list.
  5149. bool IsVariadic = false;
  5150. ArrayRef<ParmVarDecl *> Params;
  5151. DeclContext *Caller = S.CurContext;
  5152. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  5153. IsVariadic = Block->isVariadic();
  5154. Params = Block->parameters();
  5155. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  5156. IsVariadic = FD->isVariadic();
  5157. Params = FD->parameters();
  5158. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  5159. IsVariadic = MD->isVariadic();
  5160. // FIXME: This isn't correct for methods (results in bogus warning).
  5161. Params = MD->parameters();
  5162. } else if (isa<CapturedDecl>(Caller)) {
  5163. // We don't support va_start in a CapturedDecl.
  5164. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  5165. return true;
  5166. } else {
  5167. // This must be some other declcontext that parses exprs.
  5168. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  5169. return true;
  5170. }
  5171. if (!IsVariadic) {
  5172. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  5173. return true;
  5174. }
  5175. if (LastParam)
  5176. *LastParam = Params.empty() ? nullptr : Params.back();
  5177. return false;
  5178. }
  5179. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  5180. /// for validity. Emit an error and return true on failure; return false
  5181. /// on success.
  5182. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  5183. Expr *Fn = TheCall->getCallee();
  5184. if (checkVAStartABI(*this, BuiltinID, Fn))
  5185. return true;
  5186. if (TheCall->getNumArgs() > 2) {
  5187. Diag(TheCall->getArg(2)->getBeginLoc(),
  5188. diag::err_typecheck_call_too_many_args)
  5189. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5190. << Fn->getSourceRange()
  5191. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5192. (*(TheCall->arg_end() - 1))->getEndLoc());
  5193. return true;
  5194. }
  5195. if (TheCall->getNumArgs() < 2) {
  5196. return Diag(TheCall->getEndLoc(),
  5197. diag::err_typecheck_call_too_few_args_at_least)
  5198. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  5199. }
  5200. // Type-check the first argument normally.
  5201. if (checkBuiltinArgument(*this, TheCall, 0))
  5202. return true;
  5203. // Check that the current function is variadic, and get its last parameter.
  5204. ParmVarDecl *LastParam;
  5205. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  5206. return true;
  5207. // Verify that the second argument to the builtin is the last argument of the
  5208. // current function or method.
  5209. bool SecondArgIsLastNamedArgument = false;
  5210. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  5211. // These are valid if SecondArgIsLastNamedArgument is false after the next
  5212. // block.
  5213. QualType Type;
  5214. SourceLocation ParamLoc;
  5215. bool IsCRegister = false;
  5216. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  5217. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  5218. SecondArgIsLastNamedArgument = PV == LastParam;
  5219. Type = PV->getType();
  5220. ParamLoc = PV->getLocation();
  5221. IsCRegister =
  5222. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  5223. }
  5224. }
  5225. if (!SecondArgIsLastNamedArgument)
  5226. Diag(TheCall->getArg(1)->getBeginLoc(),
  5227. diag::warn_second_arg_of_va_start_not_last_named_param);
  5228. else if (IsCRegister || Type->isReferenceType() ||
  5229. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  5230. // Promotable integers are UB, but enumerations need a bit of
  5231. // extra checking to see what their promotable type actually is.
  5232. if (!Type->isPromotableIntegerType())
  5233. return false;
  5234. if (!Type->isEnumeralType())
  5235. return true;
  5236. const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
  5237. return !(ED &&
  5238. Context.typesAreCompatible(ED->getPromotionType(), Type));
  5239. }()) {
  5240. unsigned Reason = 0;
  5241. if (Type->isReferenceType()) Reason = 1;
  5242. else if (IsCRegister) Reason = 2;
  5243. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  5244. Diag(ParamLoc, diag::note_parameter_type) << Type;
  5245. }
  5246. TheCall->setType(Context.VoidTy);
  5247. return false;
  5248. }
  5249. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  5250. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  5251. // const char *named_addr);
  5252. Expr *Func = Call->getCallee();
  5253. if (Call->getNumArgs() < 3)
  5254. return Diag(Call->getEndLoc(),
  5255. diag::err_typecheck_call_too_few_args_at_least)
  5256. << 0 /*function call*/ << 3 << Call->getNumArgs();
  5257. // Type-check the first argument normally.
  5258. if (checkBuiltinArgument(*this, Call, 0))
  5259. return true;
  5260. // Check that the current function is variadic.
  5261. if (checkVAStartIsInVariadicFunction(*this, Func))
  5262. return true;
  5263. // __va_start on Windows does not validate the parameter qualifiers
  5264. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  5265. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  5266. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  5267. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  5268. const QualType &ConstCharPtrTy =
  5269. Context.getPointerType(Context.CharTy.withConst());
  5270. if (!Arg1Ty->isPointerType() ||
  5271. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  5272. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5273. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  5274. << 0 /* qualifier difference */
  5275. << 3 /* parameter mismatch */
  5276. << 2 << Arg1->getType() << ConstCharPtrTy;
  5277. const QualType SizeTy = Context.getSizeType();
  5278. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  5279. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5280. << Arg2->getType() << SizeTy << 1 /* different class */
  5281. << 0 /* qualifier difference */
  5282. << 3 /* parameter mismatch */
  5283. << 3 << Arg2->getType() << SizeTy;
  5284. return false;
  5285. }
  5286. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  5287. /// friends. This is declared to take (...), so we have to check everything.
  5288. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  5289. if (TheCall->getNumArgs() < 2)
  5290. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5291. << 0 << 2 << TheCall->getNumArgs() /*function call*/;
  5292. if (TheCall->getNumArgs() > 2)
  5293. return Diag(TheCall->getArg(2)->getBeginLoc(),
  5294. diag::err_typecheck_call_too_many_args)
  5295. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5296. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5297. (*(TheCall->arg_end() - 1))->getEndLoc());
  5298. ExprResult OrigArg0 = TheCall->getArg(0);
  5299. ExprResult OrigArg1 = TheCall->getArg(1);
  5300. // Do standard promotions between the two arguments, returning their common
  5301. // type.
  5302. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  5303. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  5304. return true;
  5305. // Make sure any conversions are pushed back into the call; this is
  5306. // type safe since unordered compare builtins are declared as "_Bool
  5307. // foo(...)".
  5308. TheCall->setArg(0, OrigArg0.get());
  5309. TheCall->setArg(1, OrigArg1.get());
  5310. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  5311. return false;
  5312. // If the common type isn't a real floating type, then the arguments were
  5313. // invalid for this operation.
  5314. if (Res.isNull() || !Res->isRealFloatingType())
  5315. return Diag(OrigArg0.get()->getBeginLoc(),
  5316. diag::err_typecheck_call_invalid_ordered_compare)
  5317. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  5318. << SourceRange(OrigArg0.get()->getBeginLoc(),
  5319. OrigArg1.get()->getEndLoc());
  5320. return false;
  5321. }
  5322. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  5323. /// __builtin_isnan and friends. This is declared to take (...), so we have
  5324. /// to check everything. We expect the last argument to be a floating point
  5325. /// value.
  5326. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  5327. if (TheCall->getNumArgs() < NumArgs)
  5328. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5329. << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
  5330. if (TheCall->getNumArgs() > NumArgs)
  5331. return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
  5332. diag::err_typecheck_call_too_many_args)
  5333. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  5334. << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
  5335. (*(TheCall->arg_end() - 1))->getEndLoc());
  5336. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  5337. if (OrigArg->isTypeDependent())
  5338. return false;
  5339. // This operation requires a non-_Complex floating-point number.
  5340. if (!OrigArg->getType()->isRealFloatingType())
  5341. return Diag(OrigArg->getBeginLoc(),
  5342. diag::err_typecheck_call_invalid_unary_fp)
  5343. << OrigArg->getType() << OrigArg->getSourceRange();
  5344. // If this is an implicit conversion from float -> float, double, or
  5345. // long double, remove it.
  5346. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  5347. // Only remove standard FloatCasts, leaving other casts inplace
  5348. if (Cast->getCastKind() == CK_FloatingCast) {
  5349. Expr *CastArg = Cast->getSubExpr();
  5350. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5351. assert(
  5352. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5353. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5354. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5355. "promotion from float to either float, double, or long double is "
  5356. "the only expected cast here");
  5357. Cast->setSubExpr(nullptr);
  5358. TheCall->setArg(NumArgs-1, CastArg);
  5359. }
  5360. }
  5361. }
  5362. return false;
  5363. }
  5364. // Customized Sema Checking for VSX builtins that have the following signature:
  5365. // vector [...] builtinName(vector [...], vector [...], const int);
  5366. // Which takes the same type of vectors (any legal vector type) for the first
  5367. // two arguments and takes compile time constant for the third argument.
  5368. // Example builtins are :
  5369. // vector double vec_xxpermdi(vector double, vector double, int);
  5370. // vector short vec_xxsldwi(vector short, vector short, int);
  5371. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5372. unsigned ExpectedNumArgs = 3;
  5373. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5374. return Diag(TheCall->getEndLoc(),
  5375. diag::err_typecheck_call_too_few_args_at_least)
  5376. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5377. << TheCall->getSourceRange();
  5378. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5379. return Diag(TheCall->getEndLoc(),
  5380. diag::err_typecheck_call_too_many_args_at_most)
  5381. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5382. << TheCall->getSourceRange();
  5383. // Check the third argument is a compile time constant
  5384. llvm::APSInt Value;
  5385. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5386. return Diag(TheCall->getBeginLoc(),
  5387. diag::err_vsx_builtin_nonconstant_argument)
  5388. << 3 /* argument index */ << TheCall->getDirectCallee()
  5389. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5390. TheCall->getArg(2)->getEndLoc());
  5391. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5392. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5393. // Check the type of argument 1 and argument 2 are vectors.
  5394. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  5395. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5396. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5397. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5398. << TheCall->getDirectCallee()
  5399. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5400. TheCall->getArg(1)->getEndLoc());
  5401. }
  5402. // Check the first two arguments are the same type.
  5403. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5404. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5405. << TheCall->getDirectCallee()
  5406. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5407. TheCall->getArg(1)->getEndLoc());
  5408. }
  5409. // When default clang type checking is turned off and the customized type
  5410. // checking is used, the returning type of the function must be explicitly
  5411. // set. Otherwise it is _Bool by default.
  5412. TheCall->setType(Arg1Ty);
  5413. return false;
  5414. }
  5415. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5416. // This is declared to take (...), so we have to check everything.
  5417. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5418. if (TheCall->getNumArgs() < 2)
  5419. return ExprError(Diag(TheCall->getEndLoc(),
  5420. diag::err_typecheck_call_too_few_args_at_least)
  5421. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5422. << TheCall->getSourceRange());
  5423. // Determine which of the following types of shufflevector we're checking:
  5424. // 1) unary, vector mask: (lhs, mask)
  5425. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5426. QualType resType = TheCall->getArg(0)->getType();
  5427. unsigned numElements = 0;
  5428. if (!TheCall->getArg(0)->isTypeDependent() &&
  5429. !TheCall->getArg(1)->isTypeDependent()) {
  5430. QualType LHSType = TheCall->getArg(0)->getType();
  5431. QualType RHSType = TheCall->getArg(1)->getType();
  5432. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5433. return ExprError(
  5434. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  5435. << TheCall->getDirectCallee()
  5436. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5437. TheCall->getArg(1)->getEndLoc()));
  5438. numElements = LHSType->castAs<VectorType>()->getNumElements();
  5439. unsigned numResElements = TheCall->getNumArgs() - 2;
  5440. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5441. // with mask. If so, verify that RHS is an integer vector type with the
  5442. // same number of elts as lhs.
  5443. if (TheCall->getNumArgs() == 2) {
  5444. if (!RHSType->hasIntegerRepresentation() ||
  5445. RHSType->castAs<VectorType>()->getNumElements() != numElements)
  5446. return ExprError(Diag(TheCall->getBeginLoc(),
  5447. diag::err_vec_builtin_incompatible_vector)
  5448. << TheCall->getDirectCallee()
  5449. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  5450. TheCall->getArg(1)->getEndLoc()));
  5451. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5452. return ExprError(Diag(TheCall->getBeginLoc(),
  5453. diag::err_vec_builtin_incompatible_vector)
  5454. << TheCall->getDirectCallee()
  5455. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5456. TheCall->getArg(1)->getEndLoc()));
  5457. } else if (numElements != numResElements) {
  5458. QualType eltType = LHSType->castAs<VectorType>()->getElementType();
  5459. resType = Context.getVectorType(eltType, numResElements,
  5460. VectorType::GenericVector);
  5461. }
  5462. }
  5463. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5464. if (TheCall->getArg(i)->isTypeDependent() ||
  5465. TheCall->getArg(i)->isValueDependent())
  5466. continue;
  5467. llvm::APSInt Result(32);
  5468. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5469. return ExprError(Diag(TheCall->getBeginLoc(),
  5470. diag::err_shufflevector_nonconstant_argument)
  5471. << TheCall->getArg(i)->getSourceRange());
  5472. // Allow -1 which will be translated to undef in the IR.
  5473. if (Result.isSigned() && Result.isAllOnesValue())
  5474. continue;
  5475. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5476. return ExprError(Diag(TheCall->getBeginLoc(),
  5477. diag::err_shufflevector_argument_too_large)
  5478. << TheCall->getArg(i)->getSourceRange());
  5479. }
  5480. SmallVector<Expr*, 32> exprs;
  5481. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5482. exprs.push_back(TheCall->getArg(i));
  5483. TheCall->setArg(i, nullptr);
  5484. }
  5485. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5486. TheCall->getCallee()->getBeginLoc(),
  5487. TheCall->getRParenLoc());
  5488. }
  5489. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5490. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5491. SourceLocation BuiltinLoc,
  5492. SourceLocation RParenLoc) {
  5493. ExprValueKind VK = VK_RValue;
  5494. ExprObjectKind OK = OK_Ordinary;
  5495. QualType DstTy = TInfo->getType();
  5496. QualType SrcTy = E->getType();
  5497. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5498. return ExprError(Diag(BuiltinLoc,
  5499. diag::err_convertvector_non_vector)
  5500. << E->getSourceRange());
  5501. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5502. return ExprError(Diag(BuiltinLoc,
  5503. diag::err_convertvector_non_vector_type));
  5504. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5505. unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
  5506. unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
  5507. if (SrcElts != DstElts)
  5508. return ExprError(Diag(BuiltinLoc,
  5509. diag::err_convertvector_incompatible_vector)
  5510. << E->getSourceRange());
  5511. }
  5512. return new (Context)
  5513. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5514. }
  5515. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5516. // This is declared to take (const void*, ...) and can take two
  5517. // optional constant int args.
  5518. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5519. unsigned NumArgs = TheCall->getNumArgs();
  5520. if (NumArgs > 3)
  5521. return Diag(TheCall->getEndLoc(),
  5522. diag::err_typecheck_call_too_many_args_at_most)
  5523. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5524. // Argument 0 is checked for us and the remaining arguments must be
  5525. // constant integers.
  5526. for (unsigned i = 1; i != NumArgs; ++i)
  5527. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5528. return true;
  5529. return false;
  5530. }
  5531. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5532. // __assume does not evaluate its arguments, and should warn if its argument
  5533. // has side effects.
  5534. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5535. Expr *Arg = TheCall->getArg(0);
  5536. if (Arg->isInstantiationDependent()) return false;
  5537. if (Arg->HasSideEffects(Context))
  5538. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  5539. << Arg->getSourceRange()
  5540. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5541. return false;
  5542. }
  5543. /// Handle __builtin_alloca_with_align. This is declared
  5544. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5545. /// than 8.
  5546. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5547. // The alignment must be a constant integer.
  5548. Expr *Arg = TheCall->getArg(1);
  5549. // We can't check the value of a dependent argument.
  5550. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5551. if (const auto *UE =
  5552. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5553. if (UE->getKind() == UETT_AlignOf ||
  5554. UE->getKind() == UETT_PreferredAlignOf)
  5555. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  5556. << Arg->getSourceRange();
  5557. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5558. if (!Result.isPowerOf2())
  5559. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5560. << Arg->getSourceRange();
  5561. if (Result < Context.getCharWidth())
  5562. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  5563. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  5564. if (Result > std::numeric_limits<int32_t>::max())
  5565. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  5566. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  5567. }
  5568. return false;
  5569. }
  5570. /// Handle __builtin_assume_aligned. This is declared
  5571. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5572. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5573. unsigned NumArgs = TheCall->getNumArgs();
  5574. if (NumArgs > 3)
  5575. return Diag(TheCall->getEndLoc(),
  5576. diag::err_typecheck_call_too_many_args_at_most)
  5577. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5578. // The alignment must be a constant integer.
  5579. Expr *Arg = TheCall->getArg(1);
  5580. // We can't check the value of a dependent argument.
  5581. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5582. llvm::APSInt Result;
  5583. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5584. return true;
  5585. if (!Result.isPowerOf2())
  5586. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5587. << Arg->getSourceRange();
  5588. // Alignment calculations can wrap around if it's greater than 2**29.
  5589. unsigned MaximumAlignment = 536870912;
  5590. if (Result > MaximumAlignment)
  5591. Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
  5592. << Arg->getSourceRange() << MaximumAlignment;
  5593. }
  5594. if (NumArgs > 2) {
  5595. ExprResult Arg(TheCall->getArg(2));
  5596. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5597. Context.getSizeType(), false);
  5598. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5599. if (Arg.isInvalid()) return true;
  5600. TheCall->setArg(2, Arg.get());
  5601. }
  5602. return false;
  5603. }
  5604. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5605. unsigned BuiltinID =
  5606. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5607. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5608. unsigned NumArgs = TheCall->getNumArgs();
  5609. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5610. if (NumArgs < NumRequiredArgs) {
  5611. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5612. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5613. << TheCall->getSourceRange();
  5614. }
  5615. if (NumArgs >= NumRequiredArgs + 0x100) {
  5616. return Diag(TheCall->getEndLoc(),
  5617. diag::err_typecheck_call_too_many_args_at_most)
  5618. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5619. << TheCall->getSourceRange();
  5620. }
  5621. unsigned i = 0;
  5622. // For formatting call, check buffer arg.
  5623. if (!IsSizeCall) {
  5624. ExprResult Arg(TheCall->getArg(i));
  5625. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5626. Context, Context.VoidPtrTy, false);
  5627. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5628. if (Arg.isInvalid())
  5629. return true;
  5630. TheCall->setArg(i, Arg.get());
  5631. i++;
  5632. }
  5633. // Check string literal arg.
  5634. unsigned FormatIdx = i;
  5635. {
  5636. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5637. if (Arg.isInvalid())
  5638. return true;
  5639. TheCall->setArg(i, Arg.get());
  5640. i++;
  5641. }
  5642. // Make sure variadic args are scalar.
  5643. unsigned FirstDataArg = i;
  5644. while (i < NumArgs) {
  5645. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5646. TheCall->getArg(i), VariadicFunction, nullptr);
  5647. if (Arg.isInvalid())
  5648. return true;
  5649. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5650. if (ArgSize.getQuantity() >= 0x100) {
  5651. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  5652. << i << (int)ArgSize.getQuantity() << 0xff
  5653. << TheCall->getSourceRange();
  5654. }
  5655. TheCall->setArg(i, Arg.get());
  5656. i++;
  5657. }
  5658. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5659. // call to avoid duplicate diagnostics.
  5660. if (!IsSizeCall) {
  5661. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5662. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5663. bool Success = CheckFormatArguments(
  5664. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5665. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  5666. CheckedVarArgs);
  5667. if (!Success)
  5668. return true;
  5669. }
  5670. if (IsSizeCall) {
  5671. TheCall->setType(Context.getSizeType());
  5672. } else {
  5673. TheCall->setType(Context.VoidPtrTy);
  5674. }
  5675. return false;
  5676. }
  5677. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5678. /// TheCall is a constant expression.
  5679. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5680. llvm::APSInt &Result) {
  5681. Expr *Arg = TheCall->getArg(ArgNum);
  5682. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5683. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5684. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5685. if (!Arg->isIntegerConstantExpr(Result, Context))
  5686. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  5687. << FDecl->getDeclName() << Arg->getSourceRange();
  5688. return false;
  5689. }
  5690. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5691. /// TheCall is a constant expression in the range [Low, High].
  5692. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5693. int Low, int High, bool RangeIsError) {
  5694. if (isConstantEvaluated())
  5695. return false;
  5696. llvm::APSInt Result;
  5697. // We can't check the value of a dependent argument.
  5698. Expr *Arg = TheCall->getArg(ArgNum);
  5699. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5700. return false;
  5701. // Check constant-ness first.
  5702. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5703. return true;
  5704. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5705. if (RangeIsError)
  5706. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  5707. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5708. else
  5709. // Defer the warning until we know if the code will be emitted so that
  5710. // dead code can ignore this.
  5711. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  5712. PDiag(diag::warn_argument_invalid_range)
  5713. << Result.toString(10) << Low << High
  5714. << Arg->getSourceRange());
  5715. }
  5716. return false;
  5717. }
  5718. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5719. /// TheCall is a constant expression is a multiple of Num..
  5720. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5721. unsigned Num) {
  5722. llvm::APSInt Result;
  5723. // We can't check the value of a dependent argument.
  5724. Expr *Arg = TheCall->getArg(ArgNum);
  5725. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5726. return false;
  5727. // Check constant-ness first.
  5728. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5729. return true;
  5730. if (Result.getSExtValue() % Num != 0)
  5731. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  5732. << Num << Arg->getSourceRange();
  5733. return false;
  5734. }
  5735. /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
  5736. bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
  5737. if (BuiltinID == AArch64::BI__builtin_arm_irg) {
  5738. if (checkArgCount(*this, TheCall, 2))
  5739. return true;
  5740. Expr *Arg0 = TheCall->getArg(0);
  5741. Expr *Arg1 = TheCall->getArg(1);
  5742. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5743. if (FirstArg.isInvalid())
  5744. return true;
  5745. QualType FirstArgType = FirstArg.get()->getType();
  5746. if (!FirstArgType->isAnyPointerType())
  5747. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5748. << "first" << FirstArgType << Arg0->getSourceRange();
  5749. TheCall->setArg(0, FirstArg.get());
  5750. ExprResult SecArg = DefaultLvalueConversion(Arg1);
  5751. if (SecArg.isInvalid())
  5752. return true;
  5753. QualType SecArgType = SecArg.get()->getType();
  5754. if (!SecArgType->isIntegerType())
  5755. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5756. << "second" << SecArgType << Arg1->getSourceRange();
  5757. // Derive the return type from the pointer argument.
  5758. TheCall->setType(FirstArgType);
  5759. return false;
  5760. }
  5761. if (BuiltinID == AArch64::BI__builtin_arm_addg) {
  5762. if (checkArgCount(*this, TheCall, 2))
  5763. return true;
  5764. Expr *Arg0 = TheCall->getArg(0);
  5765. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5766. if (FirstArg.isInvalid())
  5767. return true;
  5768. QualType FirstArgType = FirstArg.get()->getType();
  5769. if (!FirstArgType->isAnyPointerType())
  5770. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5771. << "first" << FirstArgType << Arg0->getSourceRange();
  5772. TheCall->setArg(0, FirstArg.get());
  5773. // Derive the return type from the pointer argument.
  5774. TheCall->setType(FirstArgType);
  5775. // Second arg must be an constant in range [0,15]
  5776. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5777. }
  5778. if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
  5779. if (checkArgCount(*this, TheCall, 2))
  5780. return true;
  5781. Expr *Arg0 = TheCall->getArg(0);
  5782. Expr *Arg1 = TheCall->getArg(1);
  5783. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5784. if (FirstArg.isInvalid())
  5785. return true;
  5786. QualType FirstArgType = FirstArg.get()->getType();
  5787. if (!FirstArgType->isAnyPointerType())
  5788. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5789. << "first" << FirstArgType << Arg0->getSourceRange();
  5790. QualType SecArgType = Arg1->getType();
  5791. if (!SecArgType->isIntegerType())
  5792. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5793. << "second" << SecArgType << Arg1->getSourceRange();
  5794. TheCall->setType(Context.IntTy);
  5795. return false;
  5796. }
  5797. if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
  5798. BuiltinID == AArch64::BI__builtin_arm_stg) {
  5799. if (checkArgCount(*this, TheCall, 1))
  5800. return true;
  5801. Expr *Arg0 = TheCall->getArg(0);
  5802. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5803. if (FirstArg.isInvalid())
  5804. return true;
  5805. QualType FirstArgType = FirstArg.get()->getType();
  5806. if (!FirstArgType->isAnyPointerType())
  5807. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5808. << "first" << FirstArgType << Arg0->getSourceRange();
  5809. TheCall->setArg(0, FirstArg.get());
  5810. // Derive the return type from the pointer argument.
  5811. if (BuiltinID == AArch64::BI__builtin_arm_ldg)
  5812. TheCall->setType(FirstArgType);
  5813. return false;
  5814. }
  5815. if (BuiltinID == AArch64::BI__builtin_arm_subp) {
  5816. Expr *ArgA = TheCall->getArg(0);
  5817. Expr *ArgB = TheCall->getArg(1);
  5818. ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
  5819. ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
  5820. if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
  5821. return true;
  5822. QualType ArgTypeA = ArgExprA.get()->getType();
  5823. QualType ArgTypeB = ArgExprB.get()->getType();
  5824. auto isNull = [&] (Expr *E) -> bool {
  5825. return E->isNullPointerConstant(
  5826. Context, Expr::NPC_ValueDependentIsNotNull); };
  5827. // argument should be either a pointer or null
  5828. if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
  5829. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5830. << "first" << ArgTypeA << ArgA->getSourceRange();
  5831. if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
  5832. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5833. << "second" << ArgTypeB << ArgB->getSourceRange();
  5834. // Ensure Pointee types are compatible
  5835. if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
  5836. ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
  5837. QualType pointeeA = ArgTypeA->getPointeeType();
  5838. QualType pointeeB = ArgTypeB->getPointeeType();
  5839. if (!Context.typesAreCompatible(
  5840. Context.getCanonicalType(pointeeA).getUnqualifiedType(),
  5841. Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
  5842. return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
  5843. << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
  5844. << ArgB->getSourceRange();
  5845. }
  5846. }
  5847. // at least one argument should be pointer type
  5848. if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
  5849. return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
  5850. << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
  5851. if (isNull(ArgA)) // adopt type of the other pointer
  5852. ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
  5853. if (isNull(ArgB))
  5854. ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
  5855. TheCall->setArg(0, ArgExprA.get());
  5856. TheCall->setArg(1, ArgExprB.get());
  5857. TheCall->setType(Context.LongLongTy);
  5858. return false;
  5859. }
  5860. assert(false && "Unhandled ARM MTE intrinsic");
  5861. return true;
  5862. }
  5863. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5864. /// TheCall is an ARM/AArch64 special register string literal.
  5865. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5866. int ArgNum, unsigned ExpectedFieldNum,
  5867. bool AllowName) {
  5868. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5869. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5870. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5871. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5872. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5873. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5874. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5875. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5876. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5877. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5878. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5879. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5880. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5881. // We can't check the value of a dependent argument.
  5882. Expr *Arg = TheCall->getArg(ArgNum);
  5883. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5884. return false;
  5885. // Check if the argument is a string literal.
  5886. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5887. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  5888. << Arg->getSourceRange();
  5889. // Check the type of special register given.
  5890. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5891. SmallVector<StringRef, 6> Fields;
  5892. Reg.split(Fields, ":");
  5893. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5894. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5895. << Arg->getSourceRange();
  5896. // If the string is the name of a register then we cannot check that it is
  5897. // valid here but if the string is of one the forms described in ACLE then we
  5898. // can check that the supplied fields are integers and within the valid
  5899. // ranges.
  5900. if (Fields.size() > 1) {
  5901. bool FiveFields = Fields.size() == 5;
  5902. bool ValidString = true;
  5903. if (IsARMBuiltin) {
  5904. ValidString &= Fields[0].startswith_lower("cp") ||
  5905. Fields[0].startswith_lower("p");
  5906. if (ValidString)
  5907. Fields[0] =
  5908. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5909. ValidString &= Fields[2].startswith_lower("c");
  5910. if (ValidString)
  5911. Fields[2] = Fields[2].drop_front(1);
  5912. if (FiveFields) {
  5913. ValidString &= Fields[3].startswith_lower("c");
  5914. if (ValidString)
  5915. Fields[3] = Fields[3].drop_front(1);
  5916. }
  5917. }
  5918. SmallVector<int, 5> Ranges;
  5919. if (FiveFields)
  5920. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5921. else
  5922. Ranges.append({15, 7, 15});
  5923. for (unsigned i=0; i<Fields.size(); ++i) {
  5924. int IntField;
  5925. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5926. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5927. }
  5928. if (!ValidString)
  5929. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5930. << Arg->getSourceRange();
  5931. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5932. // If the register name is one of those that appear in the condition below
  5933. // and the special register builtin being used is one of the write builtins,
  5934. // then we require that the argument provided for writing to the register
  5935. // is an integer constant expression. This is because it will be lowered to
  5936. // an MSR (immediate) instruction, so we need to know the immediate at
  5937. // compile time.
  5938. if (TheCall->getNumArgs() != 2)
  5939. return false;
  5940. std::string RegLower = Reg.lower();
  5941. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5942. RegLower != "pan" && RegLower != "uao")
  5943. return false;
  5944. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5945. }
  5946. return false;
  5947. }
  5948. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5949. /// This checks that the target supports __builtin_longjmp and
  5950. /// that val is a constant 1.
  5951. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5952. if (!Context.getTargetInfo().hasSjLjLowering())
  5953. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  5954. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5955. Expr *Arg = TheCall->getArg(1);
  5956. llvm::APSInt Result;
  5957. // TODO: This is less than ideal. Overload this to take a value.
  5958. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5959. return true;
  5960. if (Result != 1)
  5961. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  5962. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  5963. return false;
  5964. }
  5965. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5966. /// This checks that the target supports __builtin_setjmp.
  5967. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5968. if (!Context.getTargetInfo().hasSjLjLowering())
  5969. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  5970. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5971. return false;
  5972. }
  5973. namespace {
  5974. class UncoveredArgHandler {
  5975. enum { Unknown = -1, AllCovered = -2 };
  5976. signed FirstUncoveredArg = Unknown;
  5977. SmallVector<const Expr *, 4> DiagnosticExprs;
  5978. public:
  5979. UncoveredArgHandler() = default;
  5980. bool hasUncoveredArg() const {
  5981. return (FirstUncoveredArg >= 0);
  5982. }
  5983. unsigned getUncoveredArg() const {
  5984. assert(hasUncoveredArg() && "no uncovered argument");
  5985. return FirstUncoveredArg;
  5986. }
  5987. void setAllCovered() {
  5988. // A string has been found with all arguments covered, so clear out
  5989. // the diagnostics.
  5990. DiagnosticExprs.clear();
  5991. FirstUncoveredArg = AllCovered;
  5992. }
  5993. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5994. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5995. // Don't update if a previous string covers all arguments.
  5996. if (FirstUncoveredArg == AllCovered)
  5997. return;
  5998. // UncoveredArgHandler tracks the highest uncovered argument index
  5999. // and with it all the strings that match this index.
  6000. if (NewFirstUncoveredArg == FirstUncoveredArg)
  6001. DiagnosticExprs.push_back(StrExpr);
  6002. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  6003. DiagnosticExprs.clear();
  6004. DiagnosticExprs.push_back(StrExpr);
  6005. FirstUncoveredArg = NewFirstUncoveredArg;
  6006. }
  6007. }
  6008. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  6009. };
  6010. enum StringLiteralCheckType {
  6011. SLCT_NotALiteral,
  6012. SLCT_UncheckedLiteral,
  6013. SLCT_CheckedLiteral
  6014. };
  6015. } // namespace
  6016. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  6017. BinaryOperatorKind BinOpKind,
  6018. bool AddendIsRight) {
  6019. unsigned BitWidth = Offset.getBitWidth();
  6020. unsigned AddendBitWidth = Addend.getBitWidth();
  6021. // There might be negative interim results.
  6022. if (Addend.isUnsigned()) {
  6023. Addend = Addend.zext(++AddendBitWidth);
  6024. Addend.setIsSigned(true);
  6025. }
  6026. // Adjust the bit width of the APSInts.
  6027. if (AddendBitWidth > BitWidth) {
  6028. Offset = Offset.sext(AddendBitWidth);
  6029. BitWidth = AddendBitWidth;
  6030. } else if (BitWidth > AddendBitWidth) {
  6031. Addend = Addend.sext(BitWidth);
  6032. }
  6033. bool Ov = false;
  6034. llvm::APSInt ResOffset = Offset;
  6035. if (BinOpKind == BO_Add)
  6036. ResOffset = Offset.sadd_ov(Addend, Ov);
  6037. else {
  6038. assert(AddendIsRight && BinOpKind == BO_Sub &&
  6039. "operator must be add or sub with addend on the right");
  6040. ResOffset = Offset.ssub_ov(Addend, Ov);
  6041. }
  6042. // We add an offset to a pointer here so we should support an offset as big as
  6043. // possible.
  6044. if (Ov) {
  6045. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  6046. "index (intermediate) result too big");
  6047. Offset = Offset.sext(2 * BitWidth);
  6048. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  6049. return;
  6050. }
  6051. Offset = ResOffset;
  6052. }
  6053. namespace {
  6054. // This is a wrapper class around StringLiteral to support offsetted string
  6055. // literals as format strings. It takes the offset into account when returning
  6056. // the string and its length or the source locations to display notes correctly.
  6057. class FormatStringLiteral {
  6058. const StringLiteral *FExpr;
  6059. int64_t Offset;
  6060. public:
  6061. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  6062. : FExpr(fexpr), Offset(Offset) {}
  6063. StringRef getString() const {
  6064. return FExpr->getString().drop_front(Offset);
  6065. }
  6066. unsigned getByteLength() const {
  6067. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  6068. }
  6069. unsigned getLength() const { return FExpr->getLength() - Offset; }
  6070. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  6071. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  6072. QualType getType() const { return FExpr->getType(); }
  6073. bool isAscii() const { return FExpr->isAscii(); }
  6074. bool isWide() const { return FExpr->isWide(); }
  6075. bool isUTF8() const { return FExpr->isUTF8(); }
  6076. bool isUTF16() const { return FExpr->isUTF16(); }
  6077. bool isUTF32() const { return FExpr->isUTF32(); }
  6078. bool isPascal() const { return FExpr->isPascal(); }
  6079. SourceLocation getLocationOfByte(
  6080. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  6081. const TargetInfo &Target, unsigned *StartToken = nullptr,
  6082. unsigned *StartTokenByteOffset = nullptr) const {
  6083. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  6084. StartToken, StartTokenByteOffset);
  6085. }
  6086. SourceLocation getBeginLoc() const LLVM_READONLY {
  6087. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  6088. }
  6089. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  6090. };
  6091. } // namespace
  6092. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  6093. const Expr *OrigFormatExpr,
  6094. ArrayRef<const Expr *> Args,
  6095. bool HasVAListArg, unsigned format_idx,
  6096. unsigned firstDataArg,
  6097. Sema::FormatStringType Type,
  6098. bool inFunctionCall,
  6099. Sema::VariadicCallType CallType,
  6100. llvm::SmallBitVector &CheckedVarArgs,
  6101. UncoveredArgHandler &UncoveredArg,
  6102. bool IgnoreStringsWithoutSpecifiers);
  6103. // Determine if an expression is a string literal or constant string.
  6104. // If this function returns false on the arguments to a function expecting a
  6105. // format string, we will usually need to emit a warning.
  6106. // True string literals are then checked by CheckFormatString.
  6107. static StringLiteralCheckType
  6108. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  6109. bool HasVAListArg, unsigned format_idx,
  6110. unsigned firstDataArg, Sema::FormatStringType Type,
  6111. Sema::VariadicCallType CallType, bool InFunctionCall,
  6112. llvm::SmallBitVector &CheckedVarArgs,
  6113. UncoveredArgHandler &UncoveredArg,
  6114. llvm::APSInt Offset,
  6115. bool IgnoreStringsWithoutSpecifiers = false) {
  6116. if (S.isConstantEvaluated())
  6117. return SLCT_NotALiteral;
  6118. tryAgain:
  6119. assert(Offset.isSigned() && "invalid offset");
  6120. if (E->isTypeDependent() || E->isValueDependent())
  6121. return SLCT_NotALiteral;
  6122. E = E->IgnoreParenCasts();
  6123. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  6124. // Technically -Wformat-nonliteral does not warn about this case.
  6125. // The behavior of printf and friends in this case is implementation
  6126. // dependent. Ideally if the format string cannot be null then
  6127. // it should have a 'nonnull' attribute in the function prototype.
  6128. return SLCT_UncheckedLiteral;
  6129. switch (E->getStmtClass()) {
  6130. case Stmt::BinaryConditionalOperatorClass:
  6131. case Stmt::ConditionalOperatorClass: {
  6132. // The expression is a literal if both sub-expressions were, and it was
  6133. // completely checked only if both sub-expressions were checked.
  6134. const AbstractConditionalOperator *C =
  6135. cast<AbstractConditionalOperator>(E);
  6136. // Determine whether it is necessary to check both sub-expressions, for
  6137. // example, because the condition expression is a constant that can be
  6138. // evaluated at compile time.
  6139. bool CheckLeft = true, CheckRight = true;
  6140. bool Cond;
  6141. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
  6142. S.isConstantEvaluated())) {
  6143. if (Cond)
  6144. CheckRight = false;
  6145. else
  6146. CheckLeft = false;
  6147. }
  6148. // We need to maintain the offsets for the right and the left hand side
  6149. // separately to check if every possible indexed expression is a valid
  6150. // string literal. They might have different offsets for different string
  6151. // literals in the end.
  6152. StringLiteralCheckType Left;
  6153. if (!CheckLeft)
  6154. Left = SLCT_UncheckedLiteral;
  6155. else {
  6156. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  6157. HasVAListArg, format_idx, firstDataArg,
  6158. Type, CallType, InFunctionCall,
  6159. CheckedVarArgs, UncoveredArg, Offset,
  6160. IgnoreStringsWithoutSpecifiers);
  6161. if (Left == SLCT_NotALiteral || !CheckRight) {
  6162. return Left;
  6163. }
  6164. }
  6165. StringLiteralCheckType Right = checkFormatStringExpr(
  6166. S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
  6167. Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  6168. IgnoreStringsWithoutSpecifiers);
  6169. return (CheckLeft && Left < Right) ? Left : Right;
  6170. }
  6171. case Stmt::ImplicitCastExprClass:
  6172. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  6173. goto tryAgain;
  6174. case Stmt::OpaqueValueExprClass:
  6175. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  6176. E = src;
  6177. goto tryAgain;
  6178. }
  6179. return SLCT_NotALiteral;
  6180. case Stmt::PredefinedExprClass:
  6181. // While __func__, etc., are technically not string literals, they
  6182. // cannot contain format specifiers and thus are not a security
  6183. // liability.
  6184. return SLCT_UncheckedLiteral;
  6185. case Stmt::DeclRefExprClass: {
  6186. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6187. // As an exception, do not flag errors for variables binding to
  6188. // const string literals.
  6189. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  6190. bool isConstant = false;
  6191. QualType T = DR->getType();
  6192. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  6193. isConstant = AT->getElementType().isConstant(S.Context);
  6194. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  6195. isConstant = T.isConstant(S.Context) &&
  6196. PT->getPointeeType().isConstant(S.Context);
  6197. } else if (T->isObjCObjectPointerType()) {
  6198. // In ObjC, there is usually no "const ObjectPointer" type,
  6199. // so don't check if the pointee type is constant.
  6200. isConstant = T.isConstant(S.Context);
  6201. }
  6202. if (isConstant) {
  6203. if (const Expr *Init = VD->getAnyInitializer()) {
  6204. // Look through initializers like const char c[] = { "foo" }
  6205. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  6206. if (InitList->isStringLiteralInit())
  6207. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  6208. }
  6209. return checkFormatStringExpr(S, Init, Args,
  6210. HasVAListArg, format_idx,
  6211. firstDataArg, Type, CallType,
  6212. /*InFunctionCall*/ false, CheckedVarArgs,
  6213. UncoveredArg, Offset);
  6214. }
  6215. }
  6216. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  6217. // special check to see if the format string is a function parameter
  6218. // of the function calling the printf function. If the function
  6219. // has an attribute indicating it is a printf-like function, then we
  6220. // should suppress warnings concerning non-literals being used in a call
  6221. // to a vprintf function. For example:
  6222. //
  6223. // void
  6224. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  6225. // va_list ap;
  6226. // va_start(ap, fmt);
  6227. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  6228. // ...
  6229. // }
  6230. if (HasVAListArg) {
  6231. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  6232. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  6233. int PVIndex = PV->getFunctionScopeIndex() + 1;
  6234. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  6235. // adjust for implicit parameter
  6236. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6237. if (MD->isInstance())
  6238. ++PVIndex;
  6239. // We also check if the formats are compatible.
  6240. // We can't pass a 'scanf' string to a 'printf' function.
  6241. if (PVIndex == PVFormat->getFormatIdx() &&
  6242. Type == S.GetFormatStringType(PVFormat))
  6243. return SLCT_UncheckedLiteral;
  6244. }
  6245. }
  6246. }
  6247. }
  6248. }
  6249. return SLCT_NotALiteral;
  6250. }
  6251. case Stmt::CallExprClass:
  6252. case Stmt::CXXMemberCallExprClass: {
  6253. const CallExpr *CE = cast<CallExpr>(E);
  6254. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  6255. bool IsFirst = true;
  6256. StringLiteralCheckType CommonResult;
  6257. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  6258. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  6259. StringLiteralCheckType Result = checkFormatStringExpr(
  6260. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6261. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  6262. IgnoreStringsWithoutSpecifiers);
  6263. if (IsFirst) {
  6264. CommonResult = Result;
  6265. IsFirst = false;
  6266. }
  6267. }
  6268. if (!IsFirst)
  6269. return CommonResult;
  6270. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  6271. unsigned BuiltinID = FD->getBuiltinID();
  6272. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  6273. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  6274. const Expr *Arg = CE->getArg(0);
  6275. return checkFormatStringExpr(S, Arg, Args,
  6276. HasVAListArg, format_idx,
  6277. firstDataArg, Type, CallType,
  6278. InFunctionCall, CheckedVarArgs,
  6279. UncoveredArg, Offset,
  6280. IgnoreStringsWithoutSpecifiers);
  6281. }
  6282. }
  6283. }
  6284. return SLCT_NotALiteral;
  6285. }
  6286. case Stmt::ObjCMessageExprClass: {
  6287. const auto *ME = cast<ObjCMessageExpr>(E);
  6288. if (const auto *MD = ME->getMethodDecl()) {
  6289. if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
  6290. // As a special case heuristic, if we're using the method -[NSBundle
  6291. // localizedStringForKey:value:table:], ignore any key strings that lack
  6292. // format specifiers. The idea is that if the key doesn't have any
  6293. // format specifiers then its probably just a key to map to the
  6294. // localized strings. If it does have format specifiers though, then its
  6295. // likely that the text of the key is the format string in the
  6296. // programmer's language, and should be checked.
  6297. const ObjCInterfaceDecl *IFace;
  6298. if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
  6299. IFace->getIdentifier()->isStr("NSBundle") &&
  6300. MD->getSelector().isKeywordSelector(
  6301. {"localizedStringForKey", "value", "table"})) {
  6302. IgnoreStringsWithoutSpecifiers = true;
  6303. }
  6304. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  6305. return checkFormatStringExpr(
  6306. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6307. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  6308. IgnoreStringsWithoutSpecifiers);
  6309. }
  6310. }
  6311. return SLCT_NotALiteral;
  6312. }
  6313. case Stmt::ObjCStringLiteralClass:
  6314. case Stmt::StringLiteralClass: {
  6315. const StringLiteral *StrE = nullptr;
  6316. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  6317. StrE = ObjCFExpr->getString();
  6318. else
  6319. StrE = cast<StringLiteral>(E);
  6320. if (StrE) {
  6321. if (Offset.isNegative() || Offset > StrE->getLength()) {
  6322. // TODO: It would be better to have an explicit warning for out of
  6323. // bounds literals.
  6324. return SLCT_NotALiteral;
  6325. }
  6326. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  6327. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  6328. firstDataArg, Type, InFunctionCall, CallType,
  6329. CheckedVarArgs, UncoveredArg,
  6330. IgnoreStringsWithoutSpecifiers);
  6331. return SLCT_CheckedLiteral;
  6332. }
  6333. return SLCT_NotALiteral;
  6334. }
  6335. case Stmt::BinaryOperatorClass: {
  6336. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  6337. // A string literal + an int offset is still a string literal.
  6338. if (BinOp->isAdditiveOp()) {
  6339. Expr::EvalResult LResult, RResult;
  6340. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
  6341. LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6342. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
  6343. RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6344. if (LIsInt != RIsInt) {
  6345. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  6346. if (LIsInt) {
  6347. if (BinOpKind == BO_Add) {
  6348. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  6349. E = BinOp->getRHS();
  6350. goto tryAgain;
  6351. }
  6352. } else {
  6353. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  6354. E = BinOp->getLHS();
  6355. goto tryAgain;
  6356. }
  6357. }
  6358. }
  6359. return SLCT_NotALiteral;
  6360. }
  6361. case Stmt::UnaryOperatorClass: {
  6362. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  6363. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  6364. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  6365. Expr::EvalResult IndexResult;
  6366. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
  6367. Expr::SE_NoSideEffects,
  6368. S.isConstantEvaluated())) {
  6369. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  6370. /*RHS is int*/ true);
  6371. E = ASE->getBase();
  6372. goto tryAgain;
  6373. }
  6374. }
  6375. return SLCT_NotALiteral;
  6376. }
  6377. default:
  6378. return SLCT_NotALiteral;
  6379. }
  6380. }
  6381. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  6382. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  6383. .Case("scanf", FST_Scanf)
  6384. .Cases("printf", "printf0", FST_Printf)
  6385. .Cases("NSString", "CFString", FST_NSString)
  6386. .Case("strftime", FST_Strftime)
  6387. .Case("strfmon", FST_Strfmon)
  6388. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  6389. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  6390. .Case("os_trace", FST_OSLog)
  6391. .Case("os_log", FST_OSLog)
  6392. .Default(FST_Unknown);
  6393. }
  6394. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  6395. /// functions) for correct use of format strings.
  6396. /// Returns true if a format string has been fully checked.
  6397. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  6398. ArrayRef<const Expr *> Args,
  6399. bool IsCXXMember,
  6400. VariadicCallType CallType,
  6401. SourceLocation Loc, SourceRange Range,
  6402. llvm::SmallBitVector &CheckedVarArgs) {
  6403. FormatStringInfo FSI;
  6404. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  6405. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  6406. FSI.FirstDataArg, GetFormatStringType(Format),
  6407. CallType, Loc, Range, CheckedVarArgs);
  6408. return false;
  6409. }
  6410. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  6411. bool HasVAListArg, unsigned format_idx,
  6412. unsigned firstDataArg, FormatStringType Type,
  6413. VariadicCallType CallType,
  6414. SourceLocation Loc, SourceRange Range,
  6415. llvm::SmallBitVector &CheckedVarArgs) {
  6416. // CHECK: printf/scanf-like function is called with no format string.
  6417. if (format_idx >= Args.size()) {
  6418. Diag(Loc, diag::warn_missing_format_string) << Range;
  6419. return false;
  6420. }
  6421. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  6422. // CHECK: format string is not a string literal.
  6423. //
  6424. // Dynamically generated format strings are difficult to
  6425. // automatically vet at compile time. Requiring that format strings
  6426. // are string literals: (1) permits the checking of format strings by
  6427. // the compiler and thereby (2) can practically remove the source of
  6428. // many format string exploits.
  6429. // Format string can be either ObjC string (e.g. @"%d") or
  6430. // C string (e.g. "%d")
  6431. // ObjC string uses the same format specifiers as C string, so we can use
  6432. // the same format string checking logic for both ObjC and C strings.
  6433. UncoveredArgHandler UncoveredArg;
  6434. StringLiteralCheckType CT =
  6435. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  6436. format_idx, firstDataArg, Type, CallType,
  6437. /*IsFunctionCall*/ true, CheckedVarArgs,
  6438. UncoveredArg,
  6439. /*no string offset*/ llvm::APSInt(64, false) = 0);
  6440. // Generate a diagnostic where an uncovered argument is detected.
  6441. if (UncoveredArg.hasUncoveredArg()) {
  6442. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  6443. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  6444. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  6445. }
  6446. if (CT != SLCT_NotALiteral)
  6447. // Literal format string found, check done!
  6448. return CT == SLCT_CheckedLiteral;
  6449. // Strftime is particular as it always uses a single 'time' argument,
  6450. // so it is safe to pass a non-literal string.
  6451. if (Type == FST_Strftime)
  6452. return false;
  6453. // Do not emit diag when the string param is a macro expansion and the
  6454. // format is either NSString or CFString. This is a hack to prevent
  6455. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  6456. // which are usually used in place of NS and CF string literals.
  6457. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  6458. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  6459. return false;
  6460. // If there are no arguments specified, warn with -Wformat-security, otherwise
  6461. // warn only with -Wformat-nonliteral.
  6462. if (Args.size() == firstDataArg) {
  6463. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  6464. << OrigFormatExpr->getSourceRange();
  6465. switch (Type) {
  6466. default:
  6467. break;
  6468. case FST_Kprintf:
  6469. case FST_FreeBSDKPrintf:
  6470. case FST_Printf:
  6471. Diag(FormatLoc, diag::note_format_security_fixit)
  6472. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  6473. break;
  6474. case FST_NSString:
  6475. Diag(FormatLoc, diag::note_format_security_fixit)
  6476. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  6477. break;
  6478. }
  6479. } else {
  6480. Diag(FormatLoc, diag::warn_format_nonliteral)
  6481. << OrigFormatExpr->getSourceRange();
  6482. }
  6483. return false;
  6484. }
  6485. namespace {
  6486. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  6487. protected:
  6488. Sema &S;
  6489. const FormatStringLiteral *FExpr;
  6490. const Expr *OrigFormatExpr;
  6491. const Sema::FormatStringType FSType;
  6492. const unsigned FirstDataArg;
  6493. const unsigned NumDataArgs;
  6494. const char *Beg; // Start of format string.
  6495. const bool HasVAListArg;
  6496. ArrayRef<const Expr *> Args;
  6497. unsigned FormatIdx;
  6498. llvm::SmallBitVector CoveredArgs;
  6499. bool usesPositionalArgs = false;
  6500. bool atFirstArg = true;
  6501. bool inFunctionCall;
  6502. Sema::VariadicCallType CallType;
  6503. llvm::SmallBitVector &CheckedVarArgs;
  6504. UncoveredArgHandler &UncoveredArg;
  6505. public:
  6506. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  6507. const Expr *origFormatExpr,
  6508. const Sema::FormatStringType type, unsigned firstDataArg,
  6509. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6510. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6511. bool inFunctionCall, Sema::VariadicCallType callType,
  6512. llvm::SmallBitVector &CheckedVarArgs,
  6513. UncoveredArgHandler &UncoveredArg)
  6514. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6515. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6516. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6517. inFunctionCall(inFunctionCall), CallType(callType),
  6518. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6519. CoveredArgs.resize(numDataArgs);
  6520. CoveredArgs.reset();
  6521. }
  6522. void DoneProcessing();
  6523. void HandleIncompleteSpecifier(const char *startSpecifier,
  6524. unsigned specifierLen) override;
  6525. void HandleInvalidLengthModifier(
  6526. const analyze_format_string::FormatSpecifier &FS,
  6527. const analyze_format_string::ConversionSpecifier &CS,
  6528. const char *startSpecifier, unsigned specifierLen,
  6529. unsigned DiagID);
  6530. void HandleNonStandardLengthModifier(
  6531. const analyze_format_string::FormatSpecifier &FS,
  6532. const char *startSpecifier, unsigned specifierLen);
  6533. void HandleNonStandardConversionSpecifier(
  6534. const analyze_format_string::ConversionSpecifier &CS,
  6535. const char *startSpecifier, unsigned specifierLen);
  6536. void HandlePosition(const char *startPos, unsigned posLen) override;
  6537. void HandleInvalidPosition(const char *startSpecifier,
  6538. unsigned specifierLen,
  6539. analyze_format_string::PositionContext p) override;
  6540. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6541. void HandleNullChar(const char *nullCharacter) override;
  6542. template <typename Range>
  6543. static void
  6544. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6545. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6546. bool IsStringLocation, Range StringRange,
  6547. ArrayRef<FixItHint> Fixit = None);
  6548. protected:
  6549. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6550. const char *startSpec,
  6551. unsigned specifierLen,
  6552. const char *csStart, unsigned csLen);
  6553. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6554. const char *startSpec,
  6555. unsigned specifierLen);
  6556. SourceRange getFormatStringRange();
  6557. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6558. unsigned specifierLen);
  6559. SourceLocation getLocationOfByte(const char *x);
  6560. const Expr *getDataArg(unsigned i) const;
  6561. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6562. const analyze_format_string::ConversionSpecifier &CS,
  6563. const char *startSpecifier, unsigned specifierLen,
  6564. unsigned argIndex);
  6565. template <typename Range>
  6566. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6567. bool IsStringLocation, Range StringRange,
  6568. ArrayRef<FixItHint> Fixit = None);
  6569. };
  6570. } // namespace
  6571. SourceRange CheckFormatHandler::getFormatStringRange() {
  6572. return OrigFormatExpr->getSourceRange();
  6573. }
  6574. CharSourceRange CheckFormatHandler::
  6575. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6576. SourceLocation Start = getLocationOfByte(startSpecifier);
  6577. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6578. // Advance the end SourceLocation by one due to half-open ranges.
  6579. End = End.getLocWithOffset(1);
  6580. return CharSourceRange::getCharRange(Start, End);
  6581. }
  6582. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6583. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6584. S.getLangOpts(), S.Context.getTargetInfo());
  6585. }
  6586. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6587. unsigned specifierLen){
  6588. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6589. getLocationOfByte(startSpecifier),
  6590. /*IsStringLocation*/true,
  6591. getSpecifierRange(startSpecifier, specifierLen));
  6592. }
  6593. void CheckFormatHandler::HandleInvalidLengthModifier(
  6594. const analyze_format_string::FormatSpecifier &FS,
  6595. const analyze_format_string::ConversionSpecifier &CS,
  6596. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6597. using namespace analyze_format_string;
  6598. const LengthModifier &LM = FS.getLengthModifier();
  6599. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6600. // See if we know how to fix this length modifier.
  6601. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6602. if (FixedLM) {
  6603. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6604. getLocationOfByte(LM.getStart()),
  6605. /*IsStringLocation*/true,
  6606. getSpecifierRange(startSpecifier, specifierLen));
  6607. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6608. << FixedLM->toString()
  6609. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6610. } else {
  6611. FixItHint Hint;
  6612. if (DiagID == diag::warn_format_nonsensical_length)
  6613. Hint = FixItHint::CreateRemoval(LMRange);
  6614. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6615. getLocationOfByte(LM.getStart()),
  6616. /*IsStringLocation*/true,
  6617. getSpecifierRange(startSpecifier, specifierLen),
  6618. Hint);
  6619. }
  6620. }
  6621. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6622. const analyze_format_string::FormatSpecifier &FS,
  6623. const char *startSpecifier, unsigned specifierLen) {
  6624. using namespace analyze_format_string;
  6625. const LengthModifier &LM = FS.getLengthModifier();
  6626. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6627. // See if we know how to fix this length modifier.
  6628. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6629. if (FixedLM) {
  6630. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6631. << LM.toString() << 0,
  6632. getLocationOfByte(LM.getStart()),
  6633. /*IsStringLocation*/true,
  6634. getSpecifierRange(startSpecifier, specifierLen));
  6635. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6636. << FixedLM->toString()
  6637. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6638. } else {
  6639. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6640. << LM.toString() << 0,
  6641. getLocationOfByte(LM.getStart()),
  6642. /*IsStringLocation*/true,
  6643. getSpecifierRange(startSpecifier, specifierLen));
  6644. }
  6645. }
  6646. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6647. const analyze_format_string::ConversionSpecifier &CS,
  6648. const char *startSpecifier, unsigned specifierLen) {
  6649. using namespace analyze_format_string;
  6650. // See if we know how to fix this conversion specifier.
  6651. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6652. if (FixedCS) {
  6653. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6654. << CS.toString() << /*conversion specifier*/1,
  6655. getLocationOfByte(CS.getStart()),
  6656. /*IsStringLocation*/true,
  6657. getSpecifierRange(startSpecifier, specifierLen));
  6658. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6659. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6660. << FixedCS->toString()
  6661. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6662. } else {
  6663. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6664. << CS.toString() << /*conversion specifier*/1,
  6665. getLocationOfByte(CS.getStart()),
  6666. /*IsStringLocation*/true,
  6667. getSpecifierRange(startSpecifier, specifierLen));
  6668. }
  6669. }
  6670. void CheckFormatHandler::HandlePosition(const char *startPos,
  6671. unsigned posLen) {
  6672. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6673. getLocationOfByte(startPos),
  6674. /*IsStringLocation*/true,
  6675. getSpecifierRange(startPos, posLen));
  6676. }
  6677. void
  6678. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6679. analyze_format_string::PositionContext p) {
  6680. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6681. << (unsigned) p,
  6682. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6683. getSpecifierRange(startPos, posLen));
  6684. }
  6685. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6686. unsigned posLen) {
  6687. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6688. getLocationOfByte(startPos),
  6689. /*IsStringLocation*/true,
  6690. getSpecifierRange(startPos, posLen));
  6691. }
  6692. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6693. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6694. // The presence of a null character is likely an error.
  6695. EmitFormatDiagnostic(
  6696. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6697. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6698. getFormatStringRange());
  6699. }
  6700. }
  6701. // Note that this may return NULL if there was an error parsing or building
  6702. // one of the argument expressions.
  6703. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6704. return Args[FirstDataArg + i];
  6705. }
  6706. void CheckFormatHandler::DoneProcessing() {
  6707. // Does the number of data arguments exceed the number of
  6708. // format conversions in the format string?
  6709. if (!HasVAListArg) {
  6710. // Find any arguments that weren't covered.
  6711. CoveredArgs.flip();
  6712. signed notCoveredArg = CoveredArgs.find_first();
  6713. if (notCoveredArg >= 0) {
  6714. assert((unsigned)notCoveredArg < NumDataArgs);
  6715. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6716. } else {
  6717. UncoveredArg.setAllCovered();
  6718. }
  6719. }
  6720. }
  6721. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6722. const Expr *ArgExpr) {
  6723. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6724. "Invalid state");
  6725. if (!ArgExpr)
  6726. return;
  6727. SourceLocation Loc = ArgExpr->getBeginLoc();
  6728. if (S.getSourceManager().isInSystemMacro(Loc))
  6729. return;
  6730. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6731. for (auto E : DiagnosticExprs)
  6732. PDiag << E->getSourceRange();
  6733. CheckFormatHandler::EmitFormatDiagnostic(
  6734. S, IsFunctionCall, DiagnosticExprs[0],
  6735. PDiag, Loc, /*IsStringLocation*/false,
  6736. DiagnosticExprs[0]->getSourceRange());
  6737. }
  6738. bool
  6739. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6740. SourceLocation Loc,
  6741. const char *startSpec,
  6742. unsigned specifierLen,
  6743. const char *csStart,
  6744. unsigned csLen) {
  6745. bool keepGoing = true;
  6746. if (argIndex < NumDataArgs) {
  6747. // Consider the argument coverered, even though the specifier doesn't
  6748. // make sense.
  6749. CoveredArgs.set(argIndex);
  6750. }
  6751. else {
  6752. // If argIndex exceeds the number of data arguments we
  6753. // don't issue a warning because that is just a cascade of warnings (and
  6754. // they may have intended '%%' anyway). We don't want to continue processing
  6755. // the format string after this point, however, as we will like just get
  6756. // gibberish when trying to match arguments.
  6757. keepGoing = false;
  6758. }
  6759. StringRef Specifier(csStart, csLen);
  6760. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6761. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6762. // hex value.
  6763. std::string CodePointStr;
  6764. if (!llvm::sys::locale::isPrint(*csStart)) {
  6765. llvm::UTF32 CodePoint;
  6766. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6767. const llvm::UTF8 *E =
  6768. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6769. llvm::ConversionResult Result =
  6770. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6771. if (Result != llvm::conversionOK) {
  6772. unsigned char FirstChar = *csStart;
  6773. CodePoint = (llvm::UTF32)FirstChar;
  6774. }
  6775. llvm::raw_string_ostream OS(CodePointStr);
  6776. if (CodePoint < 256)
  6777. OS << "\\x" << llvm::format("%02x", CodePoint);
  6778. else if (CodePoint <= 0xFFFF)
  6779. OS << "\\u" << llvm::format("%04x", CodePoint);
  6780. else
  6781. OS << "\\U" << llvm::format("%08x", CodePoint);
  6782. OS.flush();
  6783. Specifier = CodePointStr;
  6784. }
  6785. EmitFormatDiagnostic(
  6786. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6787. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6788. return keepGoing;
  6789. }
  6790. void
  6791. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6792. const char *startSpec,
  6793. unsigned specifierLen) {
  6794. EmitFormatDiagnostic(
  6795. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6796. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6797. }
  6798. bool
  6799. CheckFormatHandler::CheckNumArgs(
  6800. const analyze_format_string::FormatSpecifier &FS,
  6801. const analyze_format_string::ConversionSpecifier &CS,
  6802. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6803. if (argIndex >= NumDataArgs) {
  6804. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6805. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6806. << (argIndex+1) << NumDataArgs)
  6807. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6808. EmitFormatDiagnostic(
  6809. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6810. getSpecifierRange(startSpecifier, specifierLen));
  6811. // Since more arguments than conversion tokens are given, by extension
  6812. // all arguments are covered, so mark this as so.
  6813. UncoveredArg.setAllCovered();
  6814. return false;
  6815. }
  6816. return true;
  6817. }
  6818. template<typename Range>
  6819. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6820. SourceLocation Loc,
  6821. bool IsStringLocation,
  6822. Range StringRange,
  6823. ArrayRef<FixItHint> FixIt) {
  6824. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6825. Loc, IsStringLocation, StringRange, FixIt);
  6826. }
  6827. /// If the format string is not within the function call, emit a note
  6828. /// so that the function call and string are in diagnostic messages.
  6829. ///
  6830. /// \param InFunctionCall if true, the format string is within the function
  6831. /// call and only one diagnostic message will be produced. Otherwise, an
  6832. /// extra note will be emitted pointing to location of the format string.
  6833. ///
  6834. /// \param ArgumentExpr the expression that is passed as the format string
  6835. /// argument in the function call. Used for getting locations when two
  6836. /// diagnostics are emitted.
  6837. ///
  6838. /// \param PDiag the callee should already have provided any strings for the
  6839. /// diagnostic message. This function only adds locations and fixits
  6840. /// to diagnostics.
  6841. ///
  6842. /// \param Loc primary location for diagnostic. If two diagnostics are
  6843. /// required, one will be at Loc and a new SourceLocation will be created for
  6844. /// the other one.
  6845. ///
  6846. /// \param IsStringLocation if true, Loc points to the format string should be
  6847. /// used for the note. Otherwise, Loc points to the argument list and will
  6848. /// be used with PDiag.
  6849. ///
  6850. /// \param StringRange some or all of the string to highlight. This is
  6851. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6852. ///
  6853. /// \param FixIt optional fix it hint for the format string.
  6854. template <typename Range>
  6855. void CheckFormatHandler::EmitFormatDiagnostic(
  6856. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6857. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6858. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6859. if (InFunctionCall) {
  6860. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6861. D << StringRange;
  6862. D << FixIt;
  6863. } else {
  6864. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6865. << ArgumentExpr->getSourceRange();
  6866. const Sema::SemaDiagnosticBuilder &Note =
  6867. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6868. diag::note_format_string_defined);
  6869. Note << StringRange;
  6870. Note << FixIt;
  6871. }
  6872. }
  6873. //===--- CHECK: Printf format string checking ------------------------------===//
  6874. namespace {
  6875. class CheckPrintfHandler : public CheckFormatHandler {
  6876. public:
  6877. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6878. const Expr *origFormatExpr,
  6879. const Sema::FormatStringType type, unsigned firstDataArg,
  6880. unsigned numDataArgs, bool isObjC, const char *beg,
  6881. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6882. unsigned formatIdx, bool inFunctionCall,
  6883. Sema::VariadicCallType CallType,
  6884. llvm::SmallBitVector &CheckedVarArgs,
  6885. UncoveredArgHandler &UncoveredArg)
  6886. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6887. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6888. inFunctionCall, CallType, CheckedVarArgs,
  6889. UncoveredArg) {}
  6890. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6891. /// Returns true if '%@' specifiers are allowed in the format string.
  6892. bool allowsObjCArg() const {
  6893. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6894. FSType == Sema::FST_OSTrace;
  6895. }
  6896. bool HandleInvalidPrintfConversionSpecifier(
  6897. const analyze_printf::PrintfSpecifier &FS,
  6898. const char *startSpecifier,
  6899. unsigned specifierLen) override;
  6900. void handleInvalidMaskType(StringRef MaskType) override;
  6901. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6902. const char *startSpecifier,
  6903. unsigned specifierLen) override;
  6904. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6905. const char *StartSpecifier,
  6906. unsigned SpecifierLen,
  6907. const Expr *E);
  6908. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6909. const char *startSpecifier, unsigned specifierLen);
  6910. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6911. const analyze_printf::OptionalAmount &Amt,
  6912. unsigned type,
  6913. const char *startSpecifier, unsigned specifierLen);
  6914. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6915. const analyze_printf::OptionalFlag &flag,
  6916. const char *startSpecifier, unsigned specifierLen);
  6917. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6918. const analyze_printf::OptionalFlag &ignoredFlag,
  6919. const analyze_printf::OptionalFlag &flag,
  6920. const char *startSpecifier, unsigned specifierLen);
  6921. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6922. const Expr *E);
  6923. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6924. unsigned flagLen) override;
  6925. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6926. unsigned flagLen) override;
  6927. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6928. const char *flagsEnd,
  6929. const char *conversionPosition)
  6930. override;
  6931. };
  6932. } // namespace
  6933. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6934. const analyze_printf::PrintfSpecifier &FS,
  6935. const char *startSpecifier,
  6936. unsigned specifierLen) {
  6937. const analyze_printf::PrintfConversionSpecifier &CS =
  6938. FS.getConversionSpecifier();
  6939. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6940. getLocationOfByte(CS.getStart()),
  6941. startSpecifier, specifierLen,
  6942. CS.getStart(), CS.getLength());
  6943. }
  6944. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  6945. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  6946. }
  6947. bool CheckPrintfHandler::HandleAmount(
  6948. const analyze_format_string::OptionalAmount &Amt,
  6949. unsigned k, const char *startSpecifier,
  6950. unsigned specifierLen) {
  6951. if (Amt.hasDataArgument()) {
  6952. if (!HasVAListArg) {
  6953. unsigned argIndex = Amt.getArgIndex();
  6954. if (argIndex >= NumDataArgs) {
  6955. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6956. << k,
  6957. getLocationOfByte(Amt.getStart()),
  6958. /*IsStringLocation*/true,
  6959. getSpecifierRange(startSpecifier, specifierLen));
  6960. // Don't do any more checking. We will just emit
  6961. // spurious errors.
  6962. return false;
  6963. }
  6964. // Type check the data argument. It should be an 'int'.
  6965. // Although not in conformance with C99, we also allow the argument to be
  6966. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6967. // doesn't emit a warning for that case.
  6968. CoveredArgs.set(argIndex);
  6969. const Expr *Arg = getDataArg(argIndex);
  6970. if (!Arg)
  6971. return false;
  6972. QualType T = Arg->getType();
  6973. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6974. assert(AT.isValid());
  6975. if (!AT.matchesType(S.Context, T)) {
  6976. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6977. << k << AT.getRepresentativeTypeName(S.Context)
  6978. << T << Arg->getSourceRange(),
  6979. getLocationOfByte(Amt.getStart()),
  6980. /*IsStringLocation*/true,
  6981. getSpecifierRange(startSpecifier, specifierLen));
  6982. // Don't do any more checking. We will just emit
  6983. // spurious errors.
  6984. return false;
  6985. }
  6986. }
  6987. }
  6988. return true;
  6989. }
  6990. void CheckPrintfHandler::HandleInvalidAmount(
  6991. const analyze_printf::PrintfSpecifier &FS,
  6992. const analyze_printf::OptionalAmount &Amt,
  6993. unsigned type,
  6994. const char *startSpecifier,
  6995. unsigned specifierLen) {
  6996. const analyze_printf::PrintfConversionSpecifier &CS =
  6997. FS.getConversionSpecifier();
  6998. FixItHint fixit =
  6999. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  7000. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  7001. Amt.getConstantLength()))
  7002. : FixItHint();
  7003. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  7004. << type << CS.toString(),
  7005. getLocationOfByte(Amt.getStart()),
  7006. /*IsStringLocation*/true,
  7007. getSpecifierRange(startSpecifier, specifierLen),
  7008. fixit);
  7009. }
  7010. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  7011. const analyze_printf::OptionalFlag &flag,
  7012. const char *startSpecifier,
  7013. unsigned specifierLen) {
  7014. // Warn about pointless flag with a fixit removal.
  7015. const analyze_printf::PrintfConversionSpecifier &CS =
  7016. FS.getConversionSpecifier();
  7017. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  7018. << flag.toString() << CS.toString(),
  7019. getLocationOfByte(flag.getPosition()),
  7020. /*IsStringLocation*/true,
  7021. getSpecifierRange(startSpecifier, specifierLen),
  7022. FixItHint::CreateRemoval(
  7023. getSpecifierRange(flag.getPosition(), 1)));
  7024. }
  7025. void CheckPrintfHandler::HandleIgnoredFlag(
  7026. const analyze_printf::PrintfSpecifier &FS,
  7027. const analyze_printf::OptionalFlag &ignoredFlag,
  7028. const analyze_printf::OptionalFlag &flag,
  7029. const char *startSpecifier,
  7030. unsigned specifierLen) {
  7031. // Warn about ignored flag with a fixit removal.
  7032. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  7033. << ignoredFlag.toString() << flag.toString(),
  7034. getLocationOfByte(ignoredFlag.getPosition()),
  7035. /*IsStringLocation*/true,
  7036. getSpecifierRange(startSpecifier, specifierLen),
  7037. FixItHint::CreateRemoval(
  7038. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  7039. }
  7040. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  7041. unsigned flagLen) {
  7042. // Warn about an empty flag.
  7043. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  7044. getLocationOfByte(startFlag),
  7045. /*IsStringLocation*/true,
  7046. getSpecifierRange(startFlag, flagLen));
  7047. }
  7048. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  7049. unsigned flagLen) {
  7050. // Warn about an invalid flag.
  7051. auto Range = getSpecifierRange(startFlag, flagLen);
  7052. StringRef flag(startFlag, flagLen);
  7053. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  7054. getLocationOfByte(startFlag),
  7055. /*IsStringLocation*/true,
  7056. Range, FixItHint::CreateRemoval(Range));
  7057. }
  7058. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  7059. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  7060. // Warn about using '[...]' without a '@' conversion.
  7061. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  7062. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  7063. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  7064. getLocationOfByte(conversionPosition),
  7065. /*IsStringLocation*/true,
  7066. Range, FixItHint::CreateRemoval(Range));
  7067. }
  7068. // Determines if the specified is a C++ class or struct containing
  7069. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  7070. // "c_str()").
  7071. template<typename MemberKind>
  7072. static llvm::SmallPtrSet<MemberKind*, 1>
  7073. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  7074. const RecordType *RT = Ty->getAs<RecordType>();
  7075. llvm::SmallPtrSet<MemberKind*, 1> Results;
  7076. if (!RT)
  7077. return Results;
  7078. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  7079. if (!RD || !RD->getDefinition())
  7080. return Results;
  7081. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  7082. Sema::LookupMemberName);
  7083. R.suppressDiagnostics();
  7084. // We just need to include all members of the right kind turned up by the
  7085. // filter, at this point.
  7086. if (S.LookupQualifiedName(R, RT->getDecl()))
  7087. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  7088. NamedDecl *decl = (*I)->getUnderlyingDecl();
  7089. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  7090. Results.insert(FK);
  7091. }
  7092. return Results;
  7093. }
  7094. /// Check if we could call '.c_str()' on an object.
  7095. ///
  7096. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  7097. /// allow the call, or if it would be ambiguous).
  7098. bool Sema::hasCStrMethod(const Expr *E) {
  7099. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  7100. MethodSet Results =
  7101. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  7102. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  7103. MI != ME; ++MI)
  7104. if ((*MI)->getMinRequiredArguments() == 0)
  7105. return true;
  7106. return false;
  7107. }
  7108. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  7109. // better diagnostic if so. AT is assumed to be valid.
  7110. // Returns true when a c_str() conversion method is found.
  7111. bool CheckPrintfHandler::checkForCStrMembers(
  7112. const analyze_printf::ArgType &AT, const Expr *E) {
  7113. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  7114. MethodSet Results =
  7115. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  7116. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  7117. MI != ME; ++MI) {
  7118. const CXXMethodDecl *Method = *MI;
  7119. if (Method->getMinRequiredArguments() == 0 &&
  7120. AT.matchesType(S.Context, Method->getReturnType())) {
  7121. // FIXME: Suggest parens if the expression needs them.
  7122. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  7123. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  7124. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  7125. return true;
  7126. }
  7127. }
  7128. return false;
  7129. }
  7130. bool
  7131. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  7132. &FS,
  7133. const char *startSpecifier,
  7134. unsigned specifierLen) {
  7135. using namespace analyze_format_string;
  7136. using namespace analyze_printf;
  7137. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  7138. if (FS.consumesDataArgument()) {
  7139. if (atFirstArg) {
  7140. atFirstArg = false;
  7141. usesPositionalArgs = FS.usesPositionalArg();
  7142. }
  7143. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7144. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7145. startSpecifier, specifierLen);
  7146. return false;
  7147. }
  7148. }
  7149. // First check if the field width, precision, and conversion specifier
  7150. // have matching data arguments.
  7151. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  7152. startSpecifier, specifierLen)) {
  7153. return false;
  7154. }
  7155. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  7156. startSpecifier, specifierLen)) {
  7157. return false;
  7158. }
  7159. if (!CS.consumesDataArgument()) {
  7160. // FIXME: Technically specifying a precision or field width here
  7161. // makes no sense. Worth issuing a warning at some point.
  7162. return true;
  7163. }
  7164. // Consume the argument.
  7165. unsigned argIndex = FS.getArgIndex();
  7166. if (argIndex < NumDataArgs) {
  7167. // The check to see if the argIndex is valid will come later.
  7168. // We set the bit here because we may exit early from this
  7169. // function if we encounter some other error.
  7170. CoveredArgs.set(argIndex);
  7171. }
  7172. // FreeBSD kernel extensions.
  7173. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  7174. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  7175. // We need at least two arguments.
  7176. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  7177. return false;
  7178. // Claim the second argument.
  7179. CoveredArgs.set(argIndex + 1);
  7180. // Type check the first argument (int for %b, pointer for %D)
  7181. const Expr *Ex = getDataArg(argIndex);
  7182. const analyze_printf::ArgType &AT =
  7183. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  7184. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  7185. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  7186. EmitFormatDiagnostic(
  7187. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7188. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  7189. << false << Ex->getSourceRange(),
  7190. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7191. getSpecifierRange(startSpecifier, specifierLen));
  7192. // Type check the second argument (char * for both %b and %D)
  7193. Ex = getDataArg(argIndex + 1);
  7194. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  7195. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  7196. EmitFormatDiagnostic(
  7197. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7198. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  7199. << false << Ex->getSourceRange(),
  7200. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7201. getSpecifierRange(startSpecifier, specifierLen));
  7202. return true;
  7203. }
  7204. // Check for using an Objective-C specific conversion specifier
  7205. // in a non-ObjC literal.
  7206. if (!allowsObjCArg() && CS.isObjCArg()) {
  7207. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7208. specifierLen);
  7209. }
  7210. // %P can only be used with os_log.
  7211. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  7212. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7213. specifierLen);
  7214. }
  7215. // %n is not allowed with os_log.
  7216. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  7217. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  7218. getLocationOfByte(CS.getStart()),
  7219. /*IsStringLocation*/ false,
  7220. getSpecifierRange(startSpecifier, specifierLen));
  7221. return true;
  7222. }
  7223. // Only scalars are allowed for os_trace.
  7224. if (FSType == Sema::FST_OSTrace &&
  7225. (CS.getKind() == ConversionSpecifier::PArg ||
  7226. CS.getKind() == ConversionSpecifier::sArg ||
  7227. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  7228. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7229. specifierLen);
  7230. }
  7231. // Check for use of public/private annotation outside of os_log().
  7232. if (FSType != Sema::FST_OSLog) {
  7233. if (FS.isPublic().isSet()) {
  7234. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7235. << "public",
  7236. getLocationOfByte(FS.isPublic().getPosition()),
  7237. /*IsStringLocation*/ false,
  7238. getSpecifierRange(startSpecifier, specifierLen));
  7239. }
  7240. if (FS.isPrivate().isSet()) {
  7241. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7242. << "private",
  7243. getLocationOfByte(FS.isPrivate().getPosition()),
  7244. /*IsStringLocation*/ false,
  7245. getSpecifierRange(startSpecifier, specifierLen));
  7246. }
  7247. }
  7248. // Check for invalid use of field width
  7249. if (!FS.hasValidFieldWidth()) {
  7250. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  7251. startSpecifier, specifierLen);
  7252. }
  7253. // Check for invalid use of precision
  7254. if (!FS.hasValidPrecision()) {
  7255. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  7256. startSpecifier, specifierLen);
  7257. }
  7258. // Precision is mandatory for %P specifier.
  7259. if (CS.getKind() == ConversionSpecifier::PArg &&
  7260. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  7261. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  7262. getLocationOfByte(startSpecifier),
  7263. /*IsStringLocation*/ false,
  7264. getSpecifierRange(startSpecifier, specifierLen));
  7265. }
  7266. // Check each flag does not conflict with any other component.
  7267. if (!FS.hasValidThousandsGroupingPrefix())
  7268. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  7269. if (!FS.hasValidLeadingZeros())
  7270. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  7271. if (!FS.hasValidPlusPrefix())
  7272. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  7273. if (!FS.hasValidSpacePrefix())
  7274. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  7275. if (!FS.hasValidAlternativeForm())
  7276. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  7277. if (!FS.hasValidLeftJustified())
  7278. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  7279. // Check that flags are not ignored by another flag
  7280. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  7281. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  7282. startSpecifier, specifierLen);
  7283. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  7284. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  7285. startSpecifier, specifierLen);
  7286. // Check the length modifier is valid with the given conversion specifier.
  7287. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7288. S.getLangOpts()))
  7289. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7290. diag::warn_format_nonsensical_length);
  7291. else if (!FS.hasStandardLengthModifier())
  7292. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7293. else if (!FS.hasStandardLengthConversionCombination())
  7294. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7295. diag::warn_format_non_standard_conversion_spec);
  7296. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7297. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7298. // The remaining checks depend on the data arguments.
  7299. if (HasVAListArg)
  7300. return true;
  7301. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7302. return false;
  7303. const Expr *Arg = getDataArg(argIndex);
  7304. if (!Arg)
  7305. return true;
  7306. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  7307. }
  7308. static bool requiresParensToAddCast(const Expr *E) {
  7309. // FIXME: We should have a general way to reason about operator
  7310. // precedence and whether parens are actually needed here.
  7311. // Take care of a few common cases where they aren't.
  7312. const Expr *Inside = E->IgnoreImpCasts();
  7313. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  7314. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  7315. switch (Inside->getStmtClass()) {
  7316. case Stmt::ArraySubscriptExprClass:
  7317. case Stmt::CallExprClass:
  7318. case Stmt::CharacterLiteralClass:
  7319. case Stmt::CXXBoolLiteralExprClass:
  7320. case Stmt::DeclRefExprClass:
  7321. case Stmt::FloatingLiteralClass:
  7322. case Stmt::IntegerLiteralClass:
  7323. case Stmt::MemberExprClass:
  7324. case Stmt::ObjCArrayLiteralClass:
  7325. case Stmt::ObjCBoolLiteralExprClass:
  7326. case Stmt::ObjCBoxedExprClass:
  7327. case Stmt::ObjCDictionaryLiteralClass:
  7328. case Stmt::ObjCEncodeExprClass:
  7329. case Stmt::ObjCIvarRefExprClass:
  7330. case Stmt::ObjCMessageExprClass:
  7331. case Stmt::ObjCPropertyRefExprClass:
  7332. case Stmt::ObjCStringLiteralClass:
  7333. case Stmt::ObjCSubscriptRefExprClass:
  7334. case Stmt::ParenExprClass:
  7335. case Stmt::StringLiteralClass:
  7336. case Stmt::UnaryOperatorClass:
  7337. return false;
  7338. default:
  7339. return true;
  7340. }
  7341. }
  7342. static std::pair<QualType, StringRef>
  7343. shouldNotPrintDirectly(const ASTContext &Context,
  7344. QualType IntendedTy,
  7345. const Expr *E) {
  7346. // Use a 'while' to peel off layers of typedefs.
  7347. QualType TyTy = IntendedTy;
  7348. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  7349. StringRef Name = UserTy->getDecl()->getName();
  7350. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  7351. .Case("CFIndex", Context.getNSIntegerType())
  7352. .Case("NSInteger", Context.getNSIntegerType())
  7353. .Case("NSUInteger", Context.getNSUIntegerType())
  7354. .Case("SInt32", Context.IntTy)
  7355. .Case("UInt32", Context.UnsignedIntTy)
  7356. .Default(QualType());
  7357. if (!CastTy.isNull())
  7358. return std::make_pair(CastTy, Name);
  7359. TyTy = UserTy->desugar();
  7360. }
  7361. // Strip parens if necessary.
  7362. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  7363. return shouldNotPrintDirectly(Context,
  7364. PE->getSubExpr()->getType(),
  7365. PE->getSubExpr());
  7366. // If this is a conditional expression, then its result type is constructed
  7367. // via usual arithmetic conversions and thus there might be no necessary
  7368. // typedef sugar there. Recurse to operands to check for NSInteger &
  7369. // Co. usage condition.
  7370. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7371. QualType TrueTy, FalseTy;
  7372. StringRef TrueName, FalseName;
  7373. std::tie(TrueTy, TrueName) =
  7374. shouldNotPrintDirectly(Context,
  7375. CO->getTrueExpr()->getType(),
  7376. CO->getTrueExpr());
  7377. std::tie(FalseTy, FalseName) =
  7378. shouldNotPrintDirectly(Context,
  7379. CO->getFalseExpr()->getType(),
  7380. CO->getFalseExpr());
  7381. if (TrueTy == FalseTy)
  7382. return std::make_pair(TrueTy, TrueName);
  7383. else if (TrueTy.isNull())
  7384. return std::make_pair(FalseTy, FalseName);
  7385. else if (FalseTy.isNull())
  7386. return std::make_pair(TrueTy, TrueName);
  7387. }
  7388. return std::make_pair(QualType(), StringRef());
  7389. }
  7390. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  7391. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  7392. /// type do not count.
  7393. static bool
  7394. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  7395. QualType From = ICE->getSubExpr()->getType();
  7396. QualType To = ICE->getType();
  7397. // It's an integer promotion if the destination type is the promoted
  7398. // source type.
  7399. if (ICE->getCastKind() == CK_IntegralCast &&
  7400. From->isPromotableIntegerType() &&
  7401. S.Context.getPromotedIntegerType(From) == To)
  7402. return true;
  7403. // Look through vector types, since we do default argument promotion for
  7404. // those in OpenCL.
  7405. if (const auto *VecTy = From->getAs<ExtVectorType>())
  7406. From = VecTy->getElementType();
  7407. if (const auto *VecTy = To->getAs<ExtVectorType>())
  7408. To = VecTy->getElementType();
  7409. // It's a floating promotion if the source type is a lower rank.
  7410. return ICE->getCastKind() == CK_FloatingCast &&
  7411. S.Context.getFloatingTypeOrder(From, To) < 0;
  7412. }
  7413. bool
  7414. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  7415. const char *StartSpecifier,
  7416. unsigned SpecifierLen,
  7417. const Expr *E) {
  7418. using namespace analyze_format_string;
  7419. using namespace analyze_printf;
  7420. // Now type check the data expression that matches the
  7421. // format specifier.
  7422. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  7423. if (!AT.isValid())
  7424. return true;
  7425. QualType ExprTy = E->getType();
  7426. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  7427. ExprTy = TET->getUnderlyingExpr()->getType();
  7428. }
  7429. // Diagnose attempts to print a boolean value as a character. Unlike other
  7430. // -Wformat diagnostics, this is fine from a type perspective, but it still
  7431. // doesn't make sense.
  7432. if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
  7433. E->isKnownToHaveBooleanValue()) {
  7434. const CharSourceRange &CSR =
  7435. getSpecifierRange(StartSpecifier, SpecifierLen);
  7436. SmallString<4> FSString;
  7437. llvm::raw_svector_ostream os(FSString);
  7438. FS.toString(os);
  7439. EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
  7440. << FSString,
  7441. E->getExprLoc(), false, CSR);
  7442. return true;
  7443. }
  7444. analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
  7445. if (Match == analyze_printf::ArgType::Match)
  7446. return true;
  7447. // Look through argument promotions for our error message's reported type.
  7448. // This includes the integral and floating promotions, but excludes array
  7449. // and function pointer decay (seeing that an argument intended to be a
  7450. // string has type 'char [6]' is probably more confusing than 'char *') and
  7451. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  7452. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7453. if (isArithmeticArgumentPromotion(S, ICE)) {
  7454. E = ICE->getSubExpr();
  7455. ExprTy = E->getType();
  7456. // Check if we didn't match because of an implicit cast from a 'char'
  7457. // or 'short' to an 'int'. This is done because printf is a varargs
  7458. // function.
  7459. if (ICE->getType() == S.Context.IntTy ||
  7460. ICE->getType() == S.Context.UnsignedIntTy) {
  7461. // All further checking is done on the subexpression
  7462. const analyze_printf::ArgType::MatchKind ImplicitMatch =
  7463. AT.matchesType(S.Context, ExprTy);
  7464. if (ImplicitMatch == analyze_printf::ArgType::Match)
  7465. return true;
  7466. if (ImplicitMatch == ArgType::NoMatchPedantic ||
  7467. ImplicitMatch == ArgType::NoMatchTypeConfusion)
  7468. Match = ImplicitMatch;
  7469. }
  7470. }
  7471. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  7472. // Special case for 'a', which has type 'int' in C.
  7473. // Note, however, that we do /not/ want to treat multibyte constants like
  7474. // 'MooV' as characters! This form is deprecated but still exists.
  7475. if (ExprTy == S.Context.IntTy)
  7476. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  7477. ExprTy = S.Context.CharTy;
  7478. }
  7479. // Look through enums to their underlying type.
  7480. bool IsEnum = false;
  7481. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  7482. ExprTy = EnumTy->getDecl()->getIntegerType();
  7483. IsEnum = true;
  7484. }
  7485. // %C in an Objective-C context prints a unichar, not a wchar_t.
  7486. // If the argument is an integer of some kind, believe the %C and suggest
  7487. // a cast instead of changing the conversion specifier.
  7488. QualType IntendedTy = ExprTy;
  7489. if (isObjCContext() &&
  7490. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  7491. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  7492. !ExprTy->isCharType()) {
  7493. // 'unichar' is defined as a typedef of unsigned short, but we should
  7494. // prefer using the typedef if it is visible.
  7495. IntendedTy = S.Context.UnsignedShortTy;
  7496. // While we are here, check if the value is an IntegerLiteral that happens
  7497. // to be within the valid range.
  7498. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  7499. const llvm::APInt &V = IL->getValue();
  7500. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  7501. return true;
  7502. }
  7503. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  7504. Sema::LookupOrdinaryName);
  7505. if (S.LookupName(Result, S.getCurScope())) {
  7506. NamedDecl *ND = Result.getFoundDecl();
  7507. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  7508. if (TD->getUnderlyingType() == IntendedTy)
  7509. IntendedTy = S.Context.getTypedefType(TD);
  7510. }
  7511. }
  7512. }
  7513. // Special-case some of Darwin's platform-independence types by suggesting
  7514. // casts to primitive types that are known to be large enough.
  7515. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  7516. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  7517. QualType CastTy;
  7518. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  7519. if (!CastTy.isNull()) {
  7520. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  7521. // (long in ASTContext). Only complain to pedants.
  7522. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  7523. (AT.isSizeT() || AT.isPtrdiffT()) &&
  7524. AT.matchesType(S.Context, CastTy))
  7525. Match = ArgType::NoMatchPedantic;
  7526. IntendedTy = CastTy;
  7527. ShouldNotPrintDirectly = true;
  7528. }
  7529. }
  7530. // We may be able to offer a FixItHint if it is a supported type.
  7531. PrintfSpecifier fixedFS = FS;
  7532. bool Success =
  7533. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  7534. if (Success) {
  7535. // Get the fix string from the fixed format specifier
  7536. SmallString<16> buf;
  7537. llvm::raw_svector_ostream os(buf);
  7538. fixedFS.toString(os);
  7539. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  7540. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  7541. unsigned Diag;
  7542. switch (Match) {
  7543. case ArgType::Match: llvm_unreachable("expected non-matching");
  7544. case ArgType::NoMatchPedantic:
  7545. Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  7546. break;
  7547. case ArgType::NoMatchTypeConfusion:
  7548. Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
  7549. break;
  7550. case ArgType::NoMatch:
  7551. Diag = diag::warn_format_conversion_argument_type_mismatch;
  7552. break;
  7553. }
  7554. // In this case, the specifier is wrong and should be changed to match
  7555. // the argument.
  7556. EmitFormatDiagnostic(S.PDiag(Diag)
  7557. << AT.getRepresentativeTypeName(S.Context)
  7558. << IntendedTy << IsEnum << E->getSourceRange(),
  7559. E->getBeginLoc(),
  7560. /*IsStringLocation*/ false, SpecRange,
  7561. FixItHint::CreateReplacement(SpecRange, os.str()));
  7562. } else {
  7563. // The canonical type for formatting this value is different from the
  7564. // actual type of the expression. (This occurs, for example, with Darwin's
  7565. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7566. // should be printed as 'long' for 64-bit compatibility.)
  7567. // Rather than emitting a normal format/argument mismatch, we want to
  7568. // add a cast to the recommended type (and correct the format string
  7569. // if necessary).
  7570. SmallString<16> CastBuf;
  7571. llvm::raw_svector_ostream CastFix(CastBuf);
  7572. CastFix << "(";
  7573. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7574. CastFix << ")";
  7575. SmallVector<FixItHint,4> Hints;
  7576. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7577. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7578. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7579. // If there's already a cast present, just replace it.
  7580. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7581. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7582. } else if (!requiresParensToAddCast(E)) {
  7583. // If the expression has high enough precedence,
  7584. // just write the C-style cast.
  7585. Hints.push_back(
  7586. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7587. } else {
  7588. // Otherwise, add parens around the expression as well as the cast.
  7589. CastFix << "(";
  7590. Hints.push_back(
  7591. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7592. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  7593. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7594. }
  7595. if (ShouldNotPrintDirectly) {
  7596. // The expression has a type that should not be printed directly.
  7597. // We extract the name from the typedef because we don't want to show
  7598. // the underlying type in the diagnostic.
  7599. StringRef Name;
  7600. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7601. Name = TypedefTy->getDecl()->getName();
  7602. else
  7603. Name = CastTyName;
  7604. unsigned Diag = Match == ArgType::NoMatchPedantic
  7605. ? diag::warn_format_argument_needs_cast_pedantic
  7606. : diag::warn_format_argument_needs_cast;
  7607. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7608. << E->getSourceRange(),
  7609. E->getBeginLoc(), /*IsStringLocation=*/false,
  7610. SpecRange, Hints);
  7611. } else {
  7612. // In this case, the expression could be printed using a different
  7613. // specifier, but we've decided that the specifier is probably correct
  7614. // and we should cast instead. Just use the normal warning message.
  7615. EmitFormatDiagnostic(
  7616. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7617. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7618. << E->getSourceRange(),
  7619. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  7620. }
  7621. }
  7622. } else {
  7623. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7624. SpecifierLen);
  7625. // Since the warning for passing non-POD types to variadic functions
  7626. // was deferred until now, we emit a warning for non-POD
  7627. // arguments here.
  7628. switch (S.isValidVarArgType(ExprTy)) {
  7629. case Sema::VAK_Valid:
  7630. case Sema::VAK_ValidInCXX11: {
  7631. unsigned Diag;
  7632. switch (Match) {
  7633. case ArgType::Match: llvm_unreachable("expected non-matching");
  7634. case ArgType::NoMatchPedantic:
  7635. Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  7636. break;
  7637. case ArgType::NoMatchTypeConfusion:
  7638. Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
  7639. break;
  7640. case ArgType::NoMatch:
  7641. Diag = diag::warn_format_conversion_argument_type_mismatch;
  7642. break;
  7643. }
  7644. EmitFormatDiagnostic(
  7645. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7646. << IsEnum << CSR << E->getSourceRange(),
  7647. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7648. break;
  7649. }
  7650. case Sema::VAK_Undefined:
  7651. case Sema::VAK_MSVCUndefined:
  7652. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7653. << S.getLangOpts().CPlusPlus11 << ExprTy
  7654. << CallType
  7655. << AT.getRepresentativeTypeName(S.Context) << CSR
  7656. << E->getSourceRange(),
  7657. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7658. checkForCStrMembers(AT, E);
  7659. break;
  7660. case Sema::VAK_Invalid:
  7661. if (ExprTy->isObjCObjectType())
  7662. EmitFormatDiagnostic(
  7663. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7664. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  7665. << AT.getRepresentativeTypeName(S.Context) << CSR
  7666. << E->getSourceRange(),
  7667. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7668. else
  7669. // FIXME: If this is an initializer list, suggest removing the braces
  7670. // or inserting a cast to the target type.
  7671. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  7672. << isa<InitListExpr>(E) << ExprTy << CallType
  7673. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  7674. break;
  7675. }
  7676. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7677. "format string specifier index out of range");
  7678. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7679. }
  7680. return true;
  7681. }
  7682. //===--- CHECK: Scanf format string checking ------------------------------===//
  7683. namespace {
  7684. class CheckScanfHandler : public CheckFormatHandler {
  7685. public:
  7686. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7687. const Expr *origFormatExpr, Sema::FormatStringType type,
  7688. unsigned firstDataArg, unsigned numDataArgs,
  7689. const char *beg, bool hasVAListArg,
  7690. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7691. bool inFunctionCall, Sema::VariadicCallType CallType,
  7692. llvm::SmallBitVector &CheckedVarArgs,
  7693. UncoveredArgHandler &UncoveredArg)
  7694. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7695. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7696. inFunctionCall, CallType, CheckedVarArgs,
  7697. UncoveredArg) {}
  7698. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7699. const char *startSpecifier,
  7700. unsigned specifierLen) override;
  7701. bool HandleInvalidScanfConversionSpecifier(
  7702. const analyze_scanf::ScanfSpecifier &FS,
  7703. const char *startSpecifier,
  7704. unsigned specifierLen) override;
  7705. void HandleIncompleteScanList(const char *start, const char *end) override;
  7706. };
  7707. } // namespace
  7708. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7709. const char *end) {
  7710. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7711. getLocationOfByte(end), /*IsStringLocation*/true,
  7712. getSpecifierRange(start, end - start));
  7713. }
  7714. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7715. const analyze_scanf::ScanfSpecifier &FS,
  7716. const char *startSpecifier,
  7717. unsigned specifierLen) {
  7718. const analyze_scanf::ScanfConversionSpecifier &CS =
  7719. FS.getConversionSpecifier();
  7720. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7721. getLocationOfByte(CS.getStart()),
  7722. startSpecifier, specifierLen,
  7723. CS.getStart(), CS.getLength());
  7724. }
  7725. bool CheckScanfHandler::HandleScanfSpecifier(
  7726. const analyze_scanf::ScanfSpecifier &FS,
  7727. const char *startSpecifier,
  7728. unsigned specifierLen) {
  7729. using namespace analyze_scanf;
  7730. using namespace analyze_format_string;
  7731. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7732. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7733. // be used to decide if we are using positional arguments consistently.
  7734. if (FS.consumesDataArgument()) {
  7735. if (atFirstArg) {
  7736. atFirstArg = false;
  7737. usesPositionalArgs = FS.usesPositionalArg();
  7738. }
  7739. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7740. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7741. startSpecifier, specifierLen);
  7742. return false;
  7743. }
  7744. }
  7745. // Check if the field with is non-zero.
  7746. const OptionalAmount &Amt = FS.getFieldWidth();
  7747. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7748. if (Amt.getConstantAmount() == 0) {
  7749. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7750. Amt.getConstantLength());
  7751. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7752. getLocationOfByte(Amt.getStart()),
  7753. /*IsStringLocation*/true, R,
  7754. FixItHint::CreateRemoval(R));
  7755. }
  7756. }
  7757. if (!FS.consumesDataArgument()) {
  7758. // FIXME: Technically specifying a precision or field width here
  7759. // makes no sense. Worth issuing a warning at some point.
  7760. return true;
  7761. }
  7762. // Consume the argument.
  7763. unsigned argIndex = FS.getArgIndex();
  7764. if (argIndex < NumDataArgs) {
  7765. // The check to see if the argIndex is valid will come later.
  7766. // We set the bit here because we may exit early from this
  7767. // function if we encounter some other error.
  7768. CoveredArgs.set(argIndex);
  7769. }
  7770. // Check the length modifier is valid with the given conversion specifier.
  7771. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7772. S.getLangOpts()))
  7773. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7774. diag::warn_format_nonsensical_length);
  7775. else if (!FS.hasStandardLengthModifier())
  7776. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7777. else if (!FS.hasStandardLengthConversionCombination())
  7778. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7779. diag::warn_format_non_standard_conversion_spec);
  7780. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7781. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7782. // The remaining checks depend on the data arguments.
  7783. if (HasVAListArg)
  7784. return true;
  7785. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7786. return false;
  7787. // Check that the argument type matches the format specifier.
  7788. const Expr *Ex = getDataArg(argIndex);
  7789. if (!Ex)
  7790. return true;
  7791. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7792. if (!AT.isValid()) {
  7793. return true;
  7794. }
  7795. analyze_format_string::ArgType::MatchKind Match =
  7796. AT.matchesType(S.Context, Ex->getType());
  7797. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7798. if (Match == analyze_format_string::ArgType::Match)
  7799. return true;
  7800. ScanfSpecifier fixedFS = FS;
  7801. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7802. S.getLangOpts(), S.Context);
  7803. unsigned Diag =
  7804. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7805. : diag::warn_format_conversion_argument_type_mismatch;
  7806. if (Success) {
  7807. // Get the fix string from the fixed format specifier.
  7808. SmallString<128> buf;
  7809. llvm::raw_svector_ostream os(buf);
  7810. fixedFS.toString(os);
  7811. EmitFormatDiagnostic(
  7812. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7813. << Ex->getType() << false << Ex->getSourceRange(),
  7814. Ex->getBeginLoc(),
  7815. /*IsStringLocation*/ false,
  7816. getSpecifierRange(startSpecifier, specifierLen),
  7817. FixItHint::CreateReplacement(
  7818. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7819. } else {
  7820. EmitFormatDiagnostic(S.PDiag(Diag)
  7821. << AT.getRepresentativeTypeName(S.Context)
  7822. << Ex->getType() << false << Ex->getSourceRange(),
  7823. Ex->getBeginLoc(),
  7824. /*IsStringLocation*/ false,
  7825. getSpecifierRange(startSpecifier, specifierLen));
  7826. }
  7827. return true;
  7828. }
  7829. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7830. const Expr *OrigFormatExpr,
  7831. ArrayRef<const Expr *> Args,
  7832. bool HasVAListArg, unsigned format_idx,
  7833. unsigned firstDataArg,
  7834. Sema::FormatStringType Type,
  7835. bool inFunctionCall,
  7836. Sema::VariadicCallType CallType,
  7837. llvm::SmallBitVector &CheckedVarArgs,
  7838. UncoveredArgHandler &UncoveredArg,
  7839. bool IgnoreStringsWithoutSpecifiers) {
  7840. // CHECK: is the format string a wide literal?
  7841. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7842. CheckFormatHandler::EmitFormatDiagnostic(
  7843. S, inFunctionCall, Args[format_idx],
  7844. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  7845. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7846. return;
  7847. }
  7848. // Str - The format string. NOTE: this is NOT null-terminated!
  7849. StringRef StrRef = FExpr->getString();
  7850. const char *Str = StrRef.data();
  7851. // Account for cases where the string literal is truncated in a declaration.
  7852. const ConstantArrayType *T =
  7853. S.Context.getAsConstantArrayType(FExpr->getType());
  7854. assert(T && "String literal not of constant array type!");
  7855. size_t TypeSize = T->getSize().getZExtValue();
  7856. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7857. const unsigned numDataArgs = Args.size() - firstDataArg;
  7858. if (IgnoreStringsWithoutSpecifiers &&
  7859. !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
  7860. Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
  7861. return;
  7862. // Emit a warning if the string literal is truncated and does not contain an
  7863. // embedded null character.
  7864. if (TypeSize <= StrRef.size() &&
  7865. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7866. CheckFormatHandler::EmitFormatDiagnostic(
  7867. S, inFunctionCall, Args[format_idx],
  7868. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7869. FExpr->getBeginLoc(),
  7870. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7871. return;
  7872. }
  7873. // CHECK: empty format string?
  7874. if (StrLen == 0 && numDataArgs > 0) {
  7875. CheckFormatHandler::EmitFormatDiagnostic(
  7876. S, inFunctionCall, Args[format_idx],
  7877. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  7878. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7879. return;
  7880. }
  7881. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7882. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7883. Type == Sema::FST_OSTrace) {
  7884. CheckPrintfHandler H(
  7885. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7886. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7887. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7888. CheckedVarArgs, UncoveredArg);
  7889. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7890. S.getLangOpts(),
  7891. S.Context.getTargetInfo(),
  7892. Type == Sema::FST_FreeBSDKPrintf))
  7893. H.DoneProcessing();
  7894. } else if (Type == Sema::FST_Scanf) {
  7895. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7896. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7897. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7898. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7899. S.getLangOpts(),
  7900. S.Context.getTargetInfo()))
  7901. H.DoneProcessing();
  7902. } // TODO: handle other formats
  7903. }
  7904. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7905. // Str - The format string. NOTE: this is NOT null-terminated!
  7906. StringRef StrRef = FExpr->getString();
  7907. const char *Str = StrRef.data();
  7908. // Account for cases where the string literal is truncated in a declaration.
  7909. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7910. assert(T && "String literal not of constant array type!");
  7911. size_t TypeSize = T->getSize().getZExtValue();
  7912. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7913. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7914. getLangOpts(),
  7915. Context.getTargetInfo());
  7916. }
  7917. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7918. // Returns the related absolute value function that is larger, of 0 if one
  7919. // does not exist.
  7920. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7921. switch (AbsFunction) {
  7922. default:
  7923. return 0;
  7924. case Builtin::BI__builtin_abs:
  7925. return Builtin::BI__builtin_labs;
  7926. case Builtin::BI__builtin_labs:
  7927. return Builtin::BI__builtin_llabs;
  7928. case Builtin::BI__builtin_llabs:
  7929. return 0;
  7930. case Builtin::BI__builtin_fabsf:
  7931. return Builtin::BI__builtin_fabs;
  7932. case Builtin::BI__builtin_fabs:
  7933. return Builtin::BI__builtin_fabsl;
  7934. case Builtin::BI__builtin_fabsl:
  7935. return 0;
  7936. case Builtin::BI__builtin_cabsf:
  7937. return Builtin::BI__builtin_cabs;
  7938. case Builtin::BI__builtin_cabs:
  7939. return Builtin::BI__builtin_cabsl;
  7940. case Builtin::BI__builtin_cabsl:
  7941. return 0;
  7942. case Builtin::BIabs:
  7943. return Builtin::BIlabs;
  7944. case Builtin::BIlabs:
  7945. return Builtin::BIllabs;
  7946. case Builtin::BIllabs:
  7947. return 0;
  7948. case Builtin::BIfabsf:
  7949. return Builtin::BIfabs;
  7950. case Builtin::BIfabs:
  7951. return Builtin::BIfabsl;
  7952. case Builtin::BIfabsl:
  7953. return 0;
  7954. case Builtin::BIcabsf:
  7955. return Builtin::BIcabs;
  7956. case Builtin::BIcabs:
  7957. return Builtin::BIcabsl;
  7958. case Builtin::BIcabsl:
  7959. return 0;
  7960. }
  7961. }
  7962. // Returns the argument type of the absolute value function.
  7963. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7964. unsigned AbsType) {
  7965. if (AbsType == 0)
  7966. return QualType();
  7967. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7968. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7969. if (Error != ASTContext::GE_None)
  7970. return QualType();
  7971. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7972. if (!FT)
  7973. return QualType();
  7974. if (FT->getNumParams() != 1)
  7975. return QualType();
  7976. return FT->getParamType(0);
  7977. }
  7978. // Returns the best absolute value function, or zero, based on type and
  7979. // current absolute value function.
  7980. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7981. unsigned AbsFunctionKind) {
  7982. unsigned BestKind = 0;
  7983. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7984. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7985. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7986. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7987. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7988. if (BestKind == 0)
  7989. BestKind = Kind;
  7990. else if (Context.hasSameType(ParamType, ArgType)) {
  7991. BestKind = Kind;
  7992. break;
  7993. }
  7994. }
  7995. }
  7996. return BestKind;
  7997. }
  7998. enum AbsoluteValueKind {
  7999. AVK_Integer,
  8000. AVK_Floating,
  8001. AVK_Complex
  8002. };
  8003. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  8004. if (T->isIntegralOrEnumerationType())
  8005. return AVK_Integer;
  8006. if (T->isRealFloatingType())
  8007. return AVK_Floating;
  8008. if (T->isAnyComplexType())
  8009. return AVK_Complex;
  8010. llvm_unreachable("Type not integer, floating, or complex");
  8011. }
  8012. // Changes the absolute value function to a different type. Preserves whether
  8013. // the function is a builtin.
  8014. static unsigned changeAbsFunction(unsigned AbsKind,
  8015. AbsoluteValueKind ValueKind) {
  8016. switch (ValueKind) {
  8017. case AVK_Integer:
  8018. switch (AbsKind) {
  8019. default:
  8020. return 0;
  8021. case Builtin::BI__builtin_fabsf:
  8022. case Builtin::BI__builtin_fabs:
  8023. case Builtin::BI__builtin_fabsl:
  8024. case Builtin::BI__builtin_cabsf:
  8025. case Builtin::BI__builtin_cabs:
  8026. case Builtin::BI__builtin_cabsl:
  8027. return Builtin::BI__builtin_abs;
  8028. case Builtin::BIfabsf:
  8029. case Builtin::BIfabs:
  8030. case Builtin::BIfabsl:
  8031. case Builtin::BIcabsf:
  8032. case Builtin::BIcabs:
  8033. case Builtin::BIcabsl:
  8034. return Builtin::BIabs;
  8035. }
  8036. case AVK_Floating:
  8037. switch (AbsKind) {
  8038. default:
  8039. return 0;
  8040. case Builtin::BI__builtin_abs:
  8041. case Builtin::BI__builtin_labs:
  8042. case Builtin::BI__builtin_llabs:
  8043. case Builtin::BI__builtin_cabsf:
  8044. case Builtin::BI__builtin_cabs:
  8045. case Builtin::BI__builtin_cabsl:
  8046. return Builtin::BI__builtin_fabsf;
  8047. case Builtin::BIabs:
  8048. case Builtin::BIlabs:
  8049. case Builtin::BIllabs:
  8050. case Builtin::BIcabsf:
  8051. case Builtin::BIcabs:
  8052. case Builtin::BIcabsl:
  8053. return Builtin::BIfabsf;
  8054. }
  8055. case AVK_Complex:
  8056. switch (AbsKind) {
  8057. default:
  8058. return 0;
  8059. case Builtin::BI__builtin_abs:
  8060. case Builtin::BI__builtin_labs:
  8061. case Builtin::BI__builtin_llabs:
  8062. case Builtin::BI__builtin_fabsf:
  8063. case Builtin::BI__builtin_fabs:
  8064. case Builtin::BI__builtin_fabsl:
  8065. return Builtin::BI__builtin_cabsf;
  8066. case Builtin::BIabs:
  8067. case Builtin::BIlabs:
  8068. case Builtin::BIllabs:
  8069. case Builtin::BIfabsf:
  8070. case Builtin::BIfabs:
  8071. case Builtin::BIfabsl:
  8072. return Builtin::BIcabsf;
  8073. }
  8074. }
  8075. llvm_unreachable("Unable to convert function");
  8076. }
  8077. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  8078. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  8079. if (!FnInfo)
  8080. return 0;
  8081. switch (FDecl->getBuiltinID()) {
  8082. default:
  8083. return 0;
  8084. case Builtin::BI__builtin_abs:
  8085. case Builtin::BI__builtin_fabs:
  8086. case Builtin::BI__builtin_fabsf:
  8087. case Builtin::BI__builtin_fabsl:
  8088. case Builtin::BI__builtin_labs:
  8089. case Builtin::BI__builtin_llabs:
  8090. case Builtin::BI__builtin_cabs:
  8091. case Builtin::BI__builtin_cabsf:
  8092. case Builtin::BI__builtin_cabsl:
  8093. case Builtin::BIabs:
  8094. case Builtin::BIlabs:
  8095. case Builtin::BIllabs:
  8096. case Builtin::BIfabs:
  8097. case Builtin::BIfabsf:
  8098. case Builtin::BIfabsl:
  8099. case Builtin::BIcabs:
  8100. case Builtin::BIcabsf:
  8101. case Builtin::BIcabsl:
  8102. return FDecl->getBuiltinID();
  8103. }
  8104. llvm_unreachable("Unknown Builtin type");
  8105. }
  8106. // If the replacement is valid, emit a note with replacement function.
  8107. // Additionally, suggest including the proper header if not already included.
  8108. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  8109. unsigned AbsKind, QualType ArgType) {
  8110. bool EmitHeaderHint = true;
  8111. const char *HeaderName = nullptr;
  8112. const char *FunctionName = nullptr;
  8113. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  8114. FunctionName = "std::abs";
  8115. if (ArgType->isIntegralOrEnumerationType()) {
  8116. HeaderName = "cstdlib";
  8117. } else if (ArgType->isRealFloatingType()) {
  8118. HeaderName = "cmath";
  8119. } else {
  8120. llvm_unreachable("Invalid Type");
  8121. }
  8122. // Lookup all std::abs
  8123. if (NamespaceDecl *Std = S.getStdNamespace()) {
  8124. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  8125. R.suppressDiagnostics();
  8126. S.LookupQualifiedName(R, Std);
  8127. for (const auto *I : R) {
  8128. const FunctionDecl *FDecl = nullptr;
  8129. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  8130. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  8131. } else {
  8132. FDecl = dyn_cast<FunctionDecl>(I);
  8133. }
  8134. if (!FDecl)
  8135. continue;
  8136. // Found std::abs(), check that they are the right ones.
  8137. if (FDecl->getNumParams() != 1)
  8138. continue;
  8139. // Check that the parameter type can handle the argument.
  8140. QualType ParamType = FDecl->getParamDecl(0)->getType();
  8141. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  8142. S.Context.getTypeSize(ArgType) <=
  8143. S.Context.getTypeSize(ParamType)) {
  8144. // Found a function, don't need the header hint.
  8145. EmitHeaderHint = false;
  8146. break;
  8147. }
  8148. }
  8149. }
  8150. } else {
  8151. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  8152. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  8153. if (HeaderName) {
  8154. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  8155. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  8156. R.suppressDiagnostics();
  8157. S.LookupName(R, S.getCurScope());
  8158. if (R.isSingleResult()) {
  8159. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  8160. if (FD && FD->getBuiltinID() == AbsKind) {
  8161. EmitHeaderHint = false;
  8162. } else {
  8163. return;
  8164. }
  8165. } else if (!R.empty()) {
  8166. return;
  8167. }
  8168. }
  8169. }
  8170. S.Diag(Loc, diag::note_replace_abs_function)
  8171. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  8172. if (!HeaderName)
  8173. return;
  8174. if (!EmitHeaderHint)
  8175. return;
  8176. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  8177. << FunctionName;
  8178. }
  8179. template <std::size_t StrLen>
  8180. static bool IsStdFunction(const FunctionDecl *FDecl,
  8181. const char (&Str)[StrLen]) {
  8182. if (!FDecl)
  8183. return false;
  8184. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  8185. return false;
  8186. if (!FDecl->isInStdNamespace())
  8187. return false;
  8188. return true;
  8189. }
  8190. // Warn when using the wrong abs() function.
  8191. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  8192. const FunctionDecl *FDecl) {
  8193. if (Call->getNumArgs() != 1)
  8194. return;
  8195. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  8196. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  8197. if (AbsKind == 0 && !IsStdAbs)
  8198. return;
  8199. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8200. QualType ParamType = Call->getArg(0)->getType();
  8201. // Unsigned types cannot be negative. Suggest removing the absolute value
  8202. // function call.
  8203. if (ArgType->isUnsignedIntegerType()) {
  8204. const char *FunctionName =
  8205. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  8206. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  8207. Diag(Call->getExprLoc(), diag::note_remove_abs)
  8208. << FunctionName
  8209. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  8210. return;
  8211. }
  8212. // Taking the absolute value of a pointer is very suspicious, they probably
  8213. // wanted to index into an array, dereference a pointer, call a function, etc.
  8214. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  8215. unsigned DiagType = 0;
  8216. if (ArgType->isFunctionType())
  8217. DiagType = 1;
  8218. else if (ArgType->isArrayType())
  8219. DiagType = 2;
  8220. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  8221. return;
  8222. }
  8223. // std::abs has overloads which prevent most of the absolute value problems
  8224. // from occurring.
  8225. if (IsStdAbs)
  8226. return;
  8227. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  8228. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  8229. // The argument and parameter are the same kind. Check if they are the right
  8230. // size.
  8231. if (ArgValueKind == ParamValueKind) {
  8232. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  8233. return;
  8234. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  8235. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  8236. << FDecl << ArgType << ParamType;
  8237. if (NewAbsKind == 0)
  8238. return;
  8239. emitReplacement(*this, Call->getExprLoc(),
  8240. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8241. return;
  8242. }
  8243. // ArgValueKind != ParamValueKind
  8244. // The wrong type of absolute value function was used. Attempt to find the
  8245. // proper one.
  8246. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  8247. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  8248. if (NewAbsKind == 0)
  8249. return;
  8250. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  8251. << FDecl << ParamValueKind << ArgValueKind;
  8252. emitReplacement(*this, Call->getExprLoc(),
  8253. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8254. }
  8255. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  8256. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  8257. const FunctionDecl *FDecl) {
  8258. if (!Call || !FDecl) return;
  8259. // Ignore template specializations and macros.
  8260. if (inTemplateInstantiation()) return;
  8261. if (Call->getExprLoc().isMacroID()) return;
  8262. // Only care about the one template argument, two function parameter std::max
  8263. if (Call->getNumArgs() != 2) return;
  8264. if (!IsStdFunction(FDecl, "max")) return;
  8265. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  8266. if (!ArgList) return;
  8267. if (ArgList->size() != 1) return;
  8268. // Check that template type argument is unsigned integer.
  8269. const auto& TA = ArgList->get(0);
  8270. if (TA.getKind() != TemplateArgument::Type) return;
  8271. QualType ArgType = TA.getAsType();
  8272. if (!ArgType->isUnsignedIntegerType()) return;
  8273. // See if either argument is a literal zero.
  8274. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  8275. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  8276. if (!MTE) return false;
  8277. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  8278. if (!Num) return false;
  8279. if (Num->getValue() != 0) return false;
  8280. return true;
  8281. };
  8282. const Expr *FirstArg = Call->getArg(0);
  8283. const Expr *SecondArg = Call->getArg(1);
  8284. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  8285. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  8286. // Only warn when exactly one argument is zero.
  8287. if (IsFirstArgZero == IsSecondArgZero) return;
  8288. SourceRange FirstRange = FirstArg->getSourceRange();
  8289. SourceRange SecondRange = SecondArg->getSourceRange();
  8290. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  8291. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  8292. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  8293. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  8294. SourceRange RemovalRange;
  8295. if (IsFirstArgZero) {
  8296. RemovalRange = SourceRange(FirstRange.getBegin(),
  8297. SecondRange.getBegin().getLocWithOffset(-1));
  8298. } else {
  8299. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  8300. SecondRange.getEnd());
  8301. }
  8302. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  8303. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  8304. << FixItHint::CreateRemoval(RemovalRange);
  8305. }
  8306. //===--- CHECK: Standard memory functions ---------------------------------===//
  8307. /// Takes the expression passed to the size_t parameter of functions
  8308. /// such as memcmp, strncat, etc and warns if it's a comparison.
  8309. ///
  8310. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  8311. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  8312. IdentifierInfo *FnName,
  8313. SourceLocation FnLoc,
  8314. SourceLocation RParenLoc) {
  8315. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  8316. if (!Size)
  8317. return false;
  8318. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  8319. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  8320. return false;
  8321. SourceRange SizeRange = Size->getSourceRange();
  8322. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  8323. << SizeRange << FnName;
  8324. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  8325. << FnName
  8326. << FixItHint::CreateInsertion(
  8327. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  8328. << FixItHint::CreateRemoval(RParenLoc);
  8329. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  8330. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  8331. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  8332. ")");
  8333. return true;
  8334. }
  8335. /// Determine whether the given type is or contains a dynamic class type
  8336. /// (e.g., whether it has a vtable).
  8337. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  8338. bool &IsContained) {
  8339. // Look through array types while ignoring qualifiers.
  8340. const Type *Ty = T->getBaseElementTypeUnsafe();
  8341. IsContained = false;
  8342. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  8343. RD = RD ? RD->getDefinition() : nullptr;
  8344. if (!RD || RD->isInvalidDecl())
  8345. return nullptr;
  8346. if (RD->isDynamicClass())
  8347. return RD;
  8348. // Check all the fields. If any bases were dynamic, the class is dynamic.
  8349. // It's impossible for a class to transitively contain itself by value, so
  8350. // infinite recursion is impossible.
  8351. for (auto *FD : RD->fields()) {
  8352. bool SubContained;
  8353. if (const CXXRecordDecl *ContainedRD =
  8354. getContainedDynamicClass(FD->getType(), SubContained)) {
  8355. IsContained = true;
  8356. return ContainedRD;
  8357. }
  8358. }
  8359. return nullptr;
  8360. }
  8361. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  8362. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  8363. if (Unary->getKind() == UETT_SizeOf)
  8364. return Unary;
  8365. return nullptr;
  8366. }
  8367. /// If E is a sizeof expression, returns its argument expression,
  8368. /// otherwise returns NULL.
  8369. static const Expr *getSizeOfExprArg(const Expr *E) {
  8370. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8371. if (!SizeOf->isArgumentType())
  8372. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  8373. return nullptr;
  8374. }
  8375. /// If E is a sizeof expression, returns its argument type.
  8376. static QualType getSizeOfArgType(const Expr *E) {
  8377. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8378. return SizeOf->getTypeOfArgument();
  8379. return QualType();
  8380. }
  8381. namespace {
  8382. struct SearchNonTrivialToInitializeField
  8383. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  8384. using Super =
  8385. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  8386. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  8387. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  8388. SourceLocation SL) {
  8389. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8390. asDerived().visitArray(PDIK, AT, SL);
  8391. return;
  8392. }
  8393. Super::visitWithKind(PDIK, FT, SL);
  8394. }
  8395. void visitARCStrong(QualType FT, SourceLocation SL) {
  8396. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8397. }
  8398. void visitARCWeak(QualType FT, SourceLocation SL) {
  8399. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8400. }
  8401. void visitStruct(QualType FT, SourceLocation SL) {
  8402. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8403. visit(FD->getType(), FD->getLocation());
  8404. }
  8405. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  8406. const ArrayType *AT, SourceLocation SL) {
  8407. visit(getContext().getBaseElementType(AT), SL);
  8408. }
  8409. void visitTrivial(QualType FT, SourceLocation SL) {}
  8410. static void diag(QualType RT, const Expr *E, Sema &S) {
  8411. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  8412. }
  8413. ASTContext &getContext() { return S.getASTContext(); }
  8414. const Expr *E;
  8415. Sema &S;
  8416. };
  8417. struct SearchNonTrivialToCopyField
  8418. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  8419. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  8420. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  8421. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  8422. SourceLocation SL) {
  8423. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8424. asDerived().visitArray(PCK, AT, SL);
  8425. return;
  8426. }
  8427. Super::visitWithKind(PCK, FT, SL);
  8428. }
  8429. void visitARCStrong(QualType FT, SourceLocation SL) {
  8430. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8431. }
  8432. void visitARCWeak(QualType FT, SourceLocation SL) {
  8433. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8434. }
  8435. void visitStruct(QualType FT, SourceLocation SL) {
  8436. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8437. visit(FD->getType(), FD->getLocation());
  8438. }
  8439. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  8440. SourceLocation SL) {
  8441. visit(getContext().getBaseElementType(AT), SL);
  8442. }
  8443. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  8444. SourceLocation SL) {}
  8445. void visitTrivial(QualType FT, SourceLocation SL) {}
  8446. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  8447. static void diag(QualType RT, const Expr *E, Sema &S) {
  8448. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  8449. }
  8450. ASTContext &getContext() { return S.getASTContext(); }
  8451. const Expr *E;
  8452. Sema &S;
  8453. };
  8454. }
  8455. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  8456. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  8457. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  8458. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  8459. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  8460. return false;
  8461. return doesExprLikelyComputeSize(BO->getLHS()) ||
  8462. doesExprLikelyComputeSize(BO->getRHS());
  8463. }
  8464. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  8465. }
  8466. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  8467. ///
  8468. /// \code
  8469. /// #define MACRO 0
  8470. /// foo(MACRO);
  8471. /// foo(0);
  8472. /// \endcode
  8473. ///
  8474. /// This should return true for the first call to foo, but not for the second
  8475. /// (regardless of whether foo is a macro or function).
  8476. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  8477. SourceLocation CallLoc,
  8478. SourceLocation ArgLoc) {
  8479. if (!CallLoc.isMacroID())
  8480. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  8481. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  8482. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  8483. }
  8484. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  8485. /// last two arguments transposed.
  8486. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  8487. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  8488. return;
  8489. const Expr *SizeArg =
  8490. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  8491. auto isLiteralZero = [](const Expr *E) {
  8492. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  8493. };
  8494. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  8495. SourceLocation CallLoc = Call->getRParenLoc();
  8496. SourceManager &SM = S.getSourceManager();
  8497. if (isLiteralZero(SizeArg) &&
  8498. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  8499. SourceLocation DiagLoc = SizeArg->getExprLoc();
  8500. // Some platforms #define bzero to __builtin_memset. See if this is the
  8501. // case, and if so, emit a better diagnostic.
  8502. if (BId == Builtin::BIbzero ||
  8503. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  8504. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  8505. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  8506. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  8507. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  8508. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  8509. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  8510. }
  8511. return;
  8512. }
  8513. // If the second argument to a memset is a sizeof expression and the third
  8514. // isn't, this is also likely an error. This should catch
  8515. // 'memset(buf, sizeof(buf), 0xff)'.
  8516. if (BId == Builtin::BImemset &&
  8517. doesExprLikelyComputeSize(Call->getArg(1)) &&
  8518. !doesExprLikelyComputeSize(Call->getArg(2))) {
  8519. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  8520. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  8521. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  8522. return;
  8523. }
  8524. }
  8525. /// Check for dangerous or invalid arguments to memset().
  8526. ///
  8527. /// This issues warnings on known problematic, dangerous or unspecified
  8528. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  8529. /// function calls.
  8530. ///
  8531. /// \param Call The call expression to diagnose.
  8532. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  8533. unsigned BId,
  8534. IdentifierInfo *FnName) {
  8535. assert(BId != 0);
  8536. // It is possible to have a non-standard definition of memset. Validate
  8537. // we have enough arguments, and if not, abort further checking.
  8538. unsigned ExpectedNumArgs =
  8539. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  8540. if (Call->getNumArgs() < ExpectedNumArgs)
  8541. return;
  8542. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  8543. BId == Builtin::BIstrndup ? 1 : 2);
  8544. unsigned LenArg =
  8545. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  8546. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  8547. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  8548. Call->getBeginLoc(), Call->getRParenLoc()))
  8549. return;
  8550. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  8551. CheckMemaccessSize(*this, BId, Call);
  8552. // We have special checking when the length is a sizeof expression.
  8553. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  8554. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  8555. llvm::FoldingSetNodeID SizeOfArgID;
  8556. // Although widely used, 'bzero' is not a standard function. Be more strict
  8557. // with the argument types before allowing diagnostics and only allow the
  8558. // form bzero(ptr, sizeof(...)).
  8559. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8560. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  8561. return;
  8562. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  8563. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  8564. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  8565. QualType DestTy = Dest->getType();
  8566. QualType PointeeTy;
  8567. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  8568. PointeeTy = DestPtrTy->getPointeeType();
  8569. // Never warn about void type pointers. This can be used to suppress
  8570. // false positives.
  8571. if (PointeeTy->isVoidType())
  8572. continue;
  8573. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8574. // actually comparing the expressions for equality. Because computing the
  8575. // expression IDs can be expensive, we only do this if the diagnostic is
  8576. // enabled.
  8577. if (SizeOfArg &&
  8578. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8579. SizeOfArg->getExprLoc())) {
  8580. // We only compute IDs for expressions if the warning is enabled, and
  8581. // cache the sizeof arg's ID.
  8582. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8583. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8584. llvm::FoldingSetNodeID DestID;
  8585. Dest->Profile(DestID, Context, true);
  8586. if (DestID == SizeOfArgID) {
  8587. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8588. // over sizeof(src) as well.
  8589. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8590. StringRef ReadableName = FnName->getName();
  8591. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8592. if (UnaryOp->getOpcode() == UO_AddrOf)
  8593. ActionIdx = 1; // If its an address-of operator, just remove it.
  8594. if (!PointeeTy->isIncompleteType() &&
  8595. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8596. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8597. // suggest an explicit length.
  8598. // If the function is defined as a builtin macro, do not show macro
  8599. // expansion.
  8600. SourceLocation SL = SizeOfArg->getExprLoc();
  8601. SourceRange DSR = Dest->getSourceRange();
  8602. SourceRange SSR = SizeOfArg->getSourceRange();
  8603. SourceManager &SM = getSourceManager();
  8604. if (SM.isMacroArgExpansion(SL)) {
  8605. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8606. SL = SM.getSpellingLoc(SL);
  8607. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8608. SM.getSpellingLoc(DSR.getEnd()));
  8609. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8610. SM.getSpellingLoc(SSR.getEnd()));
  8611. }
  8612. DiagRuntimeBehavior(SL, SizeOfArg,
  8613. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8614. << ReadableName
  8615. << PointeeTy
  8616. << DestTy
  8617. << DSR
  8618. << SSR);
  8619. DiagRuntimeBehavior(SL, SizeOfArg,
  8620. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8621. << ActionIdx
  8622. << SSR);
  8623. break;
  8624. }
  8625. }
  8626. // Also check for cases where the sizeof argument is the exact same
  8627. // type as the memory argument, and where it points to a user-defined
  8628. // record type.
  8629. if (SizeOfArgTy != QualType()) {
  8630. if (PointeeTy->isRecordType() &&
  8631. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8632. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8633. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8634. << FnName << SizeOfArgTy << ArgIdx
  8635. << PointeeTy << Dest->getSourceRange()
  8636. << LenExpr->getSourceRange());
  8637. break;
  8638. }
  8639. }
  8640. } else if (DestTy->isArrayType()) {
  8641. PointeeTy = DestTy;
  8642. }
  8643. if (PointeeTy == QualType())
  8644. continue;
  8645. // Always complain about dynamic classes.
  8646. bool IsContained;
  8647. if (const CXXRecordDecl *ContainedRD =
  8648. getContainedDynamicClass(PointeeTy, IsContained)) {
  8649. unsigned OperationType = 0;
  8650. const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
  8651. // "overwritten" if we're warning about the destination for any call
  8652. // but memcmp; otherwise a verb appropriate to the call.
  8653. if (ArgIdx != 0 || IsCmp) {
  8654. if (BId == Builtin::BImemcpy)
  8655. OperationType = 1;
  8656. else if(BId == Builtin::BImemmove)
  8657. OperationType = 2;
  8658. else if (IsCmp)
  8659. OperationType = 3;
  8660. }
  8661. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8662. PDiag(diag::warn_dyn_class_memaccess)
  8663. << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
  8664. << IsContained << ContainedRD << OperationType
  8665. << Call->getCallee()->getSourceRange());
  8666. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8667. BId != Builtin::BImemset)
  8668. DiagRuntimeBehavior(
  8669. Dest->getExprLoc(), Dest,
  8670. PDiag(diag::warn_arc_object_memaccess)
  8671. << ArgIdx << FnName << PointeeTy
  8672. << Call->getCallee()->getSourceRange());
  8673. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8674. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8675. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8676. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8677. PDiag(diag::warn_cstruct_memaccess)
  8678. << ArgIdx << FnName << PointeeTy << 0);
  8679. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8680. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8681. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8682. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8683. PDiag(diag::warn_cstruct_memaccess)
  8684. << ArgIdx << FnName << PointeeTy << 1);
  8685. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8686. } else {
  8687. continue;
  8688. }
  8689. } else
  8690. continue;
  8691. DiagRuntimeBehavior(
  8692. Dest->getExprLoc(), Dest,
  8693. PDiag(diag::note_bad_memaccess_silence)
  8694. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8695. break;
  8696. }
  8697. }
  8698. // A little helper routine: ignore addition and subtraction of integer literals.
  8699. // This intentionally does not ignore all integer constant expressions because
  8700. // we don't want to remove sizeof().
  8701. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8702. Ex = Ex->IgnoreParenCasts();
  8703. while (true) {
  8704. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8705. if (!BO || !BO->isAdditiveOp())
  8706. break;
  8707. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8708. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8709. if (isa<IntegerLiteral>(RHS))
  8710. Ex = LHS;
  8711. else if (isa<IntegerLiteral>(LHS))
  8712. Ex = RHS;
  8713. else
  8714. break;
  8715. }
  8716. return Ex;
  8717. }
  8718. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8719. ASTContext &Context) {
  8720. // Only handle constant-sized or VLAs, but not flexible members.
  8721. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8722. // Only issue the FIXIT for arrays of size > 1.
  8723. if (CAT->getSize().getSExtValue() <= 1)
  8724. return false;
  8725. } else if (!Ty->isVariableArrayType()) {
  8726. return false;
  8727. }
  8728. return true;
  8729. }
  8730. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8731. // be the size of the source, instead of the destination.
  8732. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8733. IdentifierInfo *FnName) {
  8734. // Don't crash if the user has the wrong number of arguments
  8735. unsigned NumArgs = Call->getNumArgs();
  8736. if ((NumArgs != 3) && (NumArgs != 4))
  8737. return;
  8738. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8739. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8740. const Expr *CompareWithSrc = nullptr;
  8741. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8742. Call->getBeginLoc(), Call->getRParenLoc()))
  8743. return;
  8744. // Look for 'strlcpy(dst, x, sizeof(x))'
  8745. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8746. CompareWithSrc = Ex;
  8747. else {
  8748. // Look for 'strlcpy(dst, x, strlen(x))'
  8749. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8750. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8751. SizeCall->getNumArgs() == 1)
  8752. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8753. }
  8754. }
  8755. if (!CompareWithSrc)
  8756. return;
  8757. // Determine if the argument to sizeof/strlen is equal to the source
  8758. // argument. In principle there's all kinds of things you could do
  8759. // here, for instance creating an == expression and evaluating it with
  8760. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8761. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8762. if (!SrcArgDRE)
  8763. return;
  8764. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8765. if (!CompareWithSrcDRE ||
  8766. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8767. return;
  8768. const Expr *OriginalSizeArg = Call->getArg(2);
  8769. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  8770. << OriginalSizeArg->getSourceRange() << FnName;
  8771. // Output a FIXIT hint if the destination is an array (rather than a
  8772. // pointer to an array). This could be enhanced to handle some
  8773. // pointers if we know the actual size, like if DstArg is 'array+2'
  8774. // we could say 'sizeof(array)-2'.
  8775. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8776. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8777. return;
  8778. SmallString<128> sizeString;
  8779. llvm::raw_svector_ostream OS(sizeString);
  8780. OS << "sizeof(";
  8781. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8782. OS << ")";
  8783. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  8784. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8785. OS.str());
  8786. }
  8787. /// Check if two expressions refer to the same declaration.
  8788. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8789. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8790. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8791. return D1->getDecl() == D2->getDecl();
  8792. return false;
  8793. }
  8794. static const Expr *getStrlenExprArg(const Expr *E) {
  8795. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8796. const FunctionDecl *FD = CE->getDirectCallee();
  8797. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8798. return nullptr;
  8799. return CE->getArg(0)->IgnoreParenCasts();
  8800. }
  8801. return nullptr;
  8802. }
  8803. // Warn on anti-patterns as the 'size' argument to strncat.
  8804. // The correct size argument should look like following:
  8805. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8806. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8807. IdentifierInfo *FnName) {
  8808. // Don't crash if the user has the wrong number of arguments.
  8809. if (CE->getNumArgs() < 3)
  8810. return;
  8811. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8812. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8813. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8814. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  8815. CE->getRParenLoc()))
  8816. return;
  8817. // Identify common expressions, which are wrongly used as the size argument
  8818. // to strncat and may lead to buffer overflows.
  8819. unsigned PatternType = 0;
  8820. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8821. // - sizeof(dst)
  8822. if (referToTheSameDecl(SizeOfArg, DstArg))
  8823. PatternType = 1;
  8824. // - sizeof(src)
  8825. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8826. PatternType = 2;
  8827. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8828. if (BE->getOpcode() == BO_Sub) {
  8829. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8830. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8831. // - sizeof(dst) - strlen(dst)
  8832. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8833. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8834. PatternType = 1;
  8835. // - sizeof(src) - (anything)
  8836. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8837. PatternType = 2;
  8838. }
  8839. }
  8840. if (PatternType == 0)
  8841. return;
  8842. // Generate the diagnostic.
  8843. SourceLocation SL = LenArg->getBeginLoc();
  8844. SourceRange SR = LenArg->getSourceRange();
  8845. SourceManager &SM = getSourceManager();
  8846. // If the function is defined as a builtin macro, do not show macro expansion.
  8847. if (SM.isMacroArgExpansion(SL)) {
  8848. SL = SM.getSpellingLoc(SL);
  8849. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8850. SM.getSpellingLoc(SR.getEnd()));
  8851. }
  8852. // Check if the destination is an array (rather than a pointer to an array).
  8853. QualType DstTy = DstArg->getType();
  8854. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8855. Context);
  8856. if (!isKnownSizeArray) {
  8857. if (PatternType == 1)
  8858. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8859. else
  8860. Diag(SL, diag::warn_strncat_src_size) << SR;
  8861. return;
  8862. }
  8863. if (PatternType == 1)
  8864. Diag(SL, diag::warn_strncat_large_size) << SR;
  8865. else
  8866. Diag(SL, diag::warn_strncat_src_size) << SR;
  8867. SmallString<128> sizeString;
  8868. llvm::raw_svector_ostream OS(sizeString);
  8869. OS << "sizeof(";
  8870. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8871. OS << ") - ";
  8872. OS << "strlen(";
  8873. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8874. OS << ") - 1";
  8875. Diag(SL, diag::note_strncat_wrong_size)
  8876. << FixItHint::CreateReplacement(SR, OS.str());
  8877. }
  8878. void
  8879. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8880. SourceLocation ReturnLoc,
  8881. bool isObjCMethod,
  8882. const AttrVec *Attrs,
  8883. const FunctionDecl *FD) {
  8884. // Check if the return value is null but should not be.
  8885. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8886. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8887. CheckNonNullExpr(*this, RetValExp))
  8888. Diag(ReturnLoc, diag::warn_null_ret)
  8889. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8890. // C++11 [basic.stc.dynamic.allocation]p4:
  8891. // If an allocation function declared with a non-throwing
  8892. // exception-specification fails to allocate storage, it shall return
  8893. // a null pointer. Any other allocation function that fails to allocate
  8894. // storage shall indicate failure only by throwing an exception [...]
  8895. if (FD) {
  8896. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8897. if (Op == OO_New || Op == OO_Array_New) {
  8898. const FunctionProtoType *Proto
  8899. = FD->getType()->castAs<FunctionProtoType>();
  8900. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8901. CheckNonNullExpr(*this, RetValExp))
  8902. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8903. << FD << getLangOpts().CPlusPlus11;
  8904. }
  8905. }
  8906. }
  8907. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8908. /// Check for comparisons of floating point operands using != and ==.
  8909. /// Issue a warning if these are no self-comparisons, as they are not likely
  8910. /// to do what the programmer intended.
  8911. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8912. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8913. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8914. // Special case: check for x == x (which is OK).
  8915. // Do not emit warnings for such cases.
  8916. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8917. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8918. if (DRL->getDecl() == DRR->getDecl())
  8919. return;
  8920. // Special case: check for comparisons against literals that can be exactly
  8921. // represented by APFloat. In such cases, do not emit a warning. This
  8922. // is a heuristic: often comparison against such literals are used to
  8923. // detect if a value in a variable has not changed. This clearly can
  8924. // lead to false negatives.
  8925. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8926. if (FLL->isExact())
  8927. return;
  8928. } else
  8929. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8930. if (FLR->isExact())
  8931. return;
  8932. // Check for comparisons with builtin types.
  8933. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8934. if (CL->getBuiltinCallee())
  8935. return;
  8936. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8937. if (CR->getBuiltinCallee())
  8938. return;
  8939. // Emit the diagnostic.
  8940. Diag(Loc, diag::warn_floatingpoint_eq)
  8941. << LHS->getSourceRange() << RHS->getSourceRange();
  8942. }
  8943. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8944. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8945. namespace {
  8946. /// Structure recording the 'active' range of an integer-valued
  8947. /// expression.
  8948. struct IntRange {
  8949. /// The number of bits active in the int.
  8950. unsigned Width;
  8951. /// True if the int is known not to have negative values.
  8952. bool NonNegative;
  8953. IntRange(unsigned Width, bool NonNegative)
  8954. : Width(Width), NonNegative(NonNegative) {}
  8955. /// Returns the range of the bool type.
  8956. static IntRange forBoolType() {
  8957. return IntRange(1, true);
  8958. }
  8959. /// Returns the range of an opaque value of the given integral type.
  8960. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8961. return forValueOfCanonicalType(C,
  8962. T->getCanonicalTypeInternal().getTypePtr());
  8963. }
  8964. /// Returns the range of an opaque value of a canonical integral type.
  8965. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8966. assert(T->isCanonicalUnqualified());
  8967. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8968. T = VT->getElementType().getTypePtr();
  8969. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8970. T = CT->getElementType().getTypePtr();
  8971. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8972. T = AT->getValueType().getTypePtr();
  8973. if (!C.getLangOpts().CPlusPlus) {
  8974. // For enum types in C code, use the underlying datatype.
  8975. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8976. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8977. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8978. // For enum types in C++, use the known bit width of the enumerators.
  8979. EnumDecl *Enum = ET->getDecl();
  8980. // In C++11, enums can have a fixed underlying type. Use this type to
  8981. // compute the range.
  8982. if (Enum->isFixed()) {
  8983. return IntRange(C.getIntWidth(QualType(T, 0)),
  8984. !ET->isSignedIntegerOrEnumerationType());
  8985. }
  8986. unsigned NumPositive = Enum->getNumPositiveBits();
  8987. unsigned NumNegative = Enum->getNumNegativeBits();
  8988. if (NumNegative == 0)
  8989. return IntRange(NumPositive, true/*NonNegative*/);
  8990. else
  8991. return IntRange(std::max(NumPositive + 1, NumNegative),
  8992. false/*NonNegative*/);
  8993. }
  8994. const BuiltinType *BT = cast<BuiltinType>(T);
  8995. assert(BT->isInteger());
  8996. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8997. }
  8998. /// Returns the "target" range of a canonical integral type, i.e.
  8999. /// the range of values expressible in the type.
  9000. ///
  9001. /// This matches forValueOfCanonicalType except that enums have the
  9002. /// full range of their type, not the range of their enumerators.
  9003. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  9004. assert(T->isCanonicalUnqualified());
  9005. if (const VectorType *VT = dyn_cast<VectorType>(T))
  9006. T = VT->getElementType().getTypePtr();
  9007. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  9008. T = CT->getElementType().getTypePtr();
  9009. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  9010. T = AT->getValueType().getTypePtr();
  9011. if (const EnumType *ET = dyn_cast<EnumType>(T))
  9012. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  9013. const BuiltinType *BT = cast<BuiltinType>(T);
  9014. assert(BT->isInteger());
  9015. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  9016. }
  9017. /// Returns the supremum of two ranges: i.e. their conservative merge.
  9018. static IntRange join(IntRange L, IntRange R) {
  9019. return IntRange(std::max(L.Width, R.Width),
  9020. L.NonNegative && R.NonNegative);
  9021. }
  9022. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  9023. static IntRange meet(IntRange L, IntRange R) {
  9024. return IntRange(std::min(L.Width, R.Width),
  9025. L.NonNegative || R.NonNegative);
  9026. }
  9027. };
  9028. } // namespace
  9029. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  9030. unsigned MaxWidth) {
  9031. if (value.isSigned() && value.isNegative())
  9032. return IntRange(value.getMinSignedBits(), false);
  9033. if (value.getBitWidth() > MaxWidth)
  9034. value = value.trunc(MaxWidth);
  9035. // isNonNegative() just checks the sign bit without considering
  9036. // signedness.
  9037. return IntRange(value.getActiveBits(), true);
  9038. }
  9039. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  9040. unsigned MaxWidth) {
  9041. if (result.isInt())
  9042. return GetValueRange(C, result.getInt(), MaxWidth);
  9043. if (result.isVector()) {
  9044. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  9045. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  9046. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  9047. R = IntRange::join(R, El);
  9048. }
  9049. return R;
  9050. }
  9051. if (result.isComplexInt()) {
  9052. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  9053. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  9054. return IntRange::join(R, I);
  9055. }
  9056. // This can happen with lossless casts to intptr_t of "based" lvalues.
  9057. // Assume it might use arbitrary bits.
  9058. // FIXME: The only reason we need to pass the type in here is to get
  9059. // the sign right on this one case. It would be nice if APValue
  9060. // preserved this.
  9061. assert(result.isLValue() || result.isAddrLabelDiff());
  9062. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  9063. }
  9064. static QualType GetExprType(const Expr *E) {
  9065. QualType Ty = E->getType();
  9066. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  9067. Ty = AtomicRHS->getValueType();
  9068. return Ty;
  9069. }
  9070. /// Pseudo-evaluate the given integer expression, estimating the
  9071. /// range of values it might take.
  9072. ///
  9073. /// \param MaxWidth - the width to which the value will be truncated
  9074. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
  9075. bool InConstantContext) {
  9076. E = E->IgnoreParens();
  9077. // Try a full evaluation first.
  9078. Expr::EvalResult result;
  9079. if (E->EvaluateAsRValue(result, C, InConstantContext))
  9080. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  9081. // I think we only want to look through implicit casts here; if the
  9082. // user has an explicit widening cast, we should treat the value as
  9083. // being of the new, wider type.
  9084. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  9085. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  9086. return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
  9087. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  9088. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  9089. CE->getCastKind() == CK_BooleanToSignedIntegral;
  9090. // Assume that non-integer casts can span the full range of the type.
  9091. if (!isIntegerCast)
  9092. return OutputTypeRange;
  9093. IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
  9094. std::min(MaxWidth, OutputTypeRange.Width),
  9095. InConstantContext);
  9096. // Bail out if the subexpr's range is as wide as the cast type.
  9097. if (SubRange.Width >= OutputTypeRange.Width)
  9098. return OutputTypeRange;
  9099. // Otherwise, we take the smaller width, and we're non-negative if
  9100. // either the output type or the subexpr is.
  9101. return IntRange(SubRange.Width,
  9102. SubRange.NonNegative || OutputTypeRange.NonNegative);
  9103. }
  9104. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  9105. // If we can fold the condition, just take that operand.
  9106. bool CondResult;
  9107. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  9108. return GetExprRange(C,
  9109. CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
  9110. MaxWidth, InConstantContext);
  9111. // Otherwise, conservatively merge.
  9112. IntRange L =
  9113. GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
  9114. IntRange R =
  9115. GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
  9116. return IntRange::join(L, R);
  9117. }
  9118. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  9119. switch (BO->getOpcode()) {
  9120. case BO_Cmp:
  9121. llvm_unreachable("builtin <=> should have class type");
  9122. // Boolean-valued operations are single-bit and positive.
  9123. case BO_LAnd:
  9124. case BO_LOr:
  9125. case BO_LT:
  9126. case BO_GT:
  9127. case BO_LE:
  9128. case BO_GE:
  9129. case BO_EQ:
  9130. case BO_NE:
  9131. return IntRange::forBoolType();
  9132. // The type of the assignments is the type of the LHS, so the RHS
  9133. // is not necessarily the same type.
  9134. case BO_MulAssign:
  9135. case BO_DivAssign:
  9136. case BO_RemAssign:
  9137. case BO_AddAssign:
  9138. case BO_SubAssign:
  9139. case BO_XorAssign:
  9140. case BO_OrAssign:
  9141. // TODO: bitfields?
  9142. return IntRange::forValueOfType(C, GetExprType(E));
  9143. // Simple assignments just pass through the RHS, which will have
  9144. // been coerced to the LHS type.
  9145. case BO_Assign:
  9146. // TODO: bitfields?
  9147. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9148. // Operations with opaque sources are black-listed.
  9149. case BO_PtrMemD:
  9150. case BO_PtrMemI:
  9151. return IntRange::forValueOfType(C, GetExprType(E));
  9152. // Bitwise-and uses the *infinum* of the two source ranges.
  9153. case BO_And:
  9154. case BO_AndAssign:
  9155. return IntRange::meet(
  9156. GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
  9157. GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
  9158. // Left shift gets black-listed based on a judgement call.
  9159. case BO_Shl:
  9160. // ...except that we want to treat '1 << (blah)' as logically
  9161. // positive. It's an important idiom.
  9162. if (IntegerLiteral *I
  9163. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  9164. if (I->getValue() == 1) {
  9165. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  9166. return IntRange(R.Width, /*NonNegative*/ true);
  9167. }
  9168. }
  9169. LLVM_FALLTHROUGH;
  9170. case BO_ShlAssign:
  9171. return IntRange::forValueOfType(C, GetExprType(E));
  9172. // Right shift by a constant can narrow its left argument.
  9173. case BO_Shr:
  9174. case BO_ShrAssign: {
  9175. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9176. // If the shift amount is a positive constant, drop the width by
  9177. // that much.
  9178. llvm::APSInt shift;
  9179. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  9180. shift.isNonNegative()) {
  9181. unsigned zext = shift.getZExtValue();
  9182. if (zext >= L.Width)
  9183. L.Width = (L.NonNegative ? 0 : 1);
  9184. else
  9185. L.Width -= zext;
  9186. }
  9187. return L;
  9188. }
  9189. // Comma acts as its right operand.
  9190. case BO_Comma:
  9191. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9192. // Black-list pointer subtractions.
  9193. case BO_Sub:
  9194. if (BO->getLHS()->getType()->isPointerType())
  9195. return IntRange::forValueOfType(C, GetExprType(E));
  9196. break;
  9197. // The width of a division result is mostly determined by the size
  9198. // of the LHS.
  9199. case BO_Div: {
  9200. // Don't 'pre-truncate' the operands.
  9201. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9202. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9203. // If the divisor is constant, use that.
  9204. llvm::APSInt divisor;
  9205. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  9206. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  9207. if (log2 >= L.Width)
  9208. L.Width = (L.NonNegative ? 0 : 1);
  9209. else
  9210. L.Width = std::min(L.Width - log2, MaxWidth);
  9211. return L;
  9212. }
  9213. // Otherwise, just use the LHS's width.
  9214. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9215. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  9216. }
  9217. // The result of a remainder can't be larger than the result of
  9218. // either side.
  9219. case BO_Rem: {
  9220. // Don't 'pre-truncate' the operands.
  9221. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9222. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9223. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9224. IntRange meet = IntRange::meet(L, R);
  9225. meet.Width = std::min(meet.Width, MaxWidth);
  9226. return meet;
  9227. }
  9228. // The default behavior is okay for these.
  9229. case BO_Mul:
  9230. case BO_Add:
  9231. case BO_Xor:
  9232. case BO_Or:
  9233. break;
  9234. }
  9235. // The default case is to treat the operation as if it were closed
  9236. // on the narrowest type that encompasses both operands.
  9237. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9238. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9239. return IntRange::join(L, R);
  9240. }
  9241. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  9242. switch (UO->getOpcode()) {
  9243. // Boolean-valued operations are white-listed.
  9244. case UO_LNot:
  9245. return IntRange::forBoolType();
  9246. // Operations with opaque sources are black-listed.
  9247. case UO_Deref:
  9248. case UO_AddrOf: // should be impossible
  9249. return IntRange::forValueOfType(C, GetExprType(E));
  9250. default:
  9251. return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
  9252. }
  9253. }
  9254. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  9255. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
  9256. if (const auto *BitField = E->getSourceBitField())
  9257. return IntRange(BitField->getBitWidthValue(C),
  9258. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  9259. return IntRange::forValueOfType(C, GetExprType(E));
  9260. }
  9261. static IntRange GetExprRange(ASTContext &C, const Expr *E,
  9262. bool InConstantContext) {
  9263. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
  9264. }
  9265. /// Checks whether the given value, which currently has the given
  9266. /// source semantics, has the same value when coerced through the
  9267. /// target semantics.
  9268. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  9269. const llvm::fltSemantics &Src,
  9270. const llvm::fltSemantics &Tgt) {
  9271. llvm::APFloat truncated = value;
  9272. bool ignored;
  9273. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9274. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9275. return truncated.bitwiseIsEqual(value);
  9276. }
  9277. /// Checks whether the given value, which currently has the given
  9278. /// source semantics, has the same value when coerced through the
  9279. /// target semantics.
  9280. ///
  9281. /// The value might be a vector of floats (or a complex number).
  9282. static bool IsSameFloatAfterCast(const APValue &value,
  9283. const llvm::fltSemantics &Src,
  9284. const llvm::fltSemantics &Tgt) {
  9285. if (value.isFloat())
  9286. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  9287. if (value.isVector()) {
  9288. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  9289. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  9290. return false;
  9291. return true;
  9292. }
  9293. assert(value.isComplexFloat());
  9294. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  9295. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  9296. }
  9297. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
  9298. bool IsListInit = false);
  9299. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  9300. // Suppress cases where we are comparing against an enum constant.
  9301. if (const DeclRefExpr *DR =
  9302. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  9303. if (isa<EnumConstantDecl>(DR->getDecl()))
  9304. return true;
  9305. // Suppress cases where the value is expanded from a macro, unless that macro
  9306. // is how a language represents a boolean literal. This is the case in both C
  9307. // and Objective-C.
  9308. SourceLocation BeginLoc = E->getBeginLoc();
  9309. if (BeginLoc.isMacroID()) {
  9310. StringRef MacroName = Lexer::getImmediateMacroName(
  9311. BeginLoc, S.getSourceManager(), S.getLangOpts());
  9312. return MacroName != "YES" && MacroName != "NO" &&
  9313. MacroName != "true" && MacroName != "false";
  9314. }
  9315. return false;
  9316. }
  9317. static bool isKnownToHaveUnsignedValue(Expr *E) {
  9318. return E->getType()->isIntegerType() &&
  9319. (!E->getType()->isSignedIntegerType() ||
  9320. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  9321. }
  9322. namespace {
  9323. /// The promoted range of values of a type. In general this has the
  9324. /// following structure:
  9325. ///
  9326. /// |-----------| . . . |-----------|
  9327. /// ^ ^ ^ ^
  9328. /// Min HoleMin HoleMax Max
  9329. ///
  9330. /// ... where there is only a hole if a signed type is promoted to unsigned
  9331. /// (in which case Min and Max are the smallest and largest representable
  9332. /// values).
  9333. struct PromotedRange {
  9334. // Min, or HoleMax if there is a hole.
  9335. llvm::APSInt PromotedMin;
  9336. // Max, or HoleMin if there is a hole.
  9337. llvm::APSInt PromotedMax;
  9338. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  9339. if (R.Width == 0)
  9340. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  9341. else if (R.Width >= BitWidth && !Unsigned) {
  9342. // Promotion made the type *narrower*. This happens when promoting
  9343. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  9344. // Treat all values of 'signed int' as being in range for now.
  9345. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  9346. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  9347. } else {
  9348. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  9349. .extOrTrunc(BitWidth);
  9350. PromotedMin.setIsUnsigned(Unsigned);
  9351. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  9352. .extOrTrunc(BitWidth);
  9353. PromotedMax.setIsUnsigned(Unsigned);
  9354. }
  9355. }
  9356. // Determine whether this range is contiguous (has no hole).
  9357. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  9358. // Where a constant value is within the range.
  9359. enum ComparisonResult {
  9360. LT = 0x1,
  9361. LE = 0x2,
  9362. GT = 0x4,
  9363. GE = 0x8,
  9364. EQ = 0x10,
  9365. NE = 0x20,
  9366. InRangeFlag = 0x40,
  9367. Less = LE | LT | NE,
  9368. Min = LE | InRangeFlag,
  9369. InRange = InRangeFlag,
  9370. Max = GE | InRangeFlag,
  9371. Greater = GE | GT | NE,
  9372. OnlyValue = LE | GE | EQ | InRangeFlag,
  9373. InHole = NE
  9374. };
  9375. ComparisonResult compare(const llvm::APSInt &Value) const {
  9376. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  9377. Value.isUnsigned() == PromotedMin.isUnsigned());
  9378. if (!isContiguous()) {
  9379. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  9380. if (Value.isMinValue()) return Min;
  9381. if (Value.isMaxValue()) return Max;
  9382. if (Value >= PromotedMin) return InRange;
  9383. if (Value <= PromotedMax) return InRange;
  9384. return InHole;
  9385. }
  9386. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  9387. case -1: return Less;
  9388. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  9389. case 1:
  9390. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  9391. case -1: return InRange;
  9392. case 0: return Max;
  9393. case 1: return Greater;
  9394. }
  9395. }
  9396. llvm_unreachable("impossible compare result");
  9397. }
  9398. static llvm::Optional<StringRef>
  9399. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  9400. if (Op == BO_Cmp) {
  9401. ComparisonResult LTFlag = LT, GTFlag = GT;
  9402. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  9403. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  9404. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  9405. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  9406. return llvm::None;
  9407. }
  9408. ComparisonResult TrueFlag, FalseFlag;
  9409. if (Op == BO_EQ) {
  9410. TrueFlag = EQ;
  9411. FalseFlag = NE;
  9412. } else if (Op == BO_NE) {
  9413. TrueFlag = NE;
  9414. FalseFlag = EQ;
  9415. } else {
  9416. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  9417. TrueFlag = LT;
  9418. FalseFlag = GE;
  9419. } else {
  9420. TrueFlag = GT;
  9421. FalseFlag = LE;
  9422. }
  9423. if (Op == BO_GE || Op == BO_LE)
  9424. std::swap(TrueFlag, FalseFlag);
  9425. }
  9426. if (R & TrueFlag)
  9427. return StringRef("true");
  9428. if (R & FalseFlag)
  9429. return StringRef("false");
  9430. return llvm::None;
  9431. }
  9432. };
  9433. }
  9434. static bool HasEnumType(Expr *E) {
  9435. // Strip off implicit integral promotions.
  9436. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  9437. if (ICE->getCastKind() != CK_IntegralCast &&
  9438. ICE->getCastKind() != CK_NoOp)
  9439. break;
  9440. E = ICE->getSubExpr();
  9441. }
  9442. return E->getType()->isEnumeralType();
  9443. }
  9444. static int classifyConstantValue(Expr *Constant) {
  9445. // The values of this enumeration are used in the diagnostics
  9446. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  9447. enum ConstantValueKind {
  9448. Miscellaneous = 0,
  9449. LiteralTrue,
  9450. LiteralFalse
  9451. };
  9452. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  9453. return BL->getValue() ? ConstantValueKind::LiteralTrue
  9454. : ConstantValueKind::LiteralFalse;
  9455. return ConstantValueKind::Miscellaneous;
  9456. }
  9457. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  9458. Expr *Constant, Expr *Other,
  9459. const llvm::APSInt &Value,
  9460. bool RhsConstant) {
  9461. if (S.inTemplateInstantiation())
  9462. return false;
  9463. Expr *OriginalOther = Other;
  9464. Constant = Constant->IgnoreParenImpCasts();
  9465. Other = Other->IgnoreParenImpCasts();
  9466. // Suppress warnings on tautological comparisons between values of the same
  9467. // enumeration type. There are only two ways we could warn on this:
  9468. // - If the constant is outside the range of representable values of
  9469. // the enumeration. In such a case, we should warn about the cast
  9470. // to enumeration type, not about the comparison.
  9471. // - If the constant is the maximum / minimum in-range value. For an
  9472. // enumeratin type, such comparisons can be meaningful and useful.
  9473. if (Constant->getType()->isEnumeralType() &&
  9474. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  9475. return false;
  9476. // TODO: Investigate using GetExprRange() to get tighter bounds
  9477. // on the bit ranges.
  9478. QualType OtherT = Other->getType();
  9479. if (const auto *AT = OtherT->getAs<AtomicType>())
  9480. OtherT = AT->getValueType();
  9481. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  9482. // Special case for ObjC BOOL on targets where its a typedef for a signed char
  9483. // (Namely, macOS).
  9484. bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
  9485. S.NSAPIObj->isObjCBOOLType(OtherT) &&
  9486. OtherT->isSpecificBuiltinType(BuiltinType::SChar);
  9487. // Whether we're treating Other as being a bool because of the form of
  9488. // expression despite it having another type (typically 'int' in C).
  9489. bool OtherIsBooleanDespiteType =
  9490. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  9491. if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
  9492. OtherRange = IntRange::forBoolType();
  9493. // Determine the promoted range of the other type and see if a comparison of
  9494. // the constant against that range is tautological.
  9495. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  9496. Value.isUnsigned());
  9497. auto Cmp = OtherPromotedRange.compare(Value);
  9498. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  9499. if (!Result)
  9500. return false;
  9501. // Suppress the diagnostic for an in-range comparison if the constant comes
  9502. // from a macro or enumerator. We don't want to diagnose
  9503. //
  9504. // some_long_value <= INT_MAX
  9505. //
  9506. // when sizeof(int) == sizeof(long).
  9507. bool InRange = Cmp & PromotedRange::InRangeFlag;
  9508. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  9509. return false;
  9510. // If this is a comparison to an enum constant, include that
  9511. // constant in the diagnostic.
  9512. const EnumConstantDecl *ED = nullptr;
  9513. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  9514. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  9515. // Should be enough for uint128 (39 decimal digits)
  9516. SmallString<64> PrettySourceValue;
  9517. llvm::raw_svector_ostream OS(PrettySourceValue);
  9518. if (ED) {
  9519. OS << '\'' << *ED << "' (" << Value << ")";
  9520. } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
  9521. Constant->IgnoreParenImpCasts())) {
  9522. OS << (BL->getValue() ? "YES" : "NO");
  9523. } else {
  9524. OS << Value;
  9525. }
  9526. if (IsObjCSignedCharBool) {
  9527. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9528. S.PDiag(diag::warn_tautological_compare_objc_bool)
  9529. << OS.str() << *Result);
  9530. return true;
  9531. }
  9532. // FIXME: We use a somewhat different formatting for the in-range cases and
  9533. // cases involving boolean values for historical reasons. We should pick a
  9534. // consistent way of presenting these diagnostics.
  9535. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  9536. S.DiagRuntimeBehavior(
  9537. E->getOperatorLoc(), E,
  9538. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  9539. : diag::warn_tautological_bool_compare)
  9540. << OS.str() << classifyConstantValue(Constant) << OtherT
  9541. << OtherIsBooleanDespiteType << *Result
  9542. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  9543. } else {
  9544. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  9545. ? (HasEnumType(OriginalOther)
  9546. ? diag::warn_unsigned_enum_always_true_comparison
  9547. : diag::warn_unsigned_always_true_comparison)
  9548. : diag::warn_tautological_constant_compare;
  9549. S.Diag(E->getOperatorLoc(), Diag)
  9550. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  9551. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  9552. }
  9553. return true;
  9554. }
  9555. /// Analyze the operands of the given comparison. Implements the
  9556. /// fallback case from AnalyzeComparison.
  9557. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  9558. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9559. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9560. }
  9561. /// Implements -Wsign-compare.
  9562. ///
  9563. /// \param E the binary operator to check for warnings
  9564. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  9565. // The type the comparison is being performed in.
  9566. QualType T = E->getLHS()->getType();
  9567. // Only analyze comparison operators where both sides have been converted to
  9568. // the same type.
  9569. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  9570. return AnalyzeImpConvsInComparison(S, E);
  9571. // Don't analyze value-dependent comparisons directly.
  9572. if (E->isValueDependent())
  9573. return AnalyzeImpConvsInComparison(S, E);
  9574. Expr *LHS = E->getLHS();
  9575. Expr *RHS = E->getRHS();
  9576. if (T->isIntegralType(S.Context)) {
  9577. llvm::APSInt RHSValue;
  9578. llvm::APSInt LHSValue;
  9579. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  9580. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  9581. // We don't care about expressions whose result is a constant.
  9582. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  9583. return AnalyzeImpConvsInComparison(S, E);
  9584. // We only care about expressions where just one side is literal
  9585. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  9586. // Is the constant on the RHS or LHS?
  9587. const bool RhsConstant = IsRHSIntegralLiteral;
  9588. Expr *Const = RhsConstant ? RHS : LHS;
  9589. Expr *Other = RhsConstant ? LHS : RHS;
  9590. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  9591. // Check whether an integer constant comparison results in a value
  9592. // of 'true' or 'false'.
  9593. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  9594. return AnalyzeImpConvsInComparison(S, E);
  9595. }
  9596. }
  9597. if (!T->hasUnsignedIntegerRepresentation()) {
  9598. // We don't do anything special if this isn't an unsigned integral
  9599. // comparison: we're only interested in integral comparisons, and
  9600. // signed comparisons only happen in cases we don't care to warn about.
  9601. return AnalyzeImpConvsInComparison(S, E);
  9602. }
  9603. LHS = LHS->IgnoreParenImpCasts();
  9604. RHS = RHS->IgnoreParenImpCasts();
  9605. if (!S.getLangOpts().CPlusPlus) {
  9606. // Avoid warning about comparison of integers with different signs when
  9607. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9608. // the type of `E`.
  9609. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9610. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9611. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9612. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9613. }
  9614. // Check to see if one of the (unmodified) operands is of different
  9615. // signedness.
  9616. Expr *signedOperand, *unsignedOperand;
  9617. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9618. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9619. "unsigned comparison between two signed integer expressions?");
  9620. signedOperand = LHS;
  9621. unsignedOperand = RHS;
  9622. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9623. signedOperand = RHS;
  9624. unsignedOperand = LHS;
  9625. } else {
  9626. return AnalyzeImpConvsInComparison(S, E);
  9627. }
  9628. // Otherwise, calculate the effective range of the signed operand.
  9629. IntRange signedRange =
  9630. GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
  9631. // Go ahead and analyze implicit conversions in the operands. Note
  9632. // that we skip the implicit conversions on both sides.
  9633. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9634. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9635. // If the signed range is non-negative, -Wsign-compare won't fire.
  9636. if (signedRange.NonNegative)
  9637. return;
  9638. // For (in)equality comparisons, if the unsigned operand is a
  9639. // constant which cannot collide with a overflowed signed operand,
  9640. // then reinterpreting the signed operand as unsigned will not
  9641. // change the result of the comparison.
  9642. if (E->isEqualityOp()) {
  9643. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9644. IntRange unsignedRange =
  9645. GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
  9646. // We should never be unable to prove that the unsigned operand is
  9647. // non-negative.
  9648. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9649. if (unsignedRange.Width < comparisonWidth)
  9650. return;
  9651. }
  9652. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9653. S.PDiag(diag::warn_mixed_sign_comparison)
  9654. << LHS->getType() << RHS->getType()
  9655. << LHS->getSourceRange() << RHS->getSourceRange());
  9656. }
  9657. /// Analyzes an attempt to assign the given value to a bitfield.
  9658. ///
  9659. /// Returns true if there was something fishy about the attempt.
  9660. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9661. SourceLocation InitLoc) {
  9662. assert(Bitfield->isBitField());
  9663. if (Bitfield->isInvalidDecl())
  9664. return false;
  9665. // White-list bool bitfields.
  9666. QualType BitfieldType = Bitfield->getType();
  9667. if (BitfieldType->isBooleanType())
  9668. return false;
  9669. if (BitfieldType->isEnumeralType()) {
  9670. EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
  9671. // If the underlying enum type was not explicitly specified as an unsigned
  9672. // type and the enum contain only positive values, MSVC++ will cause an
  9673. // inconsistency by storing this as a signed type.
  9674. if (S.getLangOpts().CPlusPlus11 &&
  9675. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9676. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9677. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9678. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9679. << BitfieldEnumDecl->getNameAsString();
  9680. }
  9681. }
  9682. if (Bitfield->getType()->isBooleanType())
  9683. return false;
  9684. // Ignore value- or type-dependent expressions.
  9685. if (Bitfield->getBitWidth()->isValueDependent() ||
  9686. Bitfield->getBitWidth()->isTypeDependent() ||
  9687. Init->isValueDependent() ||
  9688. Init->isTypeDependent())
  9689. return false;
  9690. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9691. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9692. Expr::EvalResult Result;
  9693. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  9694. Expr::SE_AllowSideEffects)) {
  9695. // The RHS is not constant. If the RHS has an enum type, make sure the
  9696. // bitfield is wide enough to hold all the values of the enum without
  9697. // truncation.
  9698. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9699. EnumDecl *ED = EnumTy->getDecl();
  9700. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9701. // Enum types are implicitly signed on Windows, so check if there are any
  9702. // negative enumerators to see if the enum was intended to be signed or
  9703. // not.
  9704. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9705. // Check for surprising sign changes when assigning enum values to a
  9706. // bitfield of different signedness. If the bitfield is signed and we
  9707. // have exactly the right number of bits to store this unsigned enum,
  9708. // suggest changing the enum to an unsigned type. This typically happens
  9709. // on Windows where unfixed enums always use an underlying type of 'int'.
  9710. unsigned DiagID = 0;
  9711. if (SignedEnum && !SignedBitfield) {
  9712. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9713. } else if (SignedBitfield && !SignedEnum &&
  9714. ED->getNumPositiveBits() == FieldWidth) {
  9715. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9716. }
  9717. if (DiagID) {
  9718. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9719. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9720. SourceRange TypeRange =
  9721. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9722. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9723. << SignedEnum << TypeRange;
  9724. }
  9725. // Compute the required bitwidth. If the enum has negative values, we need
  9726. // one more bit than the normal number of positive bits to represent the
  9727. // sign bit.
  9728. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9729. ED->getNumNegativeBits())
  9730. : ED->getNumPositiveBits();
  9731. // Check the bitwidth.
  9732. if (BitsNeeded > FieldWidth) {
  9733. Expr *WidthExpr = Bitfield->getBitWidth();
  9734. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9735. << Bitfield << ED;
  9736. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9737. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9738. }
  9739. }
  9740. return false;
  9741. }
  9742. llvm::APSInt Value = Result.Val.getInt();
  9743. unsigned OriginalWidth = Value.getBitWidth();
  9744. if (!Value.isSigned() || Value.isNegative())
  9745. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9746. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9747. OriginalWidth = Value.getMinSignedBits();
  9748. if (OriginalWidth <= FieldWidth)
  9749. return false;
  9750. // Compute the value which the bitfield will contain.
  9751. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9752. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9753. // Check whether the stored value is equal to the original value.
  9754. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9755. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9756. return false;
  9757. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9758. // therefore don't strictly fit into a signed bitfield of width 1.
  9759. if (FieldWidth == 1 && Value == 1)
  9760. return false;
  9761. std::string PrettyValue = Value.toString(10);
  9762. std::string PrettyTrunc = TruncatedValue.toString(10);
  9763. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9764. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9765. << Init->getSourceRange();
  9766. return true;
  9767. }
  9768. /// Analyze the given simple or compound assignment for warning-worthy
  9769. /// operations.
  9770. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9771. // Just recurse on the LHS.
  9772. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9773. // We want to recurse on the RHS as normal unless we're assigning to
  9774. // a bitfield.
  9775. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9776. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9777. E->getOperatorLoc())) {
  9778. // Recurse, ignoring any implicit conversions on the RHS.
  9779. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9780. E->getOperatorLoc());
  9781. }
  9782. }
  9783. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9784. // Diagnose implicitly sequentially-consistent atomic assignment.
  9785. if (E->getLHS()->getType()->isAtomicType())
  9786. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9787. }
  9788. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9789. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9790. SourceLocation CContext, unsigned diag,
  9791. bool pruneControlFlow = false) {
  9792. if (pruneControlFlow) {
  9793. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9794. S.PDiag(diag)
  9795. << SourceType << T << E->getSourceRange()
  9796. << SourceRange(CContext));
  9797. return;
  9798. }
  9799. S.Diag(E->getExprLoc(), diag)
  9800. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9801. }
  9802. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9803. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9804. SourceLocation CContext,
  9805. unsigned diag, bool pruneControlFlow = false) {
  9806. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9807. }
  9808. static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
  9809. return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
  9810. S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
  9811. }
  9812. static void adornObjCBoolConversionDiagWithTernaryFixit(
  9813. Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
  9814. Expr *Ignored = SourceExpr->IgnoreImplicit();
  9815. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
  9816. Ignored = OVE->getSourceExpr();
  9817. bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
  9818. isa<BinaryOperator>(Ignored) ||
  9819. isa<CXXOperatorCallExpr>(Ignored);
  9820. SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
  9821. if (NeedsParens)
  9822. Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
  9823. << FixItHint::CreateInsertion(EndLoc, ")");
  9824. Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
  9825. }
  9826. /// Diagnose an implicit cast from a floating point value to an integer value.
  9827. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9828. SourceLocation CContext) {
  9829. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9830. const bool PruneWarnings = S.inTemplateInstantiation();
  9831. Expr *InnerE = E->IgnoreParenImpCasts();
  9832. // We also want to warn on, e.g., "int i = -1.234"
  9833. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9834. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9835. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9836. const bool IsLiteral =
  9837. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9838. llvm::APFloat Value(0.0);
  9839. bool IsConstant =
  9840. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9841. if (!IsConstant) {
  9842. if (isObjCSignedCharBool(S, T)) {
  9843. return adornObjCBoolConversionDiagWithTernaryFixit(
  9844. S, E,
  9845. S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
  9846. << E->getType());
  9847. }
  9848. return DiagnoseImpCast(S, E, T, CContext,
  9849. diag::warn_impcast_float_integer, PruneWarnings);
  9850. }
  9851. bool isExact = false;
  9852. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9853. T->hasUnsignedIntegerRepresentation());
  9854. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9855. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9856. // FIXME: Force the precision of the source value down so we don't print
  9857. // digits which are usually useless (we don't really care here if we
  9858. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9859. // would automatically print the shortest representation, but it's a bit
  9860. // tricky to implement.
  9861. SmallString<16> PrettySourceValue;
  9862. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9863. precision = (precision * 59 + 195) / 196;
  9864. Value.toString(PrettySourceValue, precision);
  9865. if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
  9866. return adornObjCBoolConversionDiagWithTernaryFixit(
  9867. S, E,
  9868. S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
  9869. << PrettySourceValue);
  9870. }
  9871. if (Result == llvm::APFloat::opOK && isExact) {
  9872. if (IsLiteral) return;
  9873. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9874. PruneWarnings);
  9875. }
  9876. // Conversion of a floating-point value to a non-bool integer where the
  9877. // integral part cannot be represented by the integer type is undefined.
  9878. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9879. return DiagnoseImpCast(
  9880. S, E, T, CContext,
  9881. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9882. : diag::warn_impcast_float_to_integer_out_of_range,
  9883. PruneWarnings);
  9884. unsigned DiagID = 0;
  9885. if (IsLiteral) {
  9886. // Warn on floating point literal to integer.
  9887. DiagID = diag::warn_impcast_literal_float_to_integer;
  9888. } else if (IntegerValue == 0) {
  9889. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9890. return DiagnoseImpCast(S, E, T, CContext,
  9891. diag::warn_impcast_float_integer, PruneWarnings);
  9892. }
  9893. // Warn on non-zero to zero conversion.
  9894. DiagID = diag::warn_impcast_float_to_integer_zero;
  9895. } else {
  9896. if (IntegerValue.isUnsigned()) {
  9897. if (!IntegerValue.isMaxValue()) {
  9898. return DiagnoseImpCast(S, E, T, CContext,
  9899. diag::warn_impcast_float_integer, PruneWarnings);
  9900. }
  9901. } else { // IntegerValue.isSigned()
  9902. if (!IntegerValue.isMaxSignedValue() &&
  9903. !IntegerValue.isMinSignedValue()) {
  9904. return DiagnoseImpCast(S, E, T, CContext,
  9905. diag::warn_impcast_float_integer, PruneWarnings);
  9906. }
  9907. }
  9908. // Warn on evaluatable floating point expression to integer conversion.
  9909. DiagID = diag::warn_impcast_float_to_integer;
  9910. }
  9911. SmallString<16> PrettyTargetValue;
  9912. if (IsBool)
  9913. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9914. else
  9915. IntegerValue.toString(PrettyTargetValue);
  9916. if (PruneWarnings) {
  9917. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9918. S.PDiag(DiagID)
  9919. << E->getType() << T.getUnqualifiedType()
  9920. << PrettySourceValue << PrettyTargetValue
  9921. << E->getSourceRange() << SourceRange(CContext));
  9922. } else {
  9923. S.Diag(E->getExprLoc(), DiagID)
  9924. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9925. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9926. }
  9927. }
  9928. /// Analyze the given compound assignment for the possible losing of
  9929. /// floating-point precision.
  9930. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9931. assert(isa<CompoundAssignOperator>(E) &&
  9932. "Must be compound assignment operation");
  9933. // Recurse on the LHS and RHS in here
  9934. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9935. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9936. if (E->getLHS()->getType()->isAtomicType())
  9937. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  9938. // Now check the outermost expression
  9939. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9940. const auto *RBT = cast<CompoundAssignOperator>(E)
  9941. ->getComputationResultType()
  9942. ->getAs<BuiltinType>();
  9943. // The below checks assume source is floating point.
  9944. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  9945. // If source is floating point but target is an integer.
  9946. if (ResultBT->isInteger())
  9947. return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
  9948. E->getExprLoc(), diag::warn_impcast_float_integer);
  9949. if (!ResultBT->isFloatingPoint())
  9950. return;
  9951. // If both source and target are floating points, warn about losing precision.
  9952. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9953. QualType(ResultBT, 0), QualType(RBT, 0));
  9954. if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9955. // warn about dropping FP rank.
  9956. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  9957. diag::warn_impcast_float_result_precision);
  9958. }
  9959. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9960. IntRange Range) {
  9961. if (!Range.Width) return "0";
  9962. llvm::APSInt ValueInRange = Value;
  9963. ValueInRange.setIsSigned(!Range.NonNegative);
  9964. ValueInRange = ValueInRange.trunc(Range.Width);
  9965. return ValueInRange.toString(10);
  9966. }
  9967. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9968. if (!isa<ImplicitCastExpr>(Ex))
  9969. return false;
  9970. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9971. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9972. const Type *Source =
  9973. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9974. if (Target->isDependentType())
  9975. return false;
  9976. const BuiltinType *FloatCandidateBT =
  9977. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9978. const Type *BoolCandidateType = ToBool ? Target : Source;
  9979. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9980. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9981. }
  9982. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9983. SourceLocation CC) {
  9984. unsigned NumArgs = TheCall->getNumArgs();
  9985. for (unsigned i = 0; i < NumArgs; ++i) {
  9986. Expr *CurrA = TheCall->getArg(i);
  9987. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9988. continue;
  9989. bool IsSwapped = ((i > 0) &&
  9990. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9991. IsSwapped |= ((i < (NumArgs - 1)) &&
  9992. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9993. if (IsSwapped) {
  9994. // Warn on this floating-point to bool conversion.
  9995. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9996. CurrA->getType(), CC,
  9997. diag::warn_impcast_floating_point_to_bool);
  9998. }
  9999. }
  10000. }
  10001. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  10002. SourceLocation CC) {
  10003. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  10004. E->getExprLoc()))
  10005. return;
  10006. // Don't warn on functions which have return type nullptr_t.
  10007. if (isa<CallExpr>(E))
  10008. return;
  10009. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  10010. const Expr::NullPointerConstantKind NullKind =
  10011. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  10012. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  10013. return;
  10014. // Return if target type is a safe conversion.
  10015. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  10016. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  10017. return;
  10018. SourceLocation Loc = E->getSourceRange().getBegin();
  10019. // Venture through the macro stacks to get to the source of macro arguments.
  10020. // The new location is a better location than the complete location that was
  10021. // passed in.
  10022. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  10023. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  10024. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  10025. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  10026. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  10027. Loc, S.SourceMgr, S.getLangOpts());
  10028. if (MacroName == "NULL")
  10029. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  10030. }
  10031. // Only warn if the null and context location are in the same macro expansion.
  10032. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  10033. return;
  10034. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  10035. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  10036. << FixItHint::CreateReplacement(Loc,
  10037. S.getFixItZeroLiteralForType(T, Loc));
  10038. }
  10039. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  10040. ObjCArrayLiteral *ArrayLiteral);
  10041. static void
  10042. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  10043. ObjCDictionaryLiteral *DictionaryLiteral);
  10044. /// Check a single element within a collection literal against the
  10045. /// target element type.
  10046. static void checkObjCCollectionLiteralElement(Sema &S,
  10047. QualType TargetElementType,
  10048. Expr *Element,
  10049. unsigned ElementKind) {
  10050. // Skip a bitcast to 'id' or qualified 'id'.
  10051. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  10052. if (ICE->getCastKind() == CK_BitCast &&
  10053. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  10054. Element = ICE->getSubExpr();
  10055. }
  10056. QualType ElementType = Element->getType();
  10057. ExprResult ElementResult(Element);
  10058. if (ElementType->getAs<ObjCObjectPointerType>() &&
  10059. S.CheckSingleAssignmentConstraints(TargetElementType,
  10060. ElementResult,
  10061. false, false)
  10062. != Sema::Compatible) {
  10063. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  10064. << ElementType << ElementKind << TargetElementType
  10065. << Element->getSourceRange();
  10066. }
  10067. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  10068. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  10069. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  10070. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  10071. }
  10072. /// Check an Objective-C array literal being converted to the given
  10073. /// target type.
  10074. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  10075. ObjCArrayLiteral *ArrayLiteral) {
  10076. if (!S.NSArrayDecl)
  10077. return;
  10078. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  10079. if (!TargetObjCPtr)
  10080. return;
  10081. if (TargetObjCPtr->isUnspecialized() ||
  10082. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  10083. != S.NSArrayDecl->getCanonicalDecl())
  10084. return;
  10085. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  10086. if (TypeArgs.size() != 1)
  10087. return;
  10088. QualType TargetElementType = TypeArgs[0];
  10089. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  10090. checkObjCCollectionLiteralElement(S, TargetElementType,
  10091. ArrayLiteral->getElement(I),
  10092. 0);
  10093. }
  10094. }
  10095. /// Check an Objective-C dictionary literal being converted to the given
  10096. /// target type.
  10097. static void
  10098. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  10099. ObjCDictionaryLiteral *DictionaryLiteral) {
  10100. if (!S.NSDictionaryDecl)
  10101. return;
  10102. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  10103. if (!TargetObjCPtr)
  10104. return;
  10105. if (TargetObjCPtr->isUnspecialized() ||
  10106. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  10107. != S.NSDictionaryDecl->getCanonicalDecl())
  10108. return;
  10109. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  10110. if (TypeArgs.size() != 2)
  10111. return;
  10112. QualType TargetKeyType = TypeArgs[0];
  10113. QualType TargetObjectType = TypeArgs[1];
  10114. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  10115. auto Element = DictionaryLiteral->getKeyValueElement(I);
  10116. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  10117. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  10118. }
  10119. }
  10120. // Helper function to filter out cases for constant width constant conversion.
  10121. // Don't warn on char array initialization or for non-decimal values.
  10122. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  10123. SourceLocation CC) {
  10124. // If initializing from a constant, and the constant starts with '0',
  10125. // then it is a binary, octal, or hexadecimal. Allow these constants
  10126. // to fill all the bits, even if there is a sign change.
  10127. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  10128. const char FirstLiteralCharacter =
  10129. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  10130. if (FirstLiteralCharacter == '0')
  10131. return false;
  10132. }
  10133. // If the CC location points to a '{', and the type is char, then assume
  10134. // assume it is an array initialization.
  10135. if (CC.isValid() && T->isCharType()) {
  10136. const char FirstContextCharacter =
  10137. S.getSourceManager().getCharacterData(CC)[0];
  10138. if (FirstContextCharacter == '{')
  10139. return false;
  10140. }
  10141. return true;
  10142. }
  10143. static const IntegerLiteral *getIntegerLiteral(Expr *E) {
  10144. const auto *IL = dyn_cast<IntegerLiteral>(E);
  10145. if (!IL) {
  10146. if (auto *UO = dyn_cast<UnaryOperator>(E)) {
  10147. if (UO->getOpcode() == UO_Minus)
  10148. return dyn_cast<IntegerLiteral>(UO->getSubExpr());
  10149. }
  10150. }
  10151. return IL;
  10152. }
  10153. static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
  10154. Expr *LHS, Expr *RHS) {
  10155. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  10156. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  10157. const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  10158. if (!LHSEnumType)
  10159. return;
  10160. const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  10161. if (!RHSEnumType)
  10162. return;
  10163. // Ignore anonymous enums.
  10164. if (!LHSEnumType->getDecl()->hasNameForLinkage())
  10165. return;
  10166. if (!RHSEnumType->getDecl()->hasNameForLinkage())
  10167. return;
  10168. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  10169. return;
  10170. S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
  10171. << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
  10172. << RHS->getSourceRange();
  10173. }
  10174. static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
  10175. E = E->IgnoreParenImpCasts();
  10176. SourceLocation ExprLoc = E->getExprLoc();
  10177. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  10178. BinaryOperator::Opcode Opc = BO->getOpcode();
  10179. Expr::EvalResult Result;
  10180. // Do not diagnose unsigned shifts.
  10181. if (Opc == BO_Shl) {
  10182. const auto *LHS = getIntegerLiteral(BO->getLHS());
  10183. const auto *RHS = getIntegerLiteral(BO->getRHS());
  10184. if (LHS && LHS->getValue() == 0)
  10185. S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
  10186. else if (!E->isValueDependent() && LHS && RHS &&
  10187. RHS->getValue().isNonNegative() &&
  10188. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
  10189. S.Diag(ExprLoc, diag::warn_left_shift_always)
  10190. << (Result.Val.getInt() != 0);
  10191. else if (E->getType()->isSignedIntegerType())
  10192. S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
  10193. }
  10194. }
  10195. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  10196. const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
  10197. const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
  10198. if (!LHS || !RHS)
  10199. return;
  10200. if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
  10201. (RHS->getValue() == 0 || RHS->getValue() == 1))
  10202. // Do not diagnose common idioms.
  10203. return;
  10204. if (LHS->getValue() != 0 && RHS->getValue() != 0)
  10205. S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
  10206. }
  10207. }
  10208. static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  10209. SourceLocation CC,
  10210. bool *ICContext = nullptr,
  10211. bool IsListInit = false) {
  10212. if (E->isTypeDependent() || E->isValueDependent()) return;
  10213. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  10214. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  10215. if (Source == Target) return;
  10216. if (Target->isDependentType()) return;
  10217. // If the conversion context location is invalid don't complain. We also
  10218. // don't want to emit a warning if the issue occurs from the expansion of
  10219. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  10220. // delay this check as long as possible. Once we detect we are in that
  10221. // scenario, we just return.
  10222. if (CC.isInvalid())
  10223. return;
  10224. if (Source->isAtomicType())
  10225. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  10226. // Diagnose implicit casts to bool.
  10227. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  10228. if (isa<StringLiteral>(E))
  10229. // Warn on string literal to bool. Checks for string literals in logical
  10230. // and expressions, for instance, assert(0 && "error here"), are
  10231. // prevented by a check in AnalyzeImplicitConversions().
  10232. return DiagnoseImpCast(S, E, T, CC,
  10233. diag::warn_impcast_string_literal_to_bool);
  10234. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  10235. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  10236. // This covers the literal expressions that evaluate to Objective-C
  10237. // objects.
  10238. return DiagnoseImpCast(S, E, T, CC,
  10239. diag::warn_impcast_objective_c_literal_to_bool);
  10240. }
  10241. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  10242. // Warn on pointer to bool conversion that is always true.
  10243. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  10244. SourceRange(CC));
  10245. }
  10246. }
  10247. // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
  10248. // is a typedef for signed char (macOS), then that constant value has to be 1
  10249. // or 0.
  10250. if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
  10251. Expr::EvalResult Result;
  10252. if (E->EvaluateAsInt(Result, S.getASTContext(),
  10253. Expr::SE_AllowSideEffects)) {
  10254. if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
  10255. adornObjCBoolConversionDiagWithTernaryFixit(
  10256. S, E,
  10257. S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
  10258. << Result.Val.getInt().toString(10));
  10259. }
  10260. return;
  10261. }
  10262. }
  10263. // Check implicit casts from Objective-C collection literals to specialized
  10264. // collection types, e.g., NSArray<NSString *> *.
  10265. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  10266. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  10267. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  10268. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  10269. // Strip vector types.
  10270. if (isa<VectorType>(Source)) {
  10271. if (!isa<VectorType>(Target)) {
  10272. if (S.SourceMgr.isInSystemMacro(CC))
  10273. return;
  10274. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  10275. }
  10276. // If the vector cast is cast between two vectors of the same size, it is
  10277. // a bitcast, not a conversion.
  10278. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  10279. return;
  10280. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  10281. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  10282. }
  10283. if (auto VecTy = dyn_cast<VectorType>(Target))
  10284. Target = VecTy->getElementType().getTypePtr();
  10285. // Strip complex types.
  10286. if (isa<ComplexType>(Source)) {
  10287. if (!isa<ComplexType>(Target)) {
  10288. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  10289. return;
  10290. return DiagnoseImpCast(S, E, T, CC,
  10291. S.getLangOpts().CPlusPlus
  10292. ? diag::err_impcast_complex_scalar
  10293. : diag::warn_impcast_complex_scalar);
  10294. }
  10295. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  10296. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  10297. }
  10298. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  10299. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  10300. // If the source is floating point...
  10301. if (SourceBT && SourceBT->isFloatingPoint()) {
  10302. // ...and the target is floating point...
  10303. if (TargetBT && TargetBT->isFloatingPoint()) {
  10304. // ...then warn if we're dropping FP rank.
  10305. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  10306. QualType(SourceBT, 0), QualType(TargetBT, 0));
  10307. if (Order > 0) {
  10308. // Don't warn about float constants that are precisely
  10309. // representable in the target type.
  10310. Expr::EvalResult result;
  10311. if (E->EvaluateAsRValue(result, S.Context)) {
  10312. // Value might be a float, a float vector, or a float complex.
  10313. if (IsSameFloatAfterCast(result.Val,
  10314. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  10315. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  10316. return;
  10317. }
  10318. if (S.SourceMgr.isInSystemMacro(CC))
  10319. return;
  10320. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  10321. }
  10322. // ... or possibly if we're increasing rank, too
  10323. else if (Order < 0) {
  10324. if (S.SourceMgr.isInSystemMacro(CC))
  10325. return;
  10326. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  10327. }
  10328. return;
  10329. }
  10330. // If the target is integral, always warn.
  10331. if (TargetBT && TargetBT->isInteger()) {
  10332. if (S.SourceMgr.isInSystemMacro(CC))
  10333. return;
  10334. DiagnoseFloatingImpCast(S, E, T, CC);
  10335. }
  10336. // Detect the case where a call result is converted from floating-point to
  10337. // to bool, and the final argument to the call is converted from bool, to
  10338. // discover this typo:
  10339. //
  10340. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  10341. //
  10342. // FIXME: This is an incredibly special case; is there some more general
  10343. // way to detect this class of misplaced-parentheses bug?
  10344. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  10345. // Check last argument of function call to see if it is an
  10346. // implicit cast from a type matching the type the result
  10347. // is being cast to.
  10348. CallExpr *CEx = cast<CallExpr>(E);
  10349. if (unsigned NumArgs = CEx->getNumArgs()) {
  10350. Expr *LastA = CEx->getArg(NumArgs - 1);
  10351. Expr *InnerE = LastA->IgnoreParenImpCasts();
  10352. if (isa<ImplicitCastExpr>(LastA) &&
  10353. InnerE->getType()->isBooleanType()) {
  10354. // Warn on this floating-point to bool conversion
  10355. DiagnoseImpCast(S, E, T, CC,
  10356. diag::warn_impcast_floating_point_to_bool);
  10357. }
  10358. }
  10359. }
  10360. return;
  10361. }
  10362. // Valid casts involving fixed point types should be accounted for here.
  10363. if (Source->isFixedPointType()) {
  10364. if (Target->isUnsaturatedFixedPointType()) {
  10365. Expr::EvalResult Result;
  10366. if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
  10367. S.isConstantEvaluated())) {
  10368. APFixedPoint Value = Result.Val.getFixedPoint();
  10369. APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  10370. APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  10371. if (Value > MaxVal || Value < MinVal) {
  10372. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10373. S.PDiag(diag::warn_impcast_fixed_point_range)
  10374. << Value.toString() << T
  10375. << E->getSourceRange()
  10376. << clang::SourceRange(CC));
  10377. return;
  10378. }
  10379. }
  10380. } else if (Target->isIntegerType()) {
  10381. Expr::EvalResult Result;
  10382. if (!S.isConstantEvaluated() &&
  10383. E->EvaluateAsFixedPoint(Result, S.Context,
  10384. Expr::SE_AllowSideEffects)) {
  10385. APFixedPoint FXResult = Result.Val.getFixedPoint();
  10386. bool Overflowed;
  10387. llvm::APSInt IntResult = FXResult.convertToInt(
  10388. S.Context.getIntWidth(T),
  10389. Target->isSignedIntegerOrEnumerationType(), &Overflowed);
  10390. if (Overflowed) {
  10391. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10392. S.PDiag(diag::warn_impcast_fixed_point_range)
  10393. << FXResult.toString() << T
  10394. << E->getSourceRange()
  10395. << clang::SourceRange(CC));
  10396. return;
  10397. }
  10398. }
  10399. }
  10400. } else if (Target->isUnsaturatedFixedPointType()) {
  10401. if (Source->isIntegerType()) {
  10402. Expr::EvalResult Result;
  10403. if (!S.isConstantEvaluated() &&
  10404. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  10405. llvm::APSInt Value = Result.Val.getInt();
  10406. bool Overflowed;
  10407. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10408. Value, S.Context.getFixedPointSemantics(T), &Overflowed);
  10409. if (Overflowed) {
  10410. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10411. S.PDiag(diag::warn_impcast_fixed_point_range)
  10412. << Value.toString(/*Radix=*/10) << T
  10413. << E->getSourceRange()
  10414. << clang::SourceRange(CC));
  10415. return;
  10416. }
  10417. }
  10418. }
  10419. }
  10420. // If we are casting an integer type to a floating point type without
  10421. // initialization-list syntax, we might lose accuracy if the floating
  10422. // point type has a narrower significand than the integer type.
  10423. if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
  10424. TargetBT->isFloatingType() && !IsListInit) {
  10425. // Determine the number of precision bits in the source integer type.
  10426. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
  10427. unsigned int SourcePrecision = SourceRange.Width;
  10428. // Determine the number of precision bits in the
  10429. // target floating point type.
  10430. unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
  10431. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  10432. if (SourcePrecision > 0 && TargetPrecision > 0 &&
  10433. SourcePrecision > TargetPrecision) {
  10434. llvm::APSInt SourceInt;
  10435. if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
  10436. // If the source integer is a constant, convert it to the target
  10437. // floating point type. Issue a warning if the value changes
  10438. // during the whole conversion.
  10439. llvm::APFloat TargetFloatValue(
  10440. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  10441. llvm::APFloat::opStatus ConversionStatus =
  10442. TargetFloatValue.convertFromAPInt(
  10443. SourceInt, SourceBT->isSignedInteger(),
  10444. llvm::APFloat::rmNearestTiesToEven);
  10445. if (ConversionStatus != llvm::APFloat::opOK) {
  10446. std::string PrettySourceValue = SourceInt.toString(10);
  10447. SmallString<32> PrettyTargetValue;
  10448. TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
  10449. S.DiagRuntimeBehavior(
  10450. E->getExprLoc(), E,
  10451. S.PDiag(diag::warn_impcast_integer_float_precision_constant)
  10452. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10453. << E->getSourceRange() << clang::SourceRange(CC));
  10454. }
  10455. } else {
  10456. // Otherwise, the implicit conversion may lose precision.
  10457. DiagnoseImpCast(S, E, T, CC,
  10458. diag::warn_impcast_integer_float_precision);
  10459. }
  10460. }
  10461. }
  10462. DiagnoseNullConversion(S, E, T, CC);
  10463. S.DiscardMisalignedMemberAddress(Target, E);
  10464. if (Target->isBooleanType())
  10465. DiagnoseIntInBoolContext(S, E);
  10466. if (!Source->isIntegerType() || !Target->isIntegerType())
  10467. return;
  10468. // TODO: remove this early return once the false positives for constant->bool
  10469. // in templates, macros, etc, are reduced or removed.
  10470. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  10471. return;
  10472. if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
  10473. !E->isKnownToHaveBooleanValue()) {
  10474. return adornObjCBoolConversionDiagWithTernaryFixit(
  10475. S, E,
  10476. S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
  10477. << E->getType());
  10478. }
  10479. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
  10480. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  10481. if (SourceRange.Width > TargetRange.Width) {
  10482. // If the source is a constant, use a default-on diagnostic.
  10483. // TODO: this should happen for bitfield stores, too.
  10484. Expr::EvalResult Result;
  10485. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
  10486. S.isConstantEvaluated())) {
  10487. llvm::APSInt Value(32);
  10488. Value = Result.Val.getInt();
  10489. if (S.SourceMgr.isInSystemMacro(CC))
  10490. return;
  10491. std::string PrettySourceValue = Value.toString(10);
  10492. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10493. S.DiagRuntimeBehavior(
  10494. E->getExprLoc(), E,
  10495. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10496. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10497. << E->getSourceRange() << clang::SourceRange(CC));
  10498. return;
  10499. }
  10500. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  10501. if (S.SourceMgr.isInSystemMacro(CC))
  10502. return;
  10503. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  10504. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  10505. /* pruneControlFlow */ true);
  10506. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  10507. }
  10508. if (TargetRange.Width > SourceRange.Width) {
  10509. if (auto *UO = dyn_cast<UnaryOperator>(E))
  10510. if (UO->getOpcode() == UO_Minus)
  10511. if (Source->isUnsignedIntegerType()) {
  10512. if (Target->isUnsignedIntegerType())
  10513. return DiagnoseImpCast(S, E, T, CC,
  10514. diag::warn_impcast_high_order_zero_bits);
  10515. if (Target->isSignedIntegerType())
  10516. return DiagnoseImpCast(S, E, T, CC,
  10517. diag::warn_impcast_nonnegative_result);
  10518. }
  10519. }
  10520. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  10521. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  10522. // Warn when doing a signed to signed conversion, warn if the positive
  10523. // source value is exactly the width of the target type, which will
  10524. // cause a negative value to be stored.
  10525. Expr::EvalResult Result;
  10526. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  10527. !S.SourceMgr.isInSystemMacro(CC)) {
  10528. llvm::APSInt Value = Result.Val.getInt();
  10529. if (isSameWidthConstantConversion(S, E, T, CC)) {
  10530. std::string PrettySourceValue = Value.toString(10);
  10531. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10532. S.DiagRuntimeBehavior(
  10533. E->getExprLoc(), E,
  10534. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10535. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10536. << E->getSourceRange() << clang::SourceRange(CC));
  10537. return;
  10538. }
  10539. }
  10540. // Fall through for non-constants to give a sign conversion warning.
  10541. }
  10542. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  10543. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  10544. SourceRange.Width == TargetRange.Width)) {
  10545. if (S.SourceMgr.isInSystemMacro(CC))
  10546. return;
  10547. unsigned DiagID = diag::warn_impcast_integer_sign;
  10548. // Traditionally, gcc has warned about this under -Wsign-compare.
  10549. // We also want to warn about it in -Wconversion.
  10550. // So if -Wconversion is off, use a completely identical diagnostic
  10551. // in the sign-compare group.
  10552. // The conditional-checking code will
  10553. if (ICContext) {
  10554. DiagID = diag::warn_impcast_integer_sign_conditional;
  10555. *ICContext = true;
  10556. }
  10557. return DiagnoseImpCast(S, E, T, CC, DiagID);
  10558. }
  10559. // Diagnose conversions between different enumeration types.
  10560. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  10561. // type, to give us better diagnostics.
  10562. QualType SourceType = E->getType();
  10563. if (!S.getLangOpts().CPlusPlus) {
  10564. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10565. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  10566. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  10567. SourceType = S.Context.getTypeDeclType(Enum);
  10568. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  10569. }
  10570. }
  10571. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  10572. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  10573. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  10574. TargetEnum->getDecl()->hasNameForLinkage() &&
  10575. SourceEnum != TargetEnum) {
  10576. if (S.SourceMgr.isInSystemMacro(CC))
  10577. return;
  10578. return DiagnoseImpCast(S, E, SourceType, T, CC,
  10579. diag::warn_impcast_different_enum_types);
  10580. }
  10581. }
  10582. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10583. SourceLocation CC, QualType T);
  10584. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  10585. SourceLocation CC, bool &ICContext) {
  10586. E = E->IgnoreParenImpCasts();
  10587. if (isa<ConditionalOperator>(E))
  10588. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  10589. AnalyzeImplicitConversions(S, E, CC);
  10590. if (E->getType() != T)
  10591. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  10592. }
  10593. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10594. SourceLocation CC, QualType T) {
  10595. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  10596. bool Suspicious = false;
  10597. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  10598. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  10599. CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
  10600. E->getFalseExpr());
  10601. if (T->isBooleanType())
  10602. DiagnoseIntInBoolContext(S, E);
  10603. // If -Wconversion would have warned about either of the candidates
  10604. // for a signedness conversion to the context type...
  10605. if (!Suspicious) return;
  10606. // ...but it's currently ignored...
  10607. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  10608. return;
  10609. // ...then check whether it would have warned about either of the
  10610. // candidates for a signedness conversion to the condition type.
  10611. if (E->getType() == T) return;
  10612. Suspicious = false;
  10613. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  10614. E->getType(), CC, &Suspicious);
  10615. if (!Suspicious)
  10616. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  10617. E->getType(), CC, &Suspicious);
  10618. }
  10619. /// Check conversion of given expression to boolean.
  10620. /// Input argument E is a logical expression.
  10621. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  10622. if (S.getLangOpts().Bool)
  10623. return;
  10624. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  10625. return;
  10626. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  10627. }
  10628. /// AnalyzeImplicitConversions - Find and report any interesting
  10629. /// implicit conversions in the given expression. There are a couple
  10630. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  10631. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
  10632. bool IsListInit/*= false*/) {
  10633. QualType T = OrigE->getType();
  10634. Expr *E = OrigE->IgnoreParenImpCasts();
  10635. // Propagate whether we are in a C++ list initialization expression.
  10636. // If so, we do not issue warnings for implicit int-float conversion
  10637. // precision loss, because C++11 narrowing already handles it.
  10638. IsListInit =
  10639. IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
  10640. if (E->isTypeDependent() || E->isValueDependent())
  10641. return;
  10642. if (const auto *UO = dyn_cast<UnaryOperator>(E))
  10643. if (UO->getOpcode() == UO_Not &&
  10644. UO->getSubExpr()->isKnownToHaveBooleanValue())
  10645. S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
  10646. << OrigE->getSourceRange() << T->isBooleanType()
  10647. << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
  10648. // For conditional operators, we analyze the arguments as if they
  10649. // were being fed directly into the output.
  10650. if (isa<ConditionalOperator>(E)) {
  10651. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  10652. CheckConditionalOperator(S, CO, CC, T);
  10653. return;
  10654. }
  10655. // Check implicit argument conversions for function calls.
  10656. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  10657. CheckImplicitArgumentConversions(S, Call, CC);
  10658. // Go ahead and check any implicit conversions we might have skipped.
  10659. // The non-canonical typecheck is just an optimization;
  10660. // CheckImplicitConversion will filter out dead implicit conversions.
  10661. if (E->getType() != T)
  10662. CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
  10663. // Now continue drilling into this expression.
  10664. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  10665. // The bound subexpressions in a PseudoObjectExpr are not reachable
  10666. // as transitive children.
  10667. // FIXME: Use a more uniform representation for this.
  10668. for (auto *SE : POE->semantics())
  10669. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  10670. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
  10671. }
  10672. // Skip past explicit casts.
  10673. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  10674. E = CE->getSubExpr()->IgnoreParenImpCasts();
  10675. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  10676. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  10677. return AnalyzeImplicitConversions(S, E, CC, IsListInit);
  10678. }
  10679. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10680. // Do a somewhat different check with comparison operators.
  10681. if (BO->isComparisonOp())
  10682. return AnalyzeComparison(S, BO);
  10683. // And with simple assignments.
  10684. if (BO->getOpcode() == BO_Assign)
  10685. return AnalyzeAssignment(S, BO);
  10686. // And with compound assignments.
  10687. if (BO->isAssignmentOp())
  10688. return AnalyzeCompoundAssignment(S, BO);
  10689. }
  10690. // These break the otherwise-useful invariant below. Fortunately,
  10691. // we don't really need to recurse into them, because any internal
  10692. // expressions should have been analyzed already when they were
  10693. // built into statements.
  10694. if (isa<StmtExpr>(E)) return;
  10695. // Don't descend into unevaluated contexts.
  10696. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  10697. // Now just recurse over the expression's children.
  10698. CC = E->getExprLoc();
  10699. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  10700. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  10701. for (Stmt *SubStmt : E->children()) {
  10702. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  10703. if (!ChildExpr)
  10704. continue;
  10705. if (IsLogicalAndOperator &&
  10706. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  10707. // Ignore checking string literals that are in logical and operators.
  10708. // This is a common pattern for asserts.
  10709. continue;
  10710. AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
  10711. }
  10712. if (BO && BO->isLogicalOp()) {
  10713. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  10714. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10715. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10716. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  10717. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10718. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10719. }
  10720. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  10721. if (U->getOpcode() == UO_LNot) {
  10722. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  10723. } else if (U->getOpcode() != UO_AddrOf) {
  10724. if (U->getSubExpr()->getType()->isAtomicType())
  10725. S.Diag(U->getSubExpr()->getBeginLoc(),
  10726. diag::warn_atomic_implicit_seq_cst);
  10727. }
  10728. }
  10729. }
  10730. /// Diagnose integer type and any valid implicit conversion to it.
  10731. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  10732. // Taking into account implicit conversions,
  10733. // allow any integer.
  10734. if (!E->getType()->isIntegerType()) {
  10735. S.Diag(E->getBeginLoc(),
  10736. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  10737. return true;
  10738. }
  10739. // Potentially emit standard warnings for implicit conversions if enabled
  10740. // using -Wconversion.
  10741. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  10742. return false;
  10743. }
  10744. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  10745. // Returns true when emitting a warning about taking the address of a reference.
  10746. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  10747. const PartialDiagnostic &PD) {
  10748. E = E->IgnoreParenImpCasts();
  10749. const FunctionDecl *FD = nullptr;
  10750. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10751. if (!DRE->getDecl()->getType()->isReferenceType())
  10752. return false;
  10753. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10754. if (!M->getMemberDecl()->getType()->isReferenceType())
  10755. return false;
  10756. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  10757. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  10758. return false;
  10759. FD = Call->getDirectCallee();
  10760. } else {
  10761. return false;
  10762. }
  10763. SemaRef.Diag(E->getExprLoc(), PD);
  10764. // If possible, point to location of function.
  10765. if (FD) {
  10766. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  10767. }
  10768. return true;
  10769. }
  10770. // Returns true if the SourceLocation is expanded from any macro body.
  10771. // Returns false if the SourceLocation is invalid, is from not in a macro
  10772. // expansion, or is from expanded from a top-level macro argument.
  10773. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  10774. if (Loc.isInvalid())
  10775. return false;
  10776. while (Loc.isMacroID()) {
  10777. if (SM.isMacroBodyExpansion(Loc))
  10778. return true;
  10779. Loc = SM.getImmediateMacroCallerLoc(Loc);
  10780. }
  10781. return false;
  10782. }
  10783. /// Diagnose pointers that are always non-null.
  10784. /// \param E the expression containing the pointer
  10785. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  10786. /// compared to a null pointer
  10787. /// \param IsEqual True when the comparison is equal to a null pointer
  10788. /// \param Range Extra SourceRange to highlight in the diagnostic
  10789. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  10790. Expr::NullPointerConstantKind NullKind,
  10791. bool IsEqual, SourceRange Range) {
  10792. if (!E)
  10793. return;
  10794. // Don't warn inside macros.
  10795. if (E->getExprLoc().isMacroID()) {
  10796. const SourceManager &SM = getSourceManager();
  10797. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  10798. IsInAnyMacroBody(SM, Range.getBegin()))
  10799. return;
  10800. }
  10801. E = E->IgnoreImpCasts();
  10802. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  10803. if (isa<CXXThisExpr>(E)) {
  10804. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  10805. : diag::warn_this_bool_conversion;
  10806. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  10807. return;
  10808. }
  10809. bool IsAddressOf = false;
  10810. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10811. if (UO->getOpcode() != UO_AddrOf)
  10812. return;
  10813. IsAddressOf = true;
  10814. E = UO->getSubExpr();
  10815. }
  10816. if (IsAddressOf) {
  10817. unsigned DiagID = IsCompare
  10818. ? diag::warn_address_of_reference_null_compare
  10819. : diag::warn_address_of_reference_bool_conversion;
  10820. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  10821. << IsEqual;
  10822. if (CheckForReference(*this, E, PD)) {
  10823. return;
  10824. }
  10825. }
  10826. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  10827. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  10828. std::string Str;
  10829. llvm::raw_string_ostream S(Str);
  10830. E->printPretty(S, nullptr, getPrintingPolicy());
  10831. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  10832. : diag::warn_cast_nonnull_to_bool;
  10833. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  10834. << E->getSourceRange() << Range << IsEqual;
  10835. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  10836. };
  10837. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  10838. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  10839. if (auto *Callee = Call->getDirectCallee()) {
  10840. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  10841. ComplainAboutNonnullParamOrCall(A);
  10842. return;
  10843. }
  10844. }
  10845. }
  10846. // Expect to find a single Decl. Skip anything more complicated.
  10847. ValueDecl *D = nullptr;
  10848. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  10849. D = R->getDecl();
  10850. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10851. D = M->getMemberDecl();
  10852. }
  10853. // Weak Decls can be null.
  10854. if (!D || D->isWeak())
  10855. return;
  10856. // Check for parameter decl with nonnull attribute
  10857. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  10858. if (getCurFunction() &&
  10859. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  10860. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  10861. ComplainAboutNonnullParamOrCall(A);
  10862. return;
  10863. }
  10864. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  10865. // Skip function template not specialized yet.
  10866. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  10867. return;
  10868. auto ParamIter = llvm::find(FD->parameters(), PV);
  10869. assert(ParamIter != FD->param_end());
  10870. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  10871. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  10872. if (!NonNull->args_size()) {
  10873. ComplainAboutNonnullParamOrCall(NonNull);
  10874. return;
  10875. }
  10876. for (const ParamIdx &ArgNo : NonNull->args()) {
  10877. if (ArgNo.getASTIndex() == ParamNo) {
  10878. ComplainAboutNonnullParamOrCall(NonNull);
  10879. return;
  10880. }
  10881. }
  10882. }
  10883. }
  10884. }
  10885. }
  10886. QualType T = D->getType();
  10887. const bool IsArray = T->isArrayType();
  10888. const bool IsFunction = T->isFunctionType();
  10889. // Address of function is used to silence the function warning.
  10890. if (IsAddressOf && IsFunction) {
  10891. return;
  10892. }
  10893. // Found nothing.
  10894. if (!IsAddressOf && !IsFunction && !IsArray)
  10895. return;
  10896. // Pretty print the expression for the diagnostic.
  10897. std::string Str;
  10898. llvm::raw_string_ostream S(Str);
  10899. E->printPretty(S, nullptr, getPrintingPolicy());
  10900. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10901. : diag::warn_impcast_pointer_to_bool;
  10902. enum {
  10903. AddressOf,
  10904. FunctionPointer,
  10905. ArrayPointer
  10906. } DiagType;
  10907. if (IsAddressOf)
  10908. DiagType = AddressOf;
  10909. else if (IsFunction)
  10910. DiagType = FunctionPointer;
  10911. else if (IsArray)
  10912. DiagType = ArrayPointer;
  10913. else
  10914. llvm_unreachable("Could not determine diagnostic.");
  10915. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10916. << Range << IsEqual;
  10917. if (!IsFunction)
  10918. return;
  10919. // Suggest '&' to silence the function warning.
  10920. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10921. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  10922. // Check to see if '()' fixit should be emitted.
  10923. QualType ReturnType;
  10924. UnresolvedSet<4> NonTemplateOverloads;
  10925. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10926. if (ReturnType.isNull())
  10927. return;
  10928. if (IsCompare) {
  10929. // There are two cases here. If there is null constant, the only suggest
  10930. // for a pointer return type. If the null is 0, then suggest if the return
  10931. // type is a pointer or an integer type.
  10932. if (!ReturnType->isPointerType()) {
  10933. if (NullKind == Expr::NPCK_ZeroExpression ||
  10934. NullKind == Expr::NPCK_ZeroLiteral) {
  10935. if (!ReturnType->isIntegerType())
  10936. return;
  10937. } else {
  10938. return;
  10939. }
  10940. }
  10941. } else { // !IsCompare
  10942. // For function to bool, only suggest if the function pointer has bool
  10943. // return type.
  10944. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10945. return;
  10946. }
  10947. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10948. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  10949. }
  10950. /// Diagnoses "dangerous" implicit conversions within the given
  10951. /// expression (which is a full expression). Implements -Wconversion
  10952. /// and -Wsign-compare.
  10953. ///
  10954. /// \param CC the "context" location of the implicit conversion, i.e.
  10955. /// the most location of the syntactic entity requiring the implicit
  10956. /// conversion
  10957. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10958. // Don't diagnose in unevaluated contexts.
  10959. if (isUnevaluatedContext())
  10960. return;
  10961. // Don't diagnose for value- or type-dependent expressions.
  10962. if (E->isTypeDependent() || E->isValueDependent())
  10963. return;
  10964. // Check for array bounds violations in cases where the check isn't triggered
  10965. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10966. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10967. CheckArrayAccess(E);
  10968. // This is not the right CC for (e.g.) a variable initialization.
  10969. AnalyzeImplicitConversions(*this, E, CC);
  10970. }
  10971. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10972. /// Input argument E is a logical expression.
  10973. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10974. ::CheckBoolLikeConversion(*this, E, CC);
  10975. }
  10976. /// Diagnose when expression is an integer constant expression and its evaluation
  10977. /// results in integer overflow
  10978. void Sema::CheckForIntOverflow (Expr *E) {
  10979. // Use a work list to deal with nested struct initializers.
  10980. SmallVector<Expr *, 2> Exprs(1, E);
  10981. do {
  10982. Expr *OriginalE = Exprs.pop_back_val();
  10983. Expr *E = OriginalE->IgnoreParenCasts();
  10984. if (isa<BinaryOperator>(E)) {
  10985. E->EvaluateForOverflow(Context);
  10986. continue;
  10987. }
  10988. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10989. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10990. else if (isa<ObjCBoxedExpr>(OriginalE))
  10991. E->EvaluateForOverflow(Context);
  10992. else if (auto Call = dyn_cast<CallExpr>(E))
  10993. Exprs.append(Call->arg_begin(), Call->arg_end());
  10994. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10995. Exprs.append(Message->arg_begin(), Message->arg_end());
  10996. } while (!Exprs.empty());
  10997. }
  10998. namespace {
  10999. /// Visitor for expressions which looks for unsequenced operations on the
  11000. /// same object.
  11001. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  11002. using Base = EvaluatedExprVisitor<SequenceChecker>;
  11003. /// A tree of sequenced regions within an expression. Two regions are
  11004. /// unsequenced if one is an ancestor or a descendent of the other. When we
  11005. /// finish processing an expression with sequencing, such as a comma
  11006. /// expression, we fold its tree nodes into its parent, since they are
  11007. /// unsequenced with respect to nodes we will visit later.
  11008. class SequenceTree {
  11009. struct Value {
  11010. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  11011. unsigned Parent : 31;
  11012. unsigned Merged : 1;
  11013. };
  11014. SmallVector<Value, 8> Values;
  11015. public:
  11016. /// A region within an expression which may be sequenced with respect
  11017. /// to some other region.
  11018. class Seq {
  11019. friend class SequenceTree;
  11020. unsigned Index;
  11021. explicit Seq(unsigned N) : Index(N) {}
  11022. public:
  11023. Seq() : Index(0) {}
  11024. };
  11025. SequenceTree() { Values.push_back(Value(0)); }
  11026. Seq root() const { return Seq(0); }
  11027. /// Create a new sequence of operations, which is an unsequenced
  11028. /// subset of \p Parent. This sequence of operations is sequenced with
  11029. /// respect to other children of \p Parent.
  11030. Seq allocate(Seq Parent) {
  11031. Values.push_back(Value(Parent.Index));
  11032. return Seq(Values.size() - 1);
  11033. }
  11034. /// Merge a sequence of operations into its parent.
  11035. void merge(Seq S) {
  11036. Values[S.Index].Merged = true;
  11037. }
  11038. /// Determine whether two operations are unsequenced. This operation
  11039. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  11040. /// should have been merged into its parent as appropriate.
  11041. bool isUnsequenced(Seq Cur, Seq Old) {
  11042. unsigned C = representative(Cur.Index);
  11043. unsigned Target = representative(Old.Index);
  11044. while (C >= Target) {
  11045. if (C == Target)
  11046. return true;
  11047. C = Values[C].Parent;
  11048. }
  11049. return false;
  11050. }
  11051. private:
  11052. /// Pick a representative for a sequence.
  11053. unsigned representative(unsigned K) {
  11054. if (Values[K].Merged)
  11055. // Perform path compression as we go.
  11056. return Values[K].Parent = representative(Values[K].Parent);
  11057. return K;
  11058. }
  11059. };
  11060. /// An object for which we can track unsequenced uses.
  11061. using Object = NamedDecl *;
  11062. /// Different flavors of object usage which we track. We only track the
  11063. /// least-sequenced usage of each kind.
  11064. enum UsageKind {
  11065. /// A read of an object. Multiple unsequenced reads are OK.
  11066. UK_Use,
  11067. /// A modification of an object which is sequenced before the value
  11068. /// computation of the expression, such as ++n in C++.
  11069. UK_ModAsValue,
  11070. /// A modification of an object which is not sequenced before the value
  11071. /// computation of the expression, such as n++.
  11072. UK_ModAsSideEffect,
  11073. UK_Count = UK_ModAsSideEffect + 1
  11074. };
  11075. struct Usage {
  11076. Expr *Use;
  11077. SequenceTree::Seq Seq;
  11078. Usage() : Use(nullptr), Seq() {}
  11079. };
  11080. struct UsageInfo {
  11081. Usage Uses[UK_Count];
  11082. /// Have we issued a diagnostic for this variable already?
  11083. bool Diagnosed;
  11084. UsageInfo() : Uses(), Diagnosed(false) {}
  11085. };
  11086. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  11087. Sema &SemaRef;
  11088. /// Sequenced regions within the expression.
  11089. SequenceTree Tree;
  11090. /// Declaration modifications and references which we have seen.
  11091. UsageInfoMap UsageMap;
  11092. /// The region we are currently within.
  11093. SequenceTree::Seq Region;
  11094. /// Filled in with declarations which were modified as a side-effect
  11095. /// (that is, post-increment operations).
  11096. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  11097. /// Expressions to check later. We defer checking these to reduce
  11098. /// stack usage.
  11099. SmallVectorImpl<Expr *> &WorkList;
  11100. /// RAII object wrapping the visitation of a sequenced subexpression of an
  11101. /// expression. At the end of this process, the side-effects of the evaluation
  11102. /// become sequenced with respect to the value computation of the result, so
  11103. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  11104. /// UK_ModAsValue.
  11105. struct SequencedSubexpression {
  11106. SequencedSubexpression(SequenceChecker &Self)
  11107. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  11108. Self.ModAsSideEffect = &ModAsSideEffect;
  11109. }
  11110. ~SequencedSubexpression() {
  11111. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  11112. UsageInfo &U = Self.UsageMap[M.first];
  11113. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  11114. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  11115. SideEffectUsage = M.second;
  11116. }
  11117. Self.ModAsSideEffect = OldModAsSideEffect;
  11118. }
  11119. SequenceChecker &Self;
  11120. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  11121. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  11122. };
  11123. /// RAII object wrapping the visitation of a subexpression which we might
  11124. /// choose to evaluate as a constant. If any subexpression is evaluated and
  11125. /// found to be non-constant, this allows us to suppress the evaluation of
  11126. /// the outer expression.
  11127. class EvaluationTracker {
  11128. public:
  11129. EvaluationTracker(SequenceChecker &Self)
  11130. : Self(Self), Prev(Self.EvalTracker) {
  11131. Self.EvalTracker = this;
  11132. }
  11133. ~EvaluationTracker() {
  11134. Self.EvalTracker = Prev;
  11135. if (Prev)
  11136. Prev->EvalOK &= EvalOK;
  11137. }
  11138. bool evaluate(const Expr *E, bool &Result) {
  11139. if (!EvalOK || E->isValueDependent())
  11140. return false;
  11141. EvalOK = E->EvaluateAsBooleanCondition(
  11142. Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
  11143. return EvalOK;
  11144. }
  11145. private:
  11146. SequenceChecker &Self;
  11147. EvaluationTracker *Prev;
  11148. bool EvalOK = true;
  11149. } *EvalTracker = nullptr;
  11150. /// Find the object which is produced by the specified expression,
  11151. /// if any.
  11152. Object getObject(Expr *E, bool Mod) const {
  11153. E = E->IgnoreParenCasts();
  11154. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  11155. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  11156. return getObject(UO->getSubExpr(), Mod);
  11157. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  11158. if (BO->getOpcode() == BO_Comma)
  11159. return getObject(BO->getRHS(), Mod);
  11160. if (Mod && BO->isAssignmentOp())
  11161. return getObject(BO->getLHS(), Mod);
  11162. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  11163. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  11164. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  11165. return ME->getMemberDecl();
  11166. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  11167. // FIXME: If this is a reference, map through to its value.
  11168. return DRE->getDecl();
  11169. return nullptr;
  11170. }
  11171. /// Note that an object was modified or used by an expression.
  11172. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  11173. Usage &U = UI.Uses[UK];
  11174. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  11175. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  11176. ModAsSideEffect->push_back(std::make_pair(O, U));
  11177. U.Use = Ref;
  11178. U.Seq = Region;
  11179. }
  11180. }
  11181. /// Check whether a modification or use conflicts with a prior usage.
  11182. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  11183. bool IsModMod) {
  11184. if (UI.Diagnosed)
  11185. return;
  11186. const Usage &U = UI.Uses[OtherKind];
  11187. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  11188. return;
  11189. Expr *Mod = U.Use;
  11190. Expr *ModOrUse = Ref;
  11191. if (OtherKind == UK_Use)
  11192. std::swap(Mod, ModOrUse);
  11193. SemaRef.DiagRuntimeBehavior(
  11194. Mod->getExprLoc(), {Mod, ModOrUse},
  11195. SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
  11196. : diag::warn_unsequenced_mod_use)
  11197. << O << SourceRange(ModOrUse->getExprLoc()));
  11198. UI.Diagnosed = true;
  11199. }
  11200. void notePreUse(Object O, Expr *Use) {
  11201. UsageInfo &U = UsageMap[O];
  11202. // Uses conflict with other modifications.
  11203. checkUsage(O, U, Use, UK_ModAsValue, false);
  11204. }
  11205. void notePostUse(Object O, Expr *Use) {
  11206. UsageInfo &U = UsageMap[O];
  11207. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  11208. addUsage(U, O, Use, UK_Use);
  11209. }
  11210. void notePreMod(Object O, Expr *Mod) {
  11211. UsageInfo &U = UsageMap[O];
  11212. // Modifications conflict with other modifications and with uses.
  11213. checkUsage(O, U, Mod, UK_ModAsValue, true);
  11214. checkUsage(O, U, Mod, UK_Use, false);
  11215. }
  11216. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  11217. UsageInfo &U = UsageMap[O];
  11218. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  11219. addUsage(U, O, Use, UK);
  11220. }
  11221. public:
  11222. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  11223. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  11224. Visit(E);
  11225. }
  11226. void VisitStmt(Stmt *S) {
  11227. // Skip all statements which aren't expressions for now.
  11228. }
  11229. void VisitExpr(Expr *E) {
  11230. // By default, just recurse to evaluated subexpressions.
  11231. Base::VisitStmt(E);
  11232. }
  11233. void VisitCastExpr(CastExpr *E) {
  11234. Object O = Object();
  11235. if (E->getCastKind() == CK_LValueToRValue)
  11236. O = getObject(E->getSubExpr(), false);
  11237. if (O)
  11238. notePreUse(O, E);
  11239. VisitExpr(E);
  11240. if (O)
  11241. notePostUse(O, E);
  11242. }
  11243. void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
  11244. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  11245. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  11246. SequenceTree::Seq OldRegion = Region;
  11247. {
  11248. SequencedSubexpression SeqBefore(*this);
  11249. Region = BeforeRegion;
  11250. Visit(SequencedBefore);
  11251. }
  11252. Region = AfterRegion;
  11253. Visit(SequencedAfter);
  11254. Region = OldRegion;
  11255. Tree.merge(BeforeRegion);
  11256. Tree.merge(AfterRegion);
  11257. }
  11258. void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
  11259. // C++17 [expr.sub]p1:
  11260. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  11261. // expression E1 is sequenced before the expression E2.
  11262. if (SemaRef.getLangOpts().CPlusPlus17)
  11263. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  11264. else
  11265. Base::VisitStmt(ASE);
  11266. }
  11267. void VisitBinComma(BinaryOperator *BO) {
  11268. // C++11 [expr.comma]p1:
  11269. // Every value computation and side effect associated with the left
  11270. // expression is sequenced before every value computation and side
  11271. // effect associated with the right expression.
  11272. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  11273. }
  11274. void VisitBinAssign(BinaryOperator *BO) {
  11275. // The modification is sequenced after the value computation of the LHS
  11276. // and RHS, so check it before inspecting the operands and update the
  11277. // map afterwards.
  11278. Object O = getObject(BO->getLHS(), true);
  11279. if (!O)
  11280. return VisitExpr(BO);
  11281. notePreMod(O, BO);
  11282. // C++11 [expr.ass]p7:
  11283. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  11284. // only once.
  11285. //
  11286. // Therefore, for a compound assignment operator, O is considered used
  11287. // everywhere except within the evaluation of E1 itself.
  11288. if (isa<CompoundAssignOperator>(BO))
  11289. notePreUse(O, BO);
  11290. Visit(BO->getLHS());
  11291. if (isa<CompoundAssignOperator>(BO))
  11292. notePostUse(O, BO);
  11293. Visit(BO->getRHS());
  11294. // C++11 [expr.ass]p1:
  11295. // the assignment is sequenced [...] before the value computation of the
  11296. // assignment expression.
  11297. // C11 6.5.16/3 has no such rule.
  11298. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  11299. : UK_ModAsSideEffect);
  11300. }
  11301. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  11302. VisitBinAssign(CAO);
  11303. }
  11304. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  11305. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  11306. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  11307. Object O = getObject(UO->getSubExpr(), true);
  11308. if (!O)
  11309. return VisitExpr(UO);
  11310. notePreMod(O, UO);
  11311. Visit(UO->getSubExpr());
  11312. // C++11 [expr.pre.incr]p1:
  11313. // the expression ++x is equivalent to x+=1
  11314. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  11315. : UK_ModAsSideEffect);
  11316. }
  11317. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  11318. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  11319. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  11320. Object O = getObject(UO->getSubExpr(), true);
  11321. if (!O)
  11322. return VisitExpr(UO);
  11323. notePreMod(O, UO);
  11324. Visit(UO->getSubExpr());
  11325. notePostMod(O, UO, UK_ModAsSideEffect);
  11326. }
  11327. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  11328. void VisitBinLOr(BinaryOperator *BO) {
  11329. // The side-effects of the LHS of an '&&' are sequenced before the
  11330. // value computation of the RHS, and hence before the value computation
  11331. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  11332. // as if they were unconditionally sequenced.
  11333. EvaluationTracker Eval(*this);
  11334. {
  11335. SequencedSubexpression Sequenced(*this);
  11336. Visit(BO->getLHS());
  11337. }
  11338. bool Result;
  11339. if (Eval.evaluate(BO->getLHS(), Result)) {
  11340. if (!Result)
  11341. Visit(BO->getRHS());
  11342. } else {
  11343. // Check for unsequenced operations in the RHS, treating it as an
  11344. // entirely separate evaluation.
  11345. //
  11346. // FIXME: If there are operations in the RHS which are unsequenced
  11347. // with respect to operations outside the RHS, and those operations
  11348. // are unconditionally evaluated, diagnose them.
  11349. WorkList.push_back(BO->getRHS());
  11350. }
  11351. }
  11352. void VisitBinLAnd(BinaryOperator *BO) {
  11353. EvaluationTracker Eval(*this);
  11354. {
  11355. SequencedSubexpression Sequenced(*this);
  11356. Visit(BO->getLHS());
  11357. }
  11358. bool Result;
  11359. if (Eval.evaluate(BO->getLHS(), Result)) {
  11360. if (Result)
  11361. Visit(BO->getRHS());
  11362. } else {
  11363. WorkList.push_back(BO->getRHS());
  11364. }
  11365. }
  11366. // Only visit the condition, unless we can be sure which subexpression will
  11367. // be chosen.
  11368. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  11369. EvaluationTracker Eval(*this);
  11370. {
  11371. SequencedSubexpression Sequenced(*this);
  11372. Visit(CO->getCond());
  11373. }
  11374. bool Result;
  11375. if (Eval.evaluate(CO->getCond(), Result))
  11376. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  11377. else {
  11378. WorkList.push_back(CO->getTrueExpr());
  11379. WorkList.push_back(CO->getFalseExpr());
  11380. }
  11381. }
  11382. void VisitCallExpr(CallExpr *CE) {
  11383. // C++11 [intro.execution]p15:
  11384. // When calling a function [...], every value computation and side effect
  11385. // associated with any argument expression, or with the postfix expression
  11386. // designating the called function, is sequenced before execution of every
  11387. // expression or statement in the body of the function [and thus before
  11388. // the value computation of its result].
  11389. SequencedSubexpression Sequenced(*this);
  11390. Base::VisitCallExpr(CE);
  11391. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  11392. }
  11393. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  11394. // This is a call, so all subexpressions are sequenced before the result.
  11395. SequencedSubexpression Sequenced(*this);
  11396. if (!CCE->isListInitialization())
  11397. return VisitExpr(CCE);
  11398. // In C++11, list initializations are sequenced.
  11399. SmallVector<SequenceTree::Seq, 32> Elts;
  11400. SequenceTree::Seq Parent = Region;
  11401. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  11402. E = CCE->arg_end();
  11403. I != E; ++I) {
  11404. Region = Tree.allocate(Parent);
  11405. Elts.push_back(Region);
  11406. Visit(*I);
  11407. }
  11408. // Forget that the initializers are sequenced.
  11409. Region = Parent;
  11410. for (unsigned I = 0; I < Elts.size(); ++I)
  11411. Tree.merge(Elts[I]);
  11412. }
  11413. void VisitInitListExpr(InitListExpr *ILE) {
  11414. if (!SemaRef.getLangOpts().CPlusPlus11)
  11415. return VisitExpr(ILE);
  11416. // In C++11, list initializations are sequenced.
  11417. SmallVector<SequenceTree::Seq, 32> Elts;
  11418. SequenceTree::Seq Parent = Region;
  11419. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  11420. Expr *E = ILE->getInit(I);
  11421. if (!E) continue;
  11422. Region = Tree.allocate(Parent);
  11423. Elts.push_back(Region);
  11424. Visit(E);
  11425. }
  11426. // Forget that the initializers are sequenced.
  11427. Region = Parent;
  11428. for (unsigned I = 0; I < Elts.size(); ++I)
  11429. Tree.merge(Elts[I]);
  11430. }
  11431. };
  11432. } // namespace
  11433. void Sema::CheckUnsequencedOperations(Expr *E) {
  11434. SmallVector<Expr *, 8> WorkList;
  11435. WorkList.push_back(E);
  11436. while (!WorkList.empty()) {
  11437. Expr *Item = WorkList.pop_back_val();
  11438. SequenceChecker(*this, Item, WorkList);
  11439. }
  11440. }
  11441. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  11442. bool IsConstexpr) {
  11443. llvm::SaveAndRestore<bool> ConstantContext(
  11444. isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
  11445. CheckImplicitConversions(E, CheckLoc);
  11446. if (!E->isInstantiationDependent())
  11447. CheckUnsequencedOperations(E);
  11448. if (!IsConstexpr && !E->isValueDependent())
  11449. CheckForIntOverflow(E);
  11450. DiagnoseMisalignedMembers();
  11451. }
  11452. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  11453. FieldDecl *BitField,
  11454. Expr *Init) {
  11455. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  11456. }
  11457. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  11458. SourceLocation Loc) {
  11459. if (!PType->isVariablyModifiedType())
  11460. return;
  11461. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  11462. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  11463. return;
  11464. }
  11465. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  11466. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  11467. return;
  11468. }
  11469. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  11470. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  11471. return;
  11472. }
  11473. const ArrayType *AT = S.Context.getAsArrayType(PType);
  11474. if (!AT)
  11475. return;
  11476. if (AT->getSizeModifier() != ArrayType::Star) {
  11477. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  11478. return;
  11479. }
  11480. S.Diag(Loc, diag::err_array_star_in_function_definition);
  11481. }
  11482. /// CheckParmsForFunctionDef - Check that the parameters of the given
  11483. /// function are appropriate for the definition of a function. This
  11484. /// takes care of any checks that cannot be performed on the
  11485. /// declaration itself, e.g., that the types of each of the function
  11486. /// parameters are complete.
  11487. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  11488. bool CheckParameterNames) {
  11489. bool HasInvalidParm = false;
  11490. for (ParmVarDecl *Param : Parameters) {
  11491. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  11492. // function declarator that is part of a function definition of
  11493. // that function shall not have incomplete type.
  11494. //
  11495. // This is also C++ [dcl.fct]p6.
  11496. if (!Param->isInvalidDecl() &&
  11497. RequireCompleteType(Param->getLocation(), Param->getType(),
  11498. diag::err_typecheck_decl_incomplete_type)) {
  11499. Param->setInvalidDecl();
  11500. HasInvalidParm = true;
  11501. }
  11502. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  11503. // declaration of each parameter shall include an identifier.
  11504. if (CheckParameterNames &&
  11505. Param->getIdentifier() == nullptr &&
  11506. !Param->isImplicit() &&
  11507. !getLangOpts().CPlusPlus)
  11508. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11509. // C99 6.7.5.3p12:
  11510. // If the function declarator is not part of a definition of that
  11511. // function, parameters may have incomplete type and may use the [*]
  11512. // notation in their sequences of declarator specifiers to specify
  11513. // variable length array types.
  11514. QualType PType = Param->getOriginalType();
  11515. // FIXME: This diagnostic should point the '[*]' if source-location
  11516. // information is added for it.
  11517. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  11518. // If the parameter is a c++ class type and it has to be destructed in the
  11519. // callee function, declare the destructor so that it can be called by the
  11520. // callee function. Do not perform any direct access check on the dtor here.
  11521. if (!Param->isInvalidDecl()) {
  11522. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  11523. if (!ClassDecl->isInvalidDecl() &&
  11524. !ClassDecl->hasIrrelevantDestructor() &&
  11525. !ClassDecl->isDependentContext() &&
  11526. ClassDecl->isParamDestroyedInCallee()) {
  11527. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11528. MarkFunctionReferenced(Param->getLocation(), Destructor);
  11529. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  11530. }
  11531. }
  11532. }
  11533. // Parameters with the pass_object_size attribute only need to be marked
  11534. // constant at function definitions. Because we lack information about
  11535. // whether we're on a declaration or definition when we're instantiating the
  11536. // attribute, we need to check for constness here.
  11537. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  11538. if (!Param->getType().isConstQualified())
  11539. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  11540. << Attr->getSpelling() << 1;
  11541. // Check for parameter names shadowing fields from the class.
  11542. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  11543. // The owning context for the parameter should be the function, but we
  11544. // want to see if this function's declaration context is a record.
  11545. DeclContext *DC = Param->getDeclContext();
  11546. if (DC && DC->isFunctionOrMethod()) {
  11547. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  11548. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  11549. RD, /*DeclIsField*/ false);
  11550. }
  11551. }
  11552. }
  11553. return HasInvalidParm;
  11554. }
  11555. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  11556. /// or MemberExpr.
  11557. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  11558. ASTContext &Context) {
  11559. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  11560. return Context.getDeclAlign(DRE->getDecl());
  11561. if (const auto *ME = dyn_cast<MemberExpr>(E))
  11562. return Context.getDeclAlign(ME->getMemberDecl());
  11563. return TypeAlign;
  11564. }
  11565. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  11566. /// pointer cast increases the alignment requirements.
  11567. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  11568. // This is actually a lot of work to potentially be doing on every
  11569. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  11570. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  11571. return;
  11572. // Ignore dependent types.
  11573. if (T->isDependentType() || Op->getType()->isDependentType())
  11574. return;
  11575. // Require that the destination be a pointer type.
  11576. const PointerType *DestPtr = T->getAs<PointerType>();
  11577. if (!DestPtr) return;
  11578. // If the destination has alignment 1, we're done.
  11579. QualType DestPointee = DestPtr->getPointeeType();
  11580. if (DestPointee->isIncompleteType()) return;
  11581. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  11582. if (DestAlign.isOne()) return;
  11583. // Require that the source be a pointer type.
  11584. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  11585. if (!SrcPtr) return;
  11586. QualType SrcPointee = SrcPtr->getPointeeType();
  11587. // Whitelist casts from cv void*. We already implicitly
  11588. // whitelisted casts to cv void*, since they have alignment 1.
  11589. // Also whitelist casts involving incomplete types, which implicitly
  11590. // includes 'void'.
  11591. if (SrcPointee->isIncompleteType()) return;
  11592. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  11593. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  11594. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  11595. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  11596. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  11597. if (UO->getOpcode() == UO_AddrOf)
  11598. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  11599. }
  11600. if (SrcAlign >= DestAlign) return;
  11601. Diag(TRange.getBegin(), diag::warn_cast_align)
  11602. << Op->getType() << T
  11603. << static_cast<unsigned>(SrcAlign.getQuantity())
  11604. << static_cast<unsigned>(DestAlign.getQuantity())
  11605. << TRange << Op->getSourceRange();
  11606. }
  11607. /// Check whether this array fits the idiom of a size-one tail padded
  11608. /// array member of a struct.
  11609. ///
  11610. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  11611. /// commonly used to emulate flexible arrays in C89 code.
  11612. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  11613. const NamedDecl *ND) {
  11614. if (Size != 1 || !ND) return false;
  11615. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  11616. if (!FD) return false;
  11617. // Don't consider sizes resulting from macro expansions or template argument
  11618. // substitution to form C89 tail-padded arrays.
  11619. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  11620. while (TInfo) {
  11621. TypeLoc TL = TInfo->getTypeLoc();
  11622. // Look through typedefs.
  11623. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  11624. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  11625. TInfo = TDL->getTypeSourceInfo();
  11626. continue;
  11627. }
  11628. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  11629. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  11630. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  11631. return false;
  11632. }
  11633. break;
  11634. }
  11635. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  11636. if (!RD) return false;
  11637. if (RD->isUnion()) return false;
  11638. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11639. if (!CRD->isStandardLayout()) return false;
  11640. }
  11641. // See if this is the last field decl in the record.
  11642. const Decl *D = FD;
  11643. while ((D = D->getNextDeclInContext()))
  11644. if (isa<FieldDecl>(D))
  11645. return false;
  11646. return true;
  11647. }
  11648. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  11649. const ArraySubscriptExpr *ASE,
  11650. bool AllowOnePastEnd, bool IndexNegated) {
  11651. // Already diagnosed by the constant evaluator.
  11652. if (isConstantEvaluated())
  11653. return;
  11654. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  11655. if (IndexExpr->isValueDependent())
  11656. return;
  11657. const Type *EffectiveType =
  11658. BaseExpr->getType()->getPointeeOrArrayElementType();
  11659. BaseExpr = BaseExpr->IgnoreParenCasts();
  11660. const ConstantArrayType *ArrayTy =
  11661. Context.getAsConstantArrayType(BaseExpr->getType());
  11662. if (!ArrayTy)
  11663. return;
  11664. const Type *BaseType = ArrayTy->getElementType().getTypePtr();
  11665. if (EffectiveType->isDependentType() || BaseType->isDependentType())
  11666. return;
  11667. Expr::EvalResult Result;
  11668. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  11669. return;
  11670. llvm::APSInt index = Result.Val.getInt();
  11671. if (IndexNegated)
  11672. index = -index;
  11673. const NamedDecl *ND = nullptr;
  11674. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11675. ND = DRE->getDecl();
  11676. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11677. ND = ME->getMemberDecl();
  11678. if (index.isUnsigned() || !index.isNegative()) {
  11679. // It is possible that the type of the base expression after
  11680. // IgnoreParenCasts is incomplete, even though the type of the base
  11681. // expression before IgnoreParenCasts is complete (see PR39746 for an
  11682. // example). In this case we have no information about whether the array
  11683. // access exceeds the array bounds. However we can still diagnose an array
  11684. // access which precedes the array bounds.
  11685. if (BaseType->isIncompleteType())
  11686. return;
  11687. llvm::APInt size = ArrayTy->getSize();
  11688. if (!size.isStrictlyPositive())
  11689. return;
  11690. if (BaseType != EffectiveType) {
  11691. // Make sure we're comparing apples to apples when comparing index to size
  11692. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  11693. uint64_t array_typesize = Context.getTypeSize(BaseType);
  11694. // Handle ptrarith_typesize being zero, such as when casting to void*
  11695. if (!ptrarith_typesize) ptrarith_typesize = 1;
  11696. if (ptrarith_typesize != array_typesize) {
  11697. // There's a cast to a different size type involved
  11698. uint64_t ratio = array_typesize / ptrarith_typesize;
  11699. // TODO: Be smarter about handling cases where array_typesize is not a
  11700. // multiple of ptrarith_typesize
  11701. if (ptrarith_typesize * ratio == array_typesize)
  11702. size *= llvm::APInt(size.getBitWidth(), ratio);
  11703. }
  11704. }
  11705. if (size.getBitWidth() > index.getBitWidth())
  11706. index = index.zext(size.getBitWidth());
  11707. else if (size.getBitWidth() < index.getBitWidth())
  11708. size = size.zext(index.getBitWidth());
  11709. // For array subscripting the index must be less than size, but for pointer
  11710. // arithmetic also allow the index (offset) to be equal to size since
  11711. // computing the next address after the end of the array is legal and
  11712. // commonly done e.g. in C++ iterators and range-based for loops.
  11713. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  11714. return;
  11715. // Also don't warn for arrays of size 1 which are members of some
  11716. // structure. These are often used to approximate flexible arrays in C89
  11717. // code.
  11718. if (IsTailPaddedMemberArray(*this, size, ND))
  11719. return;
  11720. // Suppress the warning if the subscript expression (as identified by the
  11721. // ']' location) and the index expression are both from macro expansions
  11722. // within a system header.
  11723. if (ASE) {
  11724. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  11725. ASE->getRBracketLoc());
  11726. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  11727. SourceLocation IndexLoc =
  11728. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  11729. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  11730. return;
  11731. }
  11732. }
  11733. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  11734. if (ASE)
  11735. DiagID = diag::warn_array_index_exceeds_bounds;
  11736. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11737. PDiag(DiagID) << index.toString(10, true)
  11738. << size.toString(10, true)
  11739. << (unsigned)size.getLimitedValue(~0U)
  11740. << IndexExpr->getSourceRange());
  11741. } else {
  11742. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  11743. if (!ASE) {
  11744. DiagID = diag::warn_ptr_arith_precedes_bounds;
  11745. if (index.isNegative()) index = -index;
  11746. }
  11747. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11748. PDiag(DiagID) << index.toString(10, true)
  11749. << IndexExpr->getSourceRange());
  11750. }
  11751. if (!ND) {
  11752. // Try harder to find a NamedDecl to point at in the note.
  11753. while (const ArraySubscriptExpr *ASE =
  11754. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  11755. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  11756. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11757. ND = DRE->getDecl();
  11758. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11759. ND = ME->getMemberDecl();
  11760. }
  11761. if (ND)
  11762. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  11763. PDiag(diag::note_array_declared_here)
  11764. << ND->getDeclName());
  11765. }
  11766. void Sema::CheckArrayAccess(const Expr *expr) {
  11767. int AllowOnePastEnd = 0;
  11768. while (expr) {
  11769. expr = expr->IgnoreParenImpCasts();
  11770. switch (expr->getStmtClass()) {
  11771. case Stmt::ArraySubscriptExprClass: {
  11772. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  11773. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  11774. AllowOnePastEnd > 0);
  11775. expr = ASE->getBase();
  11776. break;
  11777. }
  11778. case Stmt::MemberExprClass: {
  11779. expr = cast<MemberExpr>(expr)->getBase();
  11780. break;
  11781. }
  11782. case Stmt::OMPArraySectionExprClass: {
  11783. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  11784. if (ASE->getLowerBound())
  11785. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  11786. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  11787. return;
  11788. }
  11789. case Stmt::UnaryOperatorClass: {
  11790. // Only unwrap the * and & unary operators
  11791. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  11792. expr = UO->getSubExpr();
  11793. switch (UO->getOpcode()) {
  11794. case UO_AddrOf:
  11795. AllowOnePastEnd++;
  11796. break;
  11797. case UO_Deref:
  11798. AllowOnePastEnd--;
  11799. break;
  11800. default:
  11801. return;
  11802. }
  11803. break;
  11804. }
  11805. case Stmt::ConditionalOperatorClass: {
  11806. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  11807. if (const Expr *lhs = cond->getLHS())
  11808. CheckArrayAccess(lhs);
  11809. if (const Expr *rhs = cond->getRHS())
  11810. CheckArrayAccess(rhs);
  11811. return;
  11812. }
  11813. case Stmt::CXXOperatorCallExprClass: {
  11814. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  11815. for (const auto *Arg : OCE->arguments())
  11816. CheckArrayAccess(Arg);
  11817. return;
  11818. }
  11819. default:
  11820. return;
  11821. }
  11822. }
  11823. }
  11824. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  11825. namespace {
  11826. struct RetainCycleOwner {
  11827. VarDecl *Variable = nullptr;
  11828. SourceRange Range;
  11829. SourceLocation Loc;
  11830. bool Indirect = false;
  11831. RetainCycleOwner() = default;
  11832. void setLocsFrom(Expr *e) {
  11833. Loc = e->getExprLoc();
  11834. Range = e->getSourceRange();
  11835. }
  11836. };
  11837. } // namespace
  11838. /// Consider whether capturing the given variable can possibly lead to
  11839. /// a retain cycle.
  11840. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  11841. // In ARC, it's captured strongly iff the variable has __strong
  11842. // lifetime. In MRR, it's captured strongly if the variable is
  11843. // __block and has an appropriate type.
  11844. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11845. return false;
  11846. owner.Variable = var;
  11847. if (ref)
  11848. owner.setLocsFrom(ref);
  11849. return true;
  11850. }
  11851. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11852. while (true) {
  11853. e = e->IgnoreParens();
  11854. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  11855. switch (cast->getCastKind()) {
  11856. case CK_BitCast:
  11857. case CK_LValueBitCast:
  11858. case CK_LValueToRValue:
  11859. case CK_ARCReclaimReturnedObject:
  11860. e = cast->getSubExpr();
  11861. continue;
  11862. default:
  11863. return false;
  11864. }
  11865. }
  11866. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  11867. ObjCIvarDecl *ivar = ref->getDecl();
  11868. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11869. return false;
  11870. // Try to find a retain cycle in the base.
  11871. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  11872. return false;
  11873. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  11874. owner.Indirect = true;
  11875. return true;
  11876. }
  11877. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  11878. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  11879. if (!var) return false;
  11880. return considerVariable(var, ref, owner);
  11881. }
  11882. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  11883. if (member->isArrow()) return false;
  11884. // Don't count this as an indirect ownership.
  11885. e = member->getBase();
  11886. continue;
  11887. }
  11888. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  11889. // Only pay attention to pseudo-objects on property references.
  11890. ObjCPropertyRefExpr *pre
  11891. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  11892. ->IgnoreParens());
  11893. if (!pre) return false;
  11894. if (pre->isImplicitProperty()) return false;
  11895. ObjCPropertyDecl *property = pre->getExplicitProperty();
  11896. if (!property->isRetaining() &&
  11897. !(property->getPropertyIvarDecl() &&
  11898. property->getPropertyIvarDecl()->getType()
  11899. .getObjCLifetime() == Qualifiers::OCL_Strong))
  11900. return false;
  11901. owner.Indirect = true;
  11902. if (pre->isSuperReceiver()) {
  11903. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  11904. if (!owner.Variable)
  11905. return false;
  11906. owner.Loc = pre->getLocation();
  11907. owner.Range = pre->getSourceRange();
  11908. return true;
  11909. }
  11910. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  11911. ->getSourceExpr());
  11912. continue;
  11913. }
  11914. // Array ivars?
  11915. return false;
  11916. }
  11917. }
  11918. namespace {
  11919. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11920. ASTContext &Context;
  11921. VarDecl *Variable;
  11922. Expr *Capturer = nullptr;
  11923. bool VarWillBeReased = false;
  11924. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11925. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11926. Context(Context), Variable(variable) {}
  11927. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11928. if (ref->getDecl() == Variable && !Capturer)
  11929. Capturer = ref;
  11930. }
  11931. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11932. if (Capturer) return;
  11933. Visit(ref->getBase());
  11934. if (Capturer && ref->isFreeIvar())
  11935. Capturer = ref;
  11936. }
  11937. void VisitBlockExpr(BlockExpr *block) {
  11938. // Look inside nested blocks
  11939. if (block->getBlockDecl()->capturesVariable(Variable))
  11940. Visit(block->getBlockDecl()->getBody());
  11941. }
  11942. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11943. if (Capturer) return;
  11944. if (OVE->getSourceExpr())
  11945. Visit(OVE->getSourceExpr());
  11946. }
  11947. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11948. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11949. return;
  11950. Expr *LHS = BinOp->getLHS();
  11951. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11952. if (DRE->getDecl() != Variable)
  11953. return;
  11954. if (Expr *RHS = BinOp->getRHS()) {
  11955. RHS = RHS->IgnoreParenCasts();
  11956. llvm::APSInt Value;
  11957. VarWillBeReased =
  11958. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11959. }
  11960. }
  11961. }
  11962. };
  11963. } // namespace
  11964. /// Check whether the given argument is a block which captures a
  11965. /// variable.
  11966. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11967. assert(owner.Variable && owner.Loc.isValid());
  11968. e = e->IgnoreParenCasts();
  11969. // Look through [^{...} copy] and Block_copy(^{...}).
  11970. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11971. Selector Cmd = ME->getSelector();
  11972. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11973. e = ME->getInstanceReceiver();
  11974. if (!e)
  11975. return nullptr;
  11976. e = e->IgnoreParenCasts();
  11977. }
  11978. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11979. if (CE->getNumArgs() == 1) {
  11980. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11981. if (Fn) {
  11982. const IdentifierInfo *FnI = Fn->getIdentifier();
  11983. if (FnI && FnI->isStr("_Block_copy")) {
  11984. e = CE->getArg(0)->IgnoreParenCasts();
  11985. }
  11986. }
  11987. }
  11988. }
  11989. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11990. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11991. return nullptr;
  11992. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11993. visitor.Visit(block->getBlockDecl()->getBody());
  11994. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11995. }
  11996. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11997. RetainCycleOwner &owner) {
  11998. assert(capturer);
  11999. assert(owner.Variable && owner.Loc.isValid());
  12000. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  12001. << owner.Variable << capturer->getSourceRange();
  12002. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  12003. << owner.Indirect << owner.Range;
  12004. }
  12005. /// Check for a keyword selector that starts with the word 'add' or
  12006. /// 'set'.
  12007. static bool isSetterLikeSelector(Selector sel) {
  12008. if (sel.isUnarySelector()) return false;
  12009. StringRef str = sel.getNameForSlot(0);
  12010. while (!str.empty() && str.front() == '_') str = str.substr(1);
  12011. if (str.startswith("set"))
  12012. str = str.substr(3);
  12013. else if (str.startswith("add")) {
  12014. // Specially whitelist 'addOperationWithBlock:'.
  12015. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  12016. return false;
  12017. str = str.substr(3);
  12018. }
  12019. else
  12020. return false;
  12021. if (str.empty()) return true;
  12022. return !isLowercase(str.front());
  12023. }
  12024. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  12025. ObjCMessageExpr *Message) {
  12026. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  12027. Message->getReceiverInterface(),
  12028. NSAPI::ClassId_NSMutableArray);
  12029. if (!IsMutableArray) {
  12030. return None;
  12031. }
  12032. Selector Sel = Message->getSelector();
  12033. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  12034. S.NSAPIObj->getNSArrayMethodKind(Sel);
  12035. if (!MKOpt) {
  12036. return None;
  12037. }
  12038. NSAPI::NSArrayMethodKind MK = *MKOpt;
  12039. switch (MK) {
  12040. case NSAPI::NSMutableArr_addObject:
  12041. case NSAPI::NSMutableArr_insertObjectAtIndex:
  12042. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  12043. return 0;
  12044. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  12045. return 1;
  12046. default:
  12047. return None;
  12048. }
  12049. return None;
  12050. }
  12051. static
  12052. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  12053. ObjCMessageExpr *Message) {
  12054. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  12055. Message->getReceiverInterface(),
  12056. NSAPI::ClassId_NSMutableDictionary);
  12057. if (!IsMutableDictionary) {
  12058. return None;
  12059. }
  12060. Selector Sel = Message->getSelector();
  12061. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  12062. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  12063. if (!MKOpt) {
  12064. return None;
  12065. }
  12066. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  12067. switch (MK) {
  12068. case NSAPI::NSMutableDict_setObjectForKey:
  12069. case NSAPI::NSMutableDict_setValueForKey:
  12070. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  12071. return 0;
  12072. default:
  12073. return None;
  12074. }
  12075. return None;
  12076. }
  12077. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  12078. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  12079. Message->getReceiverInterface(),
  12080. NSAPI::ClassId_NSMutableSet);
  12081. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  12082. Message->getReceiverInterface(),
  12083. NSAPI::ClassId_NSMutableOrderedSet);
  12084. if (!IsMutableSet && !IsMutableOrderedSet) {
  12085. return None;
  12086. }
  12087. Selector Sel = Message->getSelector();
  12088. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  12089. if (!MKOpt) {
  12090. return None;
  12091. }
  12092. NSAPI::NSSetMethodKind MK = *MKOpt;
  12093. switch (MK) {
  12094. case NSAPI::NSMutableSet_addObject:
  12095. case NSAPI::NSOrderedSet_setObjectAtIndex:
  12096. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  12097. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  12098. return 0;
  12099. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  12100. return 1;
  12101. }
  12102. return None;
  12103. }
  12104. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  12105. if (!Message->isInstanceMessage()) {
  12106. return;
  12107. }
  12108. Optional<int> ArgOpt;
  12109. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  12110. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  12111. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  12112. return;
  12113. }
  12114. int ArgIndex = *ArgOpt;
  12115. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  12116. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  12117. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  12118. }
  12119. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  12120. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  12121. if (ArgRE->isObjCSelfExpr()) {
  12122. Diag(Message->getSourceRange().getBegin(),
  12123. diag::warn_objc_circular_container)
  12124. << ArgRE->getDecl() << StringRef("'super'");
  12125. }
  12126. }
  12127. } else {
  12128. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  12129. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  12130. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  12131. }
  12132. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  12133. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  12134. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  12135. ValueDecl *Decl = ReceiverRE->getDecl();
  12136. Diag(Message->getSourceRange().getBegin(),
  12137. diag::warn_objc_circular_container)
  12138. << Decl << Decl;
  12139. if (!ArgRE->isObjCSelfExpr()) {
  12140. Diag(Decl->getLocation(),
  12141. diag::note_objc_circular_container_declared_here)
  12142. << Decl;
  12143. }
  12144. }
  12145. }
  12146. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  12147. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  12148. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  12149. ObjCIvarDecl *Decl = IvarRE->getDecl();
  12150. Diag(Message->getSourceRange().getBegin(),
  12151. diag::warn_objc_circular_container)
  12152. << Decl << Decl;
  12153. Diag(Decl->getLocation(),
  12154. diag::note_objc_circular_container_declared_here)
  12155. << Decl;
  12156. }
  12157. }
  12158. }
  12159. }
  12160. }
  12161. /// Check a message send to see if it's likely to cause a retain cycle.
  12162. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  12163. // Only check instance methods whose selector looks like a setter.
  12164. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  12165. return;
  12166. // Try to find a variable that the receiver is strongly owned by.
  12167. RetainCycleOwner owner;
  12168. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  12169. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  12170. return;
  12171. } else {
  12172. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  12173. owner.Variable = getCurMethodDecl()->getSelfDecl();
  12174. owner.Loc = msg->getSuperLoc();
  12175. owner.Range = msg->getSuperLoc();
  12176. }
  12177. // Check whether the receiver is captured by any of the arguments.
  12178. const ObjCMethodDecl *MD = msg->getMethodDecl();
  12179. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  12180. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  12181. // noescape blocks should not be retained by the method.
  12182. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  12183. continue;
  12184. return diagnoseRetainCycle(*this, capturer, owner);
  12185. }
  12186. }
  12187. }
  12188. /// Check a property assign to see if it's likely to cause a retain cycle.
  12189. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  12190. RetainCycleOwner owner;
  12191. if (!findRetainCycleOwner(*this, receiver, owner))
  12192. return;
  12193. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  12194. diagnoseRetainCycle(*this, capturer, owner);
  12195. }
  12196. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  12197. RetainCycleOwner Owner;
  12198. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  12199. return;
  12200. // Because we don't have an expression for the variable, we have to set the
  12201. // location explicitly here.
  12202. Owner.Loc = Var->getLocation();
  12203. Owner.Range = Var->getSourceRange();
  12204. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  12205. diagnoseRetainCycle(*this, Capturer, Owner);
  12206. }
  12207. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  12208. Expr *RHS, bool isProperty) {
  12209. // Check if RHS is an Objective-C object literal, which also can get
  12210. // immediately zapped in a weak reference. Note that we explicitly
  12211. // allow ObjCStringLiterals, since those are designed to never really die.
  12212. RHS = RHS->IgnoreParenImpCasts();
  12213. // This enum needs to match with the 'select' in
  12214. // warn_objc_arc_literal_assign (off-by-1).
  12215. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  12216. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  12217. return false;
  12218. S.Diag(Loc, diag::warn_arc_literal_assign)
  12219. << (unsigned) Kind
  12220. << (isProperty ? 0 : 1)
  12221. << RHS->getSourceRange();
  12222. return true;
  12223. }
  12224. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  12225. Qualifiers::ObjCLifetime LT,
  12226. Expr *RHS, bool isProperty) {
  12227. // Strip off any implicit cast added to get to the one ARC-specific.
  12228. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  12229. if (cast->getCastKind() == CK_ARCConsumeObject) {
  12230. S.Diag(Loc, diag::warn_arc_retained_assign)
  12231. << (LT == Qualifiers::OCL_ExplicitNone)
  12232. << (isProperty ? 0 : 1)
  12233. << RHS->getSourceRange();
  12234. return true;
  12235. }
  12236. RHS = cast->getSubExpr();
  12237. }
  12238. if (LT == Qualifiers::OCL_Weak &&
  12239. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  12240. return true;
  12241. return false;
  12242. }
  12243. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  12244. QualType LHS, Expr *RHS) {
  12245. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  12246. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  12247. return false;
  12248. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  12249. return true;
  12250. return false;
  12251. }
  12252. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  12253. Expr *LHS, Expr *RHS) {
  12254. QualType LHSType;
  12255. // PropertyRef on LHS type need be directly obtained from
  12256. // its declaration as it has a PseudoType.
  12257. ObjCPropertyRefExpr *PRE
  12258. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  12259. if (PRE && !PRE->isImplicitProperty()) {
  12260. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  12261. if (PD)
  12262. LHSType = PD->getType();
  12263. }
  12264. if (LHSType.isNull())
  12265. LHSType = LHS->getType();
  12266. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  12267. if (LT == Qualifiers::OCL_Weak) {
  12268. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  12269. getCurFunction()->markSafeWeakUse(LHS);
  12270. }
  12271. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  12272. return;
  12273. // FIXME. Check for other life times.
  12274. if (LT != Qualifiers::OCL_None)
  12275. return;
  12276. if (PRE) {
  12277. if (PRE->isImplicitProperty())
  12278. return;
  12279. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  12280. if (!PD)
  12281. return;
  12282. unsigned Attributes = PD->getPropertyAttributes();
  12283. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  12284. // when 'assign' attribute was not explicitly specified
  12285. // by user, ignore it and rely on property type itself
  12286. // for lifetime info.
  12287. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  12288. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  12289. LHSType->isObjCRetainableType())
  12290. return;
  12291. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  12292. if (cast->getCastKind() == CK_ARCConsumeObject) {
  12293. Diag(Loc, diag::warn_arc_retained_property_assign)
  12294. << RHS->getSourceRange();
  12295. return;
  12296. }
  12297. RHS = cast->getSubExpr();
  12298. }
  12299. }
  12300. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  12301. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  12302. return;
  12303. }
  12304. }
  12305. }
  12306. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  12307. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  12308. SourceLocation StmtLoc,
  12309. const NullStmt *Body) {
  12310. // Do not warn if the body is a macro that expands to nothing, e.g:
  12311. //
  12312. // #define CALL(x)
  12313. // if (condition)
  12314. // CALL(0);
  12315. if (Body->hasLeadingEmptyMacro())
  12316. return false;
  12317. // Get line numbers of statement and body.
  12318. bool StmtLineInvalid;
  12319. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  12320. &StmtLineInvalid);
  12321. if (StmtLineInvalid)
  12322. return false;
  12323. bool BodyLineInvalid;
  12324. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  12325. &BodyLineInvalid);
  12326. if (BodyLineInvalid)
  12327. return false;
  12328. // Warn if null statement and body are on the same line.
  12329. if (StmtLine != BodyLine)
  12330. return false;
  12331. return true;
  12332. }
  12333. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  12334. const Stmt *Body,
  12335. unsigned DiagID) {
  12336. // Since this is a syntactic check, don't emit diagnostic for template
  12337. // instantiations, this just adds noise.
  12338. if (CurrentInstantiationScope)
  12339. return;
  12340. // The body should be a null statement.
  12341. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  12342. if (!NBody)
  12343. return;
  12344. // Do the usual checks.
  12345. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  12346. return;
  12347. Diag(NBody->getSemiLoc(), DiagID);
  12348. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12349. }
  12350. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  12351. const Stmt *PossibleBody) {
  12352. assert(!CurrentInstantiationScope); // Ensured by caller
  12353. SourceLocation StmtLoc;
  12354. const Stmt *Body;
  12355. unsigned DiagID;
  12356. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  12357. StmtLoc = FS->getRParenLoc();
  12358. Body = FS->getBody();
  12359. DiagID = diag::warn_empty_for_body;
  12360. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  12361. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  12362. Body = WS->getBody();
  12363. DiagID = diag::warn_empty_while_body;
  12364. } else
  12365. return; // Neither `for' nor `while'.
  12366. // The body should be a null statement.
  12367. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  12368. if (!NBody)
  12369. return;
  12370. // Skip expensive checks if diagnostic is disabled.
  12371. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  12372. return;
  12373. // Do the usual checks.
  12374. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  12375. return;
  12376. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  12377. // noise level low, emit diagnostics only if for/while is followed by a
  12378. // CompoundStmt, e.g.:
  12379. // for (int i = 0; i < n; i++);
  12380. // {
  12381. // a(i);
  12382. // }
  12383. // or if for/while is followed by a statement with more indentation
  12384. // than for/while itself:
  12385. // for (int i = 0; i < n; i++);
  12386. // a(i);
  12387. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  12388. if (!ProbableTypo) {
  12389. bool BodyColInvalid;
  12390. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  12391. PossibleBody->getBeginLoc(), &BodyColInvalid);
  12392. if (BodyColInvalid)
  12393. return;
  12394. bool StmtColInvalid;
  12395. unsigned StmtCol =
  12396. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  12397. if (StmtColInvalid)
  12398. return;
  12399. if (BodyCol > StmtCol)
  12400. ProbableTypo = true;
  12401. }
  12402. if (ProbableTypo) {
  12403. Diag(NBody->getSemiLoc(), DiagID);
  12404. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12405. }
  12406. }
  12407. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  12408. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  12409. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  12410. SourceLocation OpLoc) {
  12411. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  12412. return;
  12413. if (inTemplateInstantiation())
  12414. return;
  12415. // Strip parens and casts away.
  12416. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  12417. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  12418. // Check for a call expression
  12419. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  12420. if (!CE || CE->getNumArgs() != 1)
  12421. return;
  12422. // Check for a call to std::move
  12423. if (!CE->isCallToStdMove())
  12424. return;
  12425. // Get argument from std::move
  12426. RHSExpr = CE->getArg(0);
  12427. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  12428. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  12429. // Two DeclRefExpr's, check that the decls are the same.
  12430. if (LHSDeclRef && RHSDeclRef) {
  12431. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12432. return;
  12433. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12434. RHSDeclRef->getDecl()->getCanonicalDecl())
  12435. return;
  12436. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12437. << LHSExpr->getSourceRange()
  12438. << RHSExpr->getSourceRange();
  12439. return;
  12440. }
  12441. // Member variables require a different approach to check for self moves.
  12442. // MemberExpr's are the same if every nested MemberExpr refers to the same
  12443. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  12444. // the base Expr's are CXXThisExpr's.
  12445. const Expr *LHSBase = LHSExpr;
  12446. const Expr *RHSBase = RHSExpr;
  12447. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  12448. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  12449. if (!LHSME || !RHSME)
  12450. return;
  12451. while (LHSME && RHSME) {
  12452. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  12453. RHSME->getMemberDecl()->getCanonicalDecl())
  12454. return;
  12455. LHSBase = LHSME->getBase();
  12456. RHSBase = RHSME->getBase();
  12457. LHSME = dyn_cast<MemberExpr>(LHSBase);
  12458. RHSME = dyn_cast<MemberExpr>(RHSBase);
  12459. }
  12460. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  12461. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  12462. if (LHSDeclRef && RHSDeclRef) {
  12463. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12464. return;
  12465. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12466. RHSDeclRef->getDecl()->getCanonicalDecl())
  12467. return;
  12468. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12469. << LHSExpr->getSourceRange()
  12470. << RHSExpr->getSourceRange();
  12471. return;
  12472. }
  12473. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  12474. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12475. << LHSExpr->getSourceRange()
  12476. << RHSExpr->getSourceRange();
  12477. }
  12478. //===--- Layout compatibility ----------------------------------------------//
  12479. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  12480. /// Check if two enumeration types are layout-compatible.
  12481. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  12482. // C++11 [dcl.enum] p8:
  12483. // Two enumeration types are layout-compatible if they have the same
  12484. // underlying type.
  12485. return ED1->isComplete() && ED2->isComplete() &&
  12486. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  12487. }
  12488. /// Check if two fields are layout-compatible.
  12489. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  12490. FieldDecl *Field2) {
  12491. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  12492. return false;
  12493. if (Field1->isBitField() != Field2->isBitField())
  12494. return false;
  12495. if (Field1->isBitField()) {
  12496. // Make sure that the bit-fields are the same length.
  12497. unsigned Bits1 = Field1->getBitWidthValue(C);
  12498. unsigned Bits2 = Field2->getBitWidthValue(C);
  12499. if (Bits1 != Bits2)
  12500. return false;
  12501. }
  12502. return true;
  12503. }
  12504. /// Check if two standard-layout structs are layout-compatible.
  12505. /// (C++11 [class.mem] p17)
  12506. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  12507. RecordDecl *RD2) {
  12508. // If both records are C++ classes, check that base classes match.
  12509. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  12510. // If one of records is a CXXRecordDecl we are in C++ mode,
  12511. // thus the other one is a CXXRecordDecl, too.
  12512. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  12513. // Check number of base classes.
  12514. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  12515. return false;
  12516. // Check the base classes.
  12517. for (CXXRecordDecl::base_class_const_iterator
  12518. Base1 = D1CXX->bases_begin(),
  12519. BaseEnd1 = D1CXX->bases_end(),
  12520. Base2 = D2CXX->bases_begin();
  12521. Base1 != BaseEnd1;
  12522. ++Base1, ++Base2) {
  12523. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  12524. return false;
  12525. }
  12526. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  12527. // If only RD2 is a C++ class, it should have zero base classes.
  12528. if (D2CXX->getNumBases() > 0)
  12529. return false;
  12530. }
  12531. // Check the fields.
  12532. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  12533. Field2End = RD2->field_end(),
  12534. Field1 = RD1->field_begin(),
  12535. Field1End = RD1->field_end();
  12536. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  12537. if (!isLayoutCompatible(C, *Field1, *Field2))
  12538. return false;
  12539. }
  12540. if (Field1 != Field1End || Field2 != Field2End)
  12541. return false;
  12542. return true;
  12543. }
  12544. /// Check if two standard-layout unions are layout-compatible.
  12545. /// (C++11 [class.mem] p18)
  12546. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  12547. RecordDecl *RD2) {
  12548. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  12549. for (auto *Field2 : RD2->fields())
  12550. UnmatchedFields.insert(Field2);
  12551. for (auto *Field1 : RD1->fields()) {
  12552. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  12553. I = UnmatchedFields.begin(),
  12554. E = UnmatchedFields.end();
  12555. for ( ; I != E; ++I) {
  12556. if (isLayoutCompatible(C, Field1, *I)) {
  12557. bool Result = UnmatchedFields.erase(*I);
  12558. (void) Result;
  12559. assert(Result);
  12560. break;
  12561. }
  12562. }
  12563. if (I == E)
  12564. return false;
  12565. }
  12566. return UnmatchedFields.empty();
  12567. }
  12568. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  12569. RecordDecl *RD2) {
  12570. if (RD1->isUnion() != RD2->isUnion())
  12571. return false;
  12572. if (RD1->isUnion())
  12573. return isLayoutCompatibleUnion(C, RD1, RD2);
  12574. else
  12575. return isLayoutCompatibleStruct(C, RD1, RD2);
  12576. }
  12577. /// Check if two types are layout-compatible in C++11 sense.
  12578. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  12579. if (T1.isNull() || T2.isNull())
  12580. return false;
  12581. // C++11 [basic.types] p11:
  12582. // If two types T1 and T2 are the same type, then T1 and T2 are
  12583. // layout-compatible types.
  12584. if (C.hasSameType(T1, T2))
  12585. return true;
  12586. T1 = T1.getCanonicalType().getUnqualifiedType();
  12587. T2 = T2.getCanonicalType().getUnqualifiedType();
  12588. const Type::TypeClass TC1 = T1->getTypeClass();
  12589. const Type::TypeClass TC2 = T2->getTypeClass();
  12590. if (TC1 != TC2)
  12591. return false;
  12592. if (TC1 == Type::Enum) {
  12593. return isLayoutCompatible(C,
  12594. cast<EnumType>(T1)->getDecl(),
  12595. cast<EnumType>(T2)->getDecl());
  12596. } else if (TC1 == Type::Record) {
  12597. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  12598. return false;
  12599. return isLayoutCompatible(C,
  12600. cast<RecordType>(T1)->getDecl(),
  12601. cast<RecordType>(T2)->getDecl());
  12602. }
  12603. return false;
  12604. }
  12605. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  12606. /// Given a type tag expression find the type tag itself.
  12607. ///
  12608. /// \param TypeExpr Type tag expression, as it appears in user's code.
  12609. ///
  12610. /// \param VD Declaration of an identifier that appears in a type tag.
  12611. ///
  12612. /// \param MagicValue Type tag magic value.
  12613. ///
  12614. /// \param isConstantEvaluated wether the evalaution should be performed in
  12615. /// constant context.
  12616. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  12617. const ValueDecl **VD, uint64_t *MagicValue,
  12618. bool isConstantEvaluated) {
  12619. while(true) {
  12620. if (!TypeExpr)
  12621. return false;
  12622. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  12623. switch (TypeExpr->getStmtClass()) {
  12624. case Stmt::UnaryOperatorClass: {
  12625. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  12626. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  12627. TypeExpr = UO->getSubExpr();
  12628. continue;
  12629. }
  12630. return false;
  12631. }
  12632. case Stmt::DeclRefExprClass: {
  12633. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  12634. *VD = DRE->getDecl();
  12635. return true;
  12636. }
  12637. case Stmt::IntegerLiteralClass: {
  12638. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  12639. llvm::APInt MagicValueAPInt = IL->getValue();
  12640. if (MagicValueAPInt.getActiveBits() <= 64) {
  12641. *MagicValue = MagicValueAPInt.getZExtValue();
  12642. return true;
  12643. } else
  12644. return false;
  12645. }
  12646. case Stmt::BinaryConditionalOperatorClass:
  12647. case Stmt::ConditionalOperatorClass: {
  12648. const AbstractConditionalOperator *ACO =
  12649. cast<AbstractConditionalOperator>(TypeExpr);
  12650. bool Result;
  12651. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
  12652. isConstantEvaluated)) {
  12653. if (Result)
  12654. TypeExpr = ACO->getTrueExpr();
  12655. else
  12656. TypeExpr = ACO->getFalseExpr();
  12657. continue;
  12658. }
  12659. return false;
  12660. }
  12661. case Stmt::BinaryOperatorClass: {
  12662. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  12663. if (BO->getOpcode() == BO_Comma) {
  12664. TypeExpr = BO->getRHS();
  12665. continue;
  12666. }
  12667. return false;
  12668. }
  12669. default:
  12670. return false;
  12671. }
  12672. }
  12673. }
  12674. /// Retrieve the C type corresponding to type tag TypeExpr.
  12675. ///
  12676. /// \param TypeExpr Expression that specifies a type tag.
  12677. ///
  12678. /// \param MagicValues Registered magic values.
  12679. ///
  12680. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  12681. /// kind.
  12682. ///
  12683. /// \param TypeInfo Information about the corresponding C type.
  12684. ///
  12685. /// \param isConstantEvaluated wether the evalaution should be performed in
  12686. /// constant context.
  12687. ///
  12688. /// \returns true if the corresponding C type was found.
  12689. static bool GetMatchingCType(
  12690. const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
  12691. const ASTContext &Ctx,
  12692. const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
  12693. *MagicValues,
  12694. bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
  12695. bool isConstantEvaluated) {
  12696. FoundWrongKind = false;
  12697. // Variable declaration that has type_tag_for_datatype attribute.
  12698. const ValueDecl *VD = nullptr;
  12699. uint64_t MagicValue;
  12700. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
  12701. return false;
  12702. if (VD) {
  12703. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  12704. if (I->getArgumentKind() != ArgumentKind) {
  12705. FoundWrongKind = true;
  12706. return false;
  12707. }
  12708. TypeInfo.Type = I->getMatchingCType();
  12709. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  12710. TypeInfo.MustBeNull = I->getMustBeNull();
  12711. return true;
  12712. }
  12713. return false;
  12714. }
  12715. if (!MagicValues)
  12716. return false;
  12717. llvm::DenseMap<Sema::TypeTagMagicValue,
  12718. Sema::TypeTagData>::const_iterator I =
  12719. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  12720. if (I == MagicValues->end())
  12721. return false;
  12722. TypeInfo = I->second;
  12723. return true;
  12724. }
  12725. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  12726. uint64_t MagicValue, QualType Type,
  12727. bool LayoutCompatible,
  12728. bool MustBeNull) {
  12729. if (!TypeTagForDatatypeMagicValues)
  12730. TypeTagForDatatypeMagicValues.reset(
  12731. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  12732. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  12733. (*TypeTagForDatatypeMagicValues)[Magic] =
  12734. TypeTagData(Type, LayoutCompatible, MustBeNull);
  12735. }
  12736. static bool IsSameCharType(QualType T1, QualType T2) {
  12737. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  12738. if (!BT1)
  12739. return false;
  12740. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  12741. if (!BT2)
  12742. return false;
  12743. BuiltinType::Kind T1Kind = BT1->getKind();
  12744. BuiltinType::Kind T2Kind = BT2->getKind();
  12745. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  12746. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  12747. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  12748. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  12749. }
  12750. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  12751. const ArrayRef<const Expr *> ExprArgs,
  12752. SourceLocation CallSiteLoc) {
  12753. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  12754. bool IsPointerAttr = Attr->getIsPointer();
  12755. // Retrieve the argument representing the 'type_tag'.
  12756. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  12757. if (TypeTagIdxAST >= ExprArgs.size()) {
  12758. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12759. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  12760. return;
  12761. }
  12762. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  12763. bool FoundWrongKind;
  12764. TypeTagData TypeInfo;
  12765. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  12766. TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
  12767. TypeInfo, isConstantEvaluated())) {
  12768. if (FoundWrongKind)
  12769. Diag(TypeTagExpr->getExprLoc(),
  12770. diag::warn_type_tag_for_datatype_wrong_kind)
  12771. << TypeTagExpr->getSourceRange();
  12772. return;
  12773. }
  12774. // Retrieve the argument representing the 'arg_idx'.
  12775. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  12776. if (ArgumentIdxAST >= ExprArgs.size()) {
  12777. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12778. << 1 << Attr->getArgumentIdx().getSourceIndex();
  12779. return;
  12780. }
  12781. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  12782. if (IsPointerAttr) {
  12783. // Skip implicit cast of pointer to `void *' (as a function argument).
  12784. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  12785. if (ICE->getType()->isVoidPointerType() &&
  12786. ICE->getCastKind() == CK_BitCast)
  12787. ArgumentExpr = ICE->getSubExpr();
  12788. }
  12789. QualType ArgumentType = ArgumentExpr->getType();
  12790. // Passing a `void*' pointer shouldn't trigger a warning.
  12791. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  12792. return;
  12793. if (TypeInfo.MustBeNull) {
  12794. // Type tag with matching void type requires a null pointer.
  12795. if (!ArgumentExpr->isNullPointerConstant(Context,
  12796. Expr::NPC_ValueDependentIsNotNull)) {
  12797. Diag(ArgumentExpr->getExprLoc(),
  12798. diag::warn_type_safety_null_pointer_required)
  12799. << ArgumentKind->getName()
  12800. << ArgumentExpr->getSourceRange()
  12801. << TypeTagExpr->getSourceRange();
  12802. }
  12803. return;
  12804. }
  12805. QualType RequiredType = TypeInfo.Type;
  12806. if (IsPointerAttr)
  12807. RequiredType = Context.getPointerType(RequiredType);
  12808. bool mismatch = false;
  12809. if (!TypeInfo.LayoutCompatible) {
  12810. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  12811. // C++11 [basic.fundamental] p1:
  12812. // Plain char, signed char, and unsigned char are three distinct types.
  12813. //
  12814. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  12815. // char' depending on the current char signedness mode.
  12816. if (mismatch)
  12817. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  12818. RequiredType->getPointeeType())) ||
  12819. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  12820. mismatch = false;
  12821. } else
  12822. if (IsPointerAttr)
  12823. mismatch = !isLayoutCompatible(Context,
  12824. ArgumentType->getPointeeType(),
  12825. RequiredType->getPointeeType());
  12826. else
  12827. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  12828. if (mismatch)
  12829. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  12830. << ArgumentType << ArgumentKind
  12831. << TypeInfo.LayoutCompatible << RequiredType
  12832. << ArgumentExpr->getSourceRange()
  12833. << TypeTagExpr->getSourceRange();
  12834. }
  12835. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  12836. CharUnits Alignment) {
  12837. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  12838. }
  12839. void Sema::DiagnoseMisalignedMembers() {
  12840. for (MisalignedMember &m : MisalignedMembers) {
  12841. const NamedDecl *ND = m.RD;
  12842. if (ND->getName().empty()) {
  12843. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  12844. ND = TD;
  12845. }
  12846. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  12847. << m.MD << ND << m.E->getSourceRange();
  12848. }
  12849. MisalignedMembers.clear();
  12850. }
  12851. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  12852. E = E->IgnoreParens();
  12853. if (!T->isPointerType() && !T->isIntegerType())
  12854. return;
  12855. if (isa<UnaryOperator>(E) &&
  12856. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  12857. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  12858. if (isa<MemberExpr>(Op)) {
  12859. auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
  12860. if (MA != MisalignedMembers.end() &&
  12861. (T->isIntegerType() ||
  12862. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  12863. Context.getTypeAlignInChars(
  12864. T->getPointeeType()) <= MA->Alignment))))
  12865. MisalignedMembers.erase(MA);
  12866. }
  12867. }
  12868. }
  12869. void Sema::RefersToMemberWithReducedAlignment(
  12870. Expr *E,
  12871. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  12872. Action) {
  12873. const auto *ME = dyn_cast<MemberExpr>(E);
  12874. if (!ME)
  12875. return;
  12876. // No need to check expressions with an __unaligned-qualified type.
  12877. if (E->getType().getQualifiers().hasUnaligned())
  12878. return;
  12879. // For a chain of MemberExpr like "a.b.c.d" this list
  12880. // will keep FieldDecl's like [d, c, b].
  12881. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  12882. const MemberExpr *TopME = nullptr;
  12883. bool AnyIsPacked = false;
  12884. do {
  12885. QualType BaseType = ME->getBase()->getType();
  12886. if (ME->isArrow())
  12887. BaseType = BaseType->getPointeeType();
  12888. RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
  12889. if (RD->isInvalidDecl())
  12890. return;
  12891. ValueDecl *MD = ME->getMemberDecl();
  12892. auto *FD = dyn_cast<FieldDecl>(MD);
  12893. // We do not care about non-data members.
  12894. if (!FD || FD->isInvalidDecl())
  12895. return;
  12896. AnyIsPacked =
  12897. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  12898. ReverseMemberChain.push_back(FD);
  12899. TopME = ME;
  12900. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  12901. } while (ME);
  12902. assert(TopME && "We did not compute a topmost MemberExpr!");
  12903. // Not the scope of this diagnostic.
  12904. if (!AnyIsPacked)
  12905. return;
  12906. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  12907. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  12908. // TODO: The innermost base of the member expression may be too complicated.
  12909. // For now, just disregard these cases. This is left for future
  12910. // improvement.
  12911. if (!DRE && !isa<CXXThisExpr>(TopBase))
  12912. return;
  12913. // Alignment expected by the whole expression.
  12914. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  12915. // No need to do anything else with this case.
  12916. if (ExpectedAlignment.isOne())
  12917. return;
  12918. // Synthesize offset of the whole access.
  12919. CharUnits Offset;
  12920. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  12921. I++) {
  12922. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12923. }
  12924. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12925. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12926. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12927. // The base expression of the innermost MemberExpr may give
  12928. // stronger guarantees than the class containing the member.
  12929. if (DRE && !TopME->isArrow()) {
  12930. const ValueDecl *VD = DRE->getDecl();
  12931. if (!VD->getType()->isReferenceType())
  12932. CompleteObjectAlignment =
  12933. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12934. }
  12935. // Check if the synthesized offset fulfills the alignment.
  12936. if (Offset % ExpectedAlignment != 0 ||
  12937. // It may fulfill the offset it but the effective alignment may still be
  12938. // lower than the expected expression alignment.
  12939. CompleteObjectAlignment < ExpectedAlignment) {
  12940. // If this happens, we want to determine a sensible culprit of this.
  12941. // Intuitively, watching the chain of member expressions from right to
  12942. // left, we start with the required alignment (as required by the field
  12943. // type) but some packed attribute in that chain has reduced the alignment.
  12944. // It may happen that another packed structure increases it again. But if
  12945. // we are here such increase has not been enough. So pointing the first
  12946. // FieldDecl that either is packed or else its RecordDecl is,
  12947. // seems reasonable.
  12948. FieldDecl *FD = nullptr;
  12949. CharUnits Alignment;
  12950. for (FieldDecl *FDI : ReverseMemberChain) {
  12951. if (FDI->hasAttr<PackedAttr>() ||
  12952. FDI->getParent()->hasAttr<PackedAttr>()) {
  12953. FD = FDI;
  12954. Alignment = std::min(
  12955. Context.getTypeAlignInChars(FD->getType()),
  12956. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12957. break;
  12958. }
  12959. }
  12960. assert(FD && "We did not find a packed FieldDecl!");
  12961. Action(E, FD->getParent(), FD, Alignment);
  12962. }
  12963. }
  12964. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12965. using namespace std::placeholders;
  12966. RefersToMemberWithReducedAlignment(
  12967. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12968. _2, _3, _4));
  12969. }