SemaChecking.cpp 350 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675
  1. //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements extra semantic analysis beyond what is enforced
  11. // by the C type system.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Sema/SemaInternal.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/CharUnits.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/EvaluatedExprVisitor.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/ExprObjC.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/Analysis/Analyses/FormatString.h"
  26. #include "clang/Basic/CharInfo.h"
  27. #include "clang/Basic/TargetBuiltins.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  30. #include "clang/Sema/Initialization.h"
  31. #include "clang/Sema/Lookup.h"
  32. #include "clang/Sema/ScopeInfo.h"
  33. #include "clang/Sema/Sema.h"
  34. #include "llvm/ADT/STLExtras.h"
  35. #include "llvm/ADT/SmallBitVector.h"
  36. #include "llvm/ADT/SmallString.h"
  37. #include "llvm/Support/ConvertUTF.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include <limits>
  40. using namespace clang;
  41. using namespace sema;
  42. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  43. unsigned ByteNo) const {
  44. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  45. Context.getTargetInfo());
  46. }
  47. /// Checks that a call expression's argument count is the desired number.
  48. /// This is useful when doing custom type-checking. Returns true on error.
  49. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  50. unsigned argCount = call->getNumArgs();
  51. if (argCount == desiredArgCount) return false;
  52. if (argCount < desiredArgCount)
  53. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  54. << 0 /*function call*/ << desiredArgCount << argCount
  55. << call->getSourceRange();
  56. // Highlight all the excess arguments.
  57. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  58. call->getArg(argCount - 1)->getLocEnd());
  59. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  60. << 0 /*function call*/ << desiredArgCount << argCount
  61. << call->getArg(1)->getSourceRange();
  62. }
  63. /// Check that the first argument to __builtin_annotation is an integer
  64. /// and the second argument is a non-wide string literal.
  65. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  66. if (checkArgCount(S, TheCall, 2))
  67. return true;
  68. // First argument should be an integer.
  69. Expr *ValArg = TheCall->getArg(0);
  70. QualType Ty = ValArg->getType();
  71. if (!Ty->isIntegerType()) {
  72. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  73. << ValArg->getSourceRange();
  74. return true;
  75. }
  76. // Second argument should be a constant string.
  77. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  78. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  79. if (!Literal || !Literal->isAscii()) {
  80. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  81. << StrArg->getSourceRange();
  82. return true;
  83. }
  84. TheCall->setType(Ty);
  85. return false;
  86. }
  87. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  88. /// result type to the corresponding pointer type.
  89. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  90. if (checkArgCount(S, TheCall, 1))
  91. return true;
  92. ExprResult Arg(TheCall->getArg(0));
  93. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
  94. if (ResultType.isNull())
  95. return true;
  96. TheCall->setArg(0, Arg.get());
  97. TheCall->setType(ResultType);
  98. return false;
  99. }
  100. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  101. CallExpr *TheCall, unsigned SizeIdx,
  102. unsigned DstSizeIdx) {
  103. if (TheCall->getNumArgs() <= SizeIdx ||
  104. TheCall->getNumArgs() <= DstSizeIdx)
  105. return;
  106. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  107. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  108. llvm::APSInt Size, DstSize;
  109. // find out if both sizes are known at compile time
  110. if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
  111. !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
  112. return;
  113. if (Size.ule(DstSize))
  114. return;
  115. // confirmed overflow so generate the diagnostic.
  116. IdentifierInfo *FnName = FDecl->getIdentifier();
  117. SourceLocation SL = TheCall->getLocStart();
  118. SourceRange SR = TheCall->getSourceRange();
  119. S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
  120. }
  121. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  122. if (checkArgCount(S, BuiltinCall, 2))
  123. return true;
  124. SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
  125. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  126. Expr *Call = BuiltinCall->getArg(0);
  127. Expr *Chain = BuiltinCall->getArg(1);
  128. if (Call->getStmtClass() != Stmt::CallExprClass) {
  129. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  130. << Call->getSourceRange();
  131. return true;
  132. }
  133. auto CE = cast<CallExpr>(Call);
  134. if (CE->getCallee()->getType()->isBlockPointerType()) {
  135. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  136. << Call->getSourceRange();
  137. return true;
  138. }
  139. const Decl *TargetDecl = CE->getCalleeDecl();
  140. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  141. if (FD->getBuiltinID()) {
  142. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  143. << Call->getSourceRange();
  144. return true;
  145. }
  146. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  147. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  148. << Call->getSourceRange();
  149. return true;
  150. }
  151. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  152. if (ChainResult.isInvalid())
  153. return true;
  154. if (!ChainResult.get()->getType()->isPointerType()) {
  155. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  156. << Chain->getSourceRange();
  157. return true;
  158. }
  159. QualType ReturnTy = CE->getCallReturnType(S.Context);
  160. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  161. QualType BuiltinTy = S.Context.getFunctionType(
  162. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  163. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  164. Builtin =
  165. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  166. BuiltinCall->setType(CE->getType());
  167. BuiltinCall->setValueKind(CE->getValueKind());
  168. BuiltinCall->setObjectKind(CE->getObjectKind());
  169. BuiltinCall->setCallee(Builtin);
  170. BuiltinCall->setArg(1, ChainResult.get());
  171. return false;
  172. }
  173. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  174. Scope::ScopeFlags NeededScopeFlags,
  175. unsigned DiagID) {
  176. // Scopes aren't available during instantiation. Fortunately, builtin
  177. // functions cannot be template args so they cannot be formed through template
  178. // instantiation. Therefore checking once during the parse is sufficient.
  179. if (!SemaRef.ActiveTemplateInstantiations.empty())
  180. return false;
  181. Scope *S = SemaRef.getCurScope();
  182. while (S && !S->isSEHExceptScope())
  183. S = S->getParent();
  184. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  185. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  186. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  187. << DRE->getDecl()->getIdentifier();
  188. return true;
  189. }
  190. return false;
  191. }
  192. ExprResult
  193. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  194. CallExpr *TheCall) {
  195. ExprResult TheCallResult(TheCall);
  196. // Find out if any arguments are required to be integer constant expressions.
  197. unsigned ICEArguments = 0;
  198. ASTContext::GetBuiltinTypeError Error;
  199. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  200. if (Error != ASTContext::GE_None)
  201. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  202. // If any arguments are required to be ICE's, check and diagnose.
  203. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  204. // Skip arguments not required to be ICE's.
  205. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  206. llvm::APSInt Result;
  207. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  208. return true;
  209. ICEArguments &= ~(1 << ArgNo);
  210. }
  211. switch (BuiltinID) {
  212. case Builtin::BI__builtin___CFStringMakeConstantString:
  213. assert(TheCall->getNumArgs() == 1 &&
  214. "Wrong # arguments to builtin CFStringMakeConstantString");
  215. if (CheckObjCString(TheCall->getArg(0)))
  216. return ExprError();
  217. break;
  218. case Builtin::BI__builtin_stdarg_start:
  219. case Builtin::BI__builtin_va_start:
  220. if (SemaBuiltinVAStart(TheCall))
  221. return ExprError();
  222. break;
  223. case Builtin::BI__va_start: {
  224. switch (Context.getTargetInfo().getTriple().getArch()) {
  225. case llvm::Triple::arm:
  226. case llvm::Triple::thumb:
  227. if (SemaBuiltinVAStartARM(TheCall))
  228. return ExprError();
  229. break;
  230. default:
  231. if (SemaBuiltinVAStart(TheCall))
  232. return ExprError();
  233. break;
  234. }
  235. break;
  236. }
  237. case Builtin::BI__builtin_isgreater:
  238. case Builtin::BI__builtin_isgreaterequal:
  239. case Builtin::BI__builtin_isless:
  240. case Builtin::BI__builtin_islessequal:
  241. case Builtin::BI__builtin_islessgreater:
  242. case Builtin::BI__builtin_isunordered:
  243. if (SemaBuiltinUnorderedCompare(TheCall))
  244. return ExprError();
  245. break;
  246. case Builtin::BI__builtin_fpclassify:
  247. if (SemaBuiltinFPClassification(TheCall, 6))
  248. return ExprError();
  249. break;
  250. case Builtin::BI__builtin_isfinite:
  251. case Builtin::BI__builtin_isinf:
  252. case Builtin::BI__builtin_isinf_sign:
  253. case Builtin::BI__builtin_isnan:
  254. case Builtin::BI__builtin_isnormal:
  255. if (SemaBuiltinFPClassification(TheCall, 1))
  256. return ExprError();
  257. break;
  258. case Builtin::BI__builtin_shufflevector:
  259. return SemaBuiltinShuffleVector(TheCall);
  260. // TheCall will be freed by the smart pointer here, but that's fine, since
  261. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  262. case Builtin::BI__builtin_prefetch:
  263. if (SemaBuiltinPrefetch(TheCall))
  264. return ExprError();
  265. break;
  266. case Builtin::BI__assume:
  267. case Builtin::BI__builtin_assume:
  268. if (SemaBuiltinAssume(TheCall))
  269. return ExprError();
  270. break;
  271. case Builtin::BI__builtin_assume_aligned:
  272. if (SemaBuiltinAssumeAligned(TheCall))
  273. return ExprError();
  274. break;
  275. case Builtin::BI__builtin_object_size:
  276. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  277. return ExprError();
  278. break;
  279. case Builtin::BI__builtin_longjmp:
  280. if (SemaBuiltinLongjmp(TheCall))
  281. return ExprError();
  282. break;
  283. case Builtin::BI__builtin_setjmp:
  284. if (SemaBuiltinSetjmp(TheCall))
  285. return ExprError();
  286. break;
  287. case Builtin::BI_setjmp:
  288. case Builtin::BI_setjmpex:
  289. if (checkArgCount(*this, TheCall, 1))
  290. return true;
  291. break;
  292. case Builtin::BI__builtin_classify_type:
  293. if (checkArgCount(*this, TheCall, 1)) return true;
  294. TheCall->setType(Context.IntTy);
  295. break;
  296. case Builtin::BI__builtin_constant_p:
  297. if (checkArgCount(*this, TheCall, 1)) return true;
  298. TheCall->setType(Context.IntTy);
  299. break;
  300. case Builtin::BI__sync_fetch_and_add:
  301. case Builtin::BI__sync_fetch_and_add_1:
  302. case Builtin::BI__sync_fetch_and_add_2:
  303. case Builtin::BI__sync_fetch_and_add_4:
  304. case Builtin::BI__sync_fetch_and_add_8:
  305. case Builtin::BI__sync_fetch_and_add_16:
  306. case Builtin::BI__sync_fetch_and_sub:
  307. case Builtin::BI__sync_fetch_and_sub_1:
  308. case Builtin::BI__sync_fetch_and_sub_2:
  309. case Builtin::BI__sync_fetch_and_sub_4:
  310. case Builtin::BI__sync_fetch_and_sub_8:
  311. case Builtin::BI__sync_fetch_and_sub_16:
  312. case Builtin::BI__sync_fetch_and_or:
  313. case Builtin::BI__sync_fetch_and_or_1:
  314. case Builtin::BI__sync_fetch_and_or_2:
  315. case Builtin::BI__sync_fetch_and_or_4:
  316. case Builtin::BI__sync_fetch_and_or_8:
  317. case Builtin::BI__sync_fetch_and_or_16:
  318. case Builtin::BI__sync_fetch_and_and:
  319. case Builtin::BI__sync_fetch_and_and_1:
  320. case Builtin::BI__sync_fetch_and_and_2:
  321. case Builtin::BI__sync_fetch_and_and_4:
  322. case Builtin::BI__sync_fetch_and_and_8:
  323. case Builtin::BI__sync_fetch_and_and_16:
  324. case Builtin::BI__sync_fetch_and_xor:
  325. case Builtin::BI__sync_fetch_and_xor_1:
  326. case Builtin::BI__sync_fetch_and_xor_2:
  327. case Builtin::BI__sync_fetch_and_xor_4:
  328. case Builtin::BI__sync_fetch_and_xor_8:
  329. case Builtin::BI__sync_fetch_and_xor_16:
  330. case Builtin::BI__sync_fetch_and_nand:
  331. case Builtin::BI__sync_fetch_and_nand_1:
  332. case Builtin::BI__sync_fetch_and_nand_2:
  333. case Builtin::BI__sync_fetch_and_nand_4:
  334. case Builtin::BI__sync_fetch_and_nand_8:
  335. case Builtin::BI__sync_fetch_and_nand_16:
  336. case Builtin::BI__sync_add_and_fetch:
  337. case Builtin::BI__sync_add_and_fetch_1:
  338. case Builtin::BI__sync_add_and_fetch_2:
  339. case Builtin::BI__sync_add_and_fetch_4:
  340. case Builtin::BI__sync_add_and_fetch_8:
  341. case Builtin::BI__sync_add_and_fetch_16:
  342. case Builtin::BI__sync_sub_and_fetch:
  343. case Builtin::BI__sync_sub_and_fetch_1:
  344. case Builtin::BI__sync_sub_and_fetch_2:
  345. case Builtin::BI__sync_sub_and_fetch_4:
  346. case Builtin::BI__sync_sub_and_fetch_8:
  347. case Builtin::BI__sync_sub_and_fetch_16:
  348. case Builtin::BI__sync_and_and_fetch:
  349. case Builtin::BI__sync_and_and_fetch_1:
  350. case Builtin::BI__sync_and_and_fetch_2:
  351. case Builtin::BI__sync_and_and_fetch_4:
  352. case Builtin::BI__sync_and_and_fetch_8:
  353. case Builtin::BI__sync_and_and_fetch_16:
  354. case Builtin::BI__sync_or_and_fetch:
  355. case Builtin::BI__sync_or_and_fetch_1:
  356. case Builtin::BI__sync_or_and_fetch_2:
  357. case Builtin::BI__sync_or_and_fetch_4:
  358. case Builtin::BI__sync_or_and_fetch_8:
  359. case Builtin::BI__sync_or_and_fetch_16:
  360. case Builtin::BI__sync_xor_and_fetch:
  361. case Builtin::BI__sync_xor_and_fetch_1:
  362. case Builtin::BI__sync_xor_and_fetch_2:
  363. case Builtin::BI__sync_xor_and_fetch_4:
  364. case Builtin::BI__sync_xor_and_fetch_8:
  365. case Builtin::BI__sync_xor_and_fetch_16:
  366. case Builtin::BI__sync_nand_and_fetch:
  367. case Builtin::BI__sync_nand_and_fetch_1:
  368. case Builtin::BI__sync_nand_and_fetch_2:
  369. case Builtin::BI__sync_nand_and_fetch_4:
  370. case Builtin::BI__sync_nand_and_fetch_8:
  371. case Builtin::BI__sync_nand_and_fetch_16:
  372. case Builtin::BI__sync_val_compare_and_swap:
  373. case Builtin::BI__sync_val_compare_and_swap_1:
  374. case Builtin::BI__sync_val_compare_and_swap_2:
  375. case Builtin::BI__sync_val_compare_and_swap_4:
  376. case Builtin::BI__sync_val_compare_and_swap_8:
  377. case Builtin::BI__sync_val_compare_and_swap_16:
  378. case Builtin::BI__sync_bool_compare_and_swap:
  379. case Builtin::BI__sync_bool_compare_and_swap_1:
  380. case Builtin::BI__sync_bool_compare_and_swap_2:
  381. case Builtin::BI__sync_bool_compare_and_swap_4:
  382. case Builtin::BI__sync_bool_compare_and_swap_8:
  383. case Builtin::BI__sync_bool_compare_and_swap_16:
  384. case Builtin::BI__sync_lock_test_and_set:
  385. case Builtin::BI__sync_lock_test_and_set_1:
  386. case Builtin::BI__sync_lock_test_and_set_2:
  387. case Builtin::BI__sync_lock_test_and_set_4:
  388. case Builtin::BI__sync_lock_test_and_set_8:
  389. case Builtin::BI__sync_lock_test_and_set_16:
  390. case Builtin::BI__sync_lock_release:
  391. case Builtin::BI__sync_lock_release_1:
  392. case Builtin::BI__sync_lock_release_2:
  393. case Builtin::BI__sync_lock_release_4:
  394. case Builtin::BI__sync_lock_release_8:
  395. case Builtin::BI__sync_lock_release_16:
  396. case Builtin::BI__sync_swap:
  397. case Builtin::BI__sync_swap_1:
  398. case Builtin::BI__sync_swap_2:
  399. case Builtin::BI__sync_swap_4:
  400. case Builtin::BI__sync_swap_8:
  401. case Builtin::BI__sync_swap_16:
  402. return SemaBuiltinAtomicOverloaded(TheCallResult);
  403. #define BUILTIN(ID, TYPE, ATTRS)
  404. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  405. case Builtin::BI##ID: \
  406. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  407. #include "clang/Basic/Builtins.def"
  408. case Builtin::BI__builtin_annotation:
  409. if (SemaBuiltinAnnotation(*this, TheCall))
  410. return ExprError();
  411. break;
  412. case Builtin::BI__builtin_addressof:
  413. if (SemaBuiltinAddressof(*this, TheCall))
  414. return ExprError();
  415. break;
  416. case Builtin::BI__builtin_operator_new:
  417. case Builtin::BI__builtin_operator_delete:
  418. if (!getLangOpts().CPlusPlus) {
  419. Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
  420. << (BuiltinID == Builtin::BI__builtin_operator_new
  421. ? "__builtin_operator_new"
  422. : "__builtin_operator_delete")
  423. << "C++";
  424. return ExprError();
  425. }
  426. // CodeGen assumes it can find the global new and delete to call,
  427. // so ensure that they are declared.
  428. DeclareGlobalNewDelete();
  429. break;
  430. // check secure string manipulation functions where overflows
  431. // are detectable at compile time
  432. case Builtin::BI__builtin___memcpy_chk:
  433. case Builtin::BI__builtin___memmove_chk:
  434. case Builtin::BI__builtin___memset_chk:
  435. case Builtin::BI__builtin___strlcat_chk:
  436. case Builtin::BI__builtin___strlcpy_chk:
  437. case Builtin::BI__builtin___strncat_chk:
  438. case Builtin::BI__builtin___strncpy_chk:
  439. case Builtin::BI__builtin___stpncpy_chk:
  440. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
  441. break;
  442. case Builtin::BI__builtin___memccpy_chk:
  443. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
  444. break;
  445. case Builtin::BI__builtin___snprintf_chk:
  446. case Builtin::BI__builtin___vsnprintf_chk:
  447. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
  448. break;
  449. case Builtin::BI__builtin_call_with_static_chain:
  450. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  451. return ExprError();
  452. break;
  453. case Builtin::BI__exception_code:
  454. case Builtin::BI_exception_code: {
  455. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  456. diag::err_seh___except_block))
  457. return ExprError();
  458. break;
  459. }
  460. case Builtin::BI__exception_info:
  461. case Builtin::BI_exception_info: {
  462. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  463. diag::err_seh___except_filter))
  464. return ExprError();
  465. break;
  466. }
  467. case Builtin::BI__GetExceptionInfo:
  468. if (checkArgCount(*this, TheCall, 1))
  469. return ExprError();
  470. if (CheckCXXThrowOperand(
  471. TheCall->getLocStart(),
  472. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  473. TheCall))
  474. return ExprError();
  475. TheCall->setType(Context.VoidPtrTy);
  476. break;
  477. }
  478. // Since the target specific builtins for each arch overlap, only check those
  479. // of the arch we are compiling for.
  480. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  481. switch (Context.getTargetInfo().getTriple().getArch()) {
  482. case llvm::Triple::arm:
  483. case llvm::Triple::armeb:
  484. case llvm::Triple::thumb:
  485. case llvm::Triple::thumbeb:
  486. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  487. return ExprError();
  488. break;
  489. case llvm::Triple::aarch64:
  490. case llvm::Triple::aarch64_be:
  491. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  492. return ExprError();
  493. break;
  494. case llvm::Triple::mips:
  495. case llvm::Triple::mipsel:
  496. case llvm::Triple::mips64:
  497. case llvm::Triple::mips64el:
  498. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  499. return ExprError();
  500. break;
  501. case llvm::Triple::systemz:
  502. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  503. return ExprError();
  504. break;
  505. case llvm::Triple::x86:
  506. case llvm::Triple::x86_64:
  507. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  508. return ExprError();
  509. break;
  510. case llvm::Triple::ppc:
  511. case llvm::Triple::ppc64:
  512. case llvm::Triple::ppc64le:
  513. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  514. return ExprError();
  515. break;
  516. default:
  517. break;
  518. }
  519. }
  520. return TheCallResult;
  521. }
  522. // Get the valid immediate range for the specified NEON type code.
  523. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  524. NeonTypeFlags Type(t);
  525. int IsQuad = ForceQuad ? true : Type.isQuad();
  526. switch (Type.getEltType()) {
  527. case NeonTypeFlags::Int8:
  528. case NeonTypeFlags::Poly8:
  529. return shift ? 7 : (8 << IsQuad) - 1;
  530. case NeonTypeFlags::Int16:
  531. case NeonTypeFlags::Poly16:
  532. return shift ? 15 : (4 << IsQuad) - 1;
  533. case NeonTypeFlags::Int32:
  534. return shift ? 31 : (2 << IsQuad) - 1;
  535. case NeonTypeFlags::Int64:
  536. case NeonTypeFlags::Poly64:
  537. return shift ? 63 : (1 << IsQuad) - 1;
  538. case NeonTypeFlags::Poly128:
  539. return shift ? 127 : (1 << IsQuad) - 1;
  540. case NeonTypeFlags::Float16:
  541. assert(!shift && "cannot shift float types!");
  542. return (4 << IsQuad) - 1;
  543. case NeonTypeFlags::Float32:
  544. assert(!shift && "cannot shift float types!");
  545. return (2 << IsQuad) - 1;
  546. case NeonTypeFlags::Float64:
  547. assert(!shift && "cannot shift float types!");
  548. return (1 << IsQuad) - 1;
  549. }
  550. llvm_unreachable("Invalid NeonTypeFlag!");
  551. }
  552. /// getNeonEltType - Return the QualType corresponding to the elements of
  553. /// the vector type specified by the NeonTypeFlags. This is used to check
  554. /// the pointer arguments for Neon load/store intrinsics.
  555. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  556. bool IsPolyUnsigned, bool IsInt64Long) {
  557. switch (Flags.getEltType()) {
  558. case NeonTypeFlags::Int8:
  559. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  560. case NeonTypeFlags::Int16:
  561. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  562. case NeonTypeFlags::Int32:
  563. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  564. case NeonTypeFlags::Int64:
  565. if (IsInt64Long)
  566. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  567. else
  568. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  569. : Context.LongLongTy;
  570. case NeonTypeFlags::Poly8:
  571. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  572. case NeonTypeFlags::Poly16:
  573. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  574. case NeonTypeFlags::Poly64:
  575. if (IsInt64Long)
  576. return Context.UnsignedLongTy;
  577. else
  578. return Context.UnsignedLongLongTy;
  579. case NeonTypeFlags::Poly128:
  580. break;
  581. case NeonTypeFlags::Float16:
  582. return Context.HalfTy;
  583. case NeonTypeFlags::Float32:
  584. return Context.FloatTy;
  585. case NeonTypeFlags::Float64:
  586. return Context.DoubleTy;
  587. }
  588. llvm_unreachable("Invalid NeonTypeFlag!");
  589. }
  590. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  591. llvm::APSInt Result;
  592. uint64_t mask = 0;
  593. unsigned TV = 0;
  594. int PtrArgNum = -1;
  595. bool HasConstPtr = false;
  596. switch (BuiltinID) {
  597. #define GET_NEON_OVERLOAD_CHECK
  598. #include "clang/Basic/arm_neon.inc"
  599. #undef GET_NEON_OVERLOAD_CHECK
  600. }
  601. // For NEON intrinsics which are overloaded on vector element type, validate
  602. // the immediate which specifies which variant to emit.
  603. unsigned ImmArg = TheCall->getNumArgs()-1;
  604. if (mask) {
  605. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  606. return true;
  607. TV = Result.getLimitedValue(64);
  608. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  609. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  610. << TheCall->getArg(ImmArg)->getSourceRange();
  611. }
  612. if (PtrArgNum >= 0) {
  613. // Check that pointer arguments have the specified type.
  614. Expr *Arg = TheCall->getArg(PtrArgNum);
  615. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  616. Arg = ICE->getSubExpr();
  617. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  618. QualType RHSTy = RHS.get()->getType();
  619. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  620. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
  621. bool IsInt64Long =
  622. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  623. QualType EltTy =
  624. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  625. if (HasConstPtr)
  626. EltTy = EltTy.withConst();
  627. QualType LHSTy = Context.getPointerType(EltTy);
  628. AssignConvertType ConvTy;
  629. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  630. if (RHS.isInvalid())
  631. return true;
  632. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  633. RHS.get(), AA_Assigning))
  634. return true;
  635. }
  636. // For NEON intrinsics which take an immediate value as part of the
  637. // instruction, range check them here.
  638. unsigned i = 0, l = 0, u = 0;
  639. switch (BuiltinID) {
  640. default:
  641. return false;
  642. #define GET_NEON_IMMEDIATE_CHECK
  643. #include "clang/Basic/arm_neon.inc"
  644. #undef GET_NEON_IMMEDIATE_CHECK
  645. }
  646. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  647. }
  648. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  649. unsigned MaxWidth) {
  650. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  651. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  652. BuiltinID == ARM::BI__builtin_arm_strex ||
  653. BuiltinID == ARM::BI__builtin_arm_stlex ||
  654. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  655. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  656. BuiltinID == AArch64::BI__builtin_arm_strex ||
  657. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  658. "unexpected ARM builtin");
  659. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  660. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  661. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  662. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  663. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  664. // Ensure that we have the proper number of arguments.
  665. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  666. return true;
  667. // Inspect the pointer argument of the atomic builtin. This should always be
  668. // a pointer type, whose element is an integral scalar or pointer type.
  669. // Because it is a pointer type, we don't have to worry about any implicit
  670. // casts here.
  671. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  672. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  673. if (PointerArgRes.isInvalid())
  674. return true;
  675. PointerArg = PointerArgRes.get();
  676. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  677. if (!pointerType) {
  678. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  679. << PointerArg->getType() << PointerArg->getSourceRange();
  680. return true;
  681. }
  682. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  683. // task is to insert the appropriate casts into the AST. First work out just
  684. // what the appropriate type is.
  685. QualType ValType = pointerType->getPointeeType();
  686. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  687. if (IsLdrex)
  688. AddrType.addConst();
  689. // Issue a warning if the cast is dodgy.
  690. CastKind CastNeeded = CK_NoOp;
  691. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  692. CastNeeded = CK_BitCast;
  693. Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
  694. << PointerArg->getType()
  695. << Context.getPointerType(AddrType)
  696. << AA_Passing << PointerArg->getSourceRange();
  697. }
  698. // Finally, do the cast and replace the argument with the corrected version.
  699. AddrType = Context.getPointerType(AddrType);
  700. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  701. if (PointerArgRes.isInvalid())
  702. return true;
  703. PointerArg = PointerArgRes.get();
  704. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  705. // In general, we allow ints, floats and pointers to be loaded and stored.
  706. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  707. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  708. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  709. << PointerArg->getType() << PointerArg->getSourceRange();
  710. return true;
  711. }
  712. // But ARM doesn't have instructions to deal with 128-bit versions.
  713. if (Context.getTypeSize(ValType) > MaxWidth) {
  714. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  715. Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
  716. << PointerArg->getType() << PointerArg->getSourceRange();
  717. return true;
  718. }
  719. switch (ValType.getObjCLifetime()) {
  720. case Qualifiers::OCL_None:
  721. case Qualifiers::OCL_ExplicitNone:
  722. // okay
  723. break;
  724. case Qualifiers::OCL_Weak:
  725. case Qualifiers::OCL_Strong:
  726. case Qualifiers::OCL_Autoreleasing:
  727. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  728. << ValType << PointerArg->getSourceRange();
  729. return true;
  730. }
  731. if (IsLdrex) {
  732. TheCall->setType(ValType);
  733. return false;
  734. }
  735. // Initialize the argument to be stored.
  736. ExprResult ValArg = TheCall->getArg(0);
  737. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  738. Context, ValType, /*consume*/ false);
  739. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  740. if (ValArg.isInvalid())
  741. return true;
  742. TheCall->setArg(0, ValArg.get());
  743. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  744. // but the custom checker bypasses all default analysis.
  745. TheCall->setType(Context.IntTy);
  746. return false;
  747. }
  748. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  749. llvm::APSInt Result;
  750. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  751. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  752. BuiltinID == ARM::BI__builtin_arm_strex ||
  753. BuiltinID == ARM::BI__builtin_arm_stlex) {
  754. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  755. }
  756. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  757. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  758. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  759. }
  760. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  761. BuiltinID == ARM::BI__builtin_arm_wsr64)
  762. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  763. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  764. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  765. BuiltinID == ARM::BI__builtin_arm_wsr ||
  766. BuiltinID == ARM::BI__builtin_arm_wsrp)
  767. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  768. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  769. return true;
  770. // For intrinsics which take an immediate value as part of the instruction,
  771. // range check them here.
  772. unsigned i = 0, l = 0, u = 0;
  773. switch (BuiltinID) {
  774. default: return false;
  775. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  776. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  777. case ARM::BI__builtin_arm_vcvtr_f:
  778. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  779. case ARM::BI__builtin_arm_dmb:
  780. case ARM::BI__builtin_arm_dsb:
  781. case ARM::BI__builtin_arm_isb:
  782. case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
  783. }
  784. // FIXME: VFP Intrinsics should error if VFP not present.
  785. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  786. }
  787. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  788. CallExpr *TheCall) {
  789. llvm::APSInt Result;
  790. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  791. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  792. BuiltinID == AArch64::BI__builtin_arm_strex ||
  793. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  794. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  795. }
  796. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  797. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  798. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  799. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  800. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  801. }
  802. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  803. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  804. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
  805. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  806. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  807. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  808. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  809. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  810. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  811. return true;
  812. // For intrinsics which take an immediate value as part of the instruction,
  813. // range check them here.
  814. unsigned i = 0, l = 0, u = 0;
  815. switch (BuiltinID) {
  816. default: return false;
  817. case AArch64::BI__builtin_arm_dmb:
  818. case AArch64::BI__builtin_arm_dsb:
  819. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  820. }
  821. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  822. }
  823. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  824. unsigned i = 0, l = 0, u = 0;
  825. switch (BuiltinID) {
  826. default: return false;
  827. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  828. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  829. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  830. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  831. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  832. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  833. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  834. }
  835. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  836. }
  837. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  838. unsigned i = 0, l = 0, u = 0;
  839. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  840. BuiltinID == PPC::BI__builtin_divdeu ||
  841. BuiltinID == PPC::BI__builtin_bpermd;
  842. bool IsTarget64Bit = Context.getTargetInfo()
  843. .getTypeWidth(Context
  844. .getTargetInfo()
  845. .getIntPtrType()) == 64;
  846. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  847. BuiltinID == PPC::BI__builtin_divweu ||
  848. BuiltinID == PPC::BI__builtin_divde ||
  849. BuiltinID == PPC::BI__builtin_divdeu;
  850. if (Is64BitBltin && !IsTarget64Bit)
  851. return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
  852. << TheCall->getSourceRange();
  853. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  854. (BuiltinID == PPC::BI__builtin_bpermd &&
  855. !Context.getTargetInfo().hasFeature("bpermd")))
  856. return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
  857. << TheCall->getSourceRange();
  858. switch (BuiltinID) {
  859. default: return false;
  860. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  861. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  862. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  863. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  864. case PPC::BI__builtin_tbegin:
  865. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  866. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  867. case PPC::BI__builtin_tabortwc:
  868. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  869. case PPC::BI__builtin_tabortwci:
  870. case PPC::BI__builtin_tabortdci:
  871. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  872. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  873. }
  874. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  875. }
  876. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  877. CallExpr *TheCall) {
  878. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  879. Expr *Arg = TheCall->getArg(0);
  880. llvm::APSInt AbortCode(32);
  881. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  882. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  883. return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
  884. << Arg->getSourceRange();
  885. }
  886. // For intrinsics which take an immediate value as part of the instruction,
  887. // range check them here.
  888. unsigned i = 0, l = 0, u = 0;
  889. switch (BuiltinID) {
  890. default: return false;
  891. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  892. case SystemZ::BI__builtin_s390_verimb:
  893. case SystemZ::BI__builtin_s390_verimh:
  894. case SystemZ::BI__builtin_s390_verimf:
  895. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  896. case SystemZ::BI__builtin_s390_vfaeb:
  897. case SystemZ::BI__builtin_s390_vfaeh:
  898. case SystemZ::BI__builtin_s390_vfaef:
  899. case SystemZ::BI__builtin_s390_vfaebs:
  900. case SystemZ::BI__builtin_s390_vfaehs:
  901. case SystemZ::BI__builtin_s390_vfaefs:
  902. case SystemZ::BI__builtin_s390_vfaezb:
  903. case SystemZ::BI__builtin_s390_vfaezh:
  904. case SystemZ::BI__builtin_s390_vfaezf:
  905. case SystemZ::BI__builtin_s390_vfaezbs:
  906. case SystemZ::BI__builtin_s390_vfaezhs:
  907. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  908. case SystemZ::BI__builtin_s390_vfidb:
  909. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  910. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  911. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  912. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  913. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  914. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  915. case SystemZ::BI__builtin_s390_vstrcb:
  916. case SystemZ::BI__builtin_s390_vstrch:
  917. case SystemZ::BI__builtin_s390_vstrcf:
  918. case SystemZ::BI__builtin_s390_vstrczb:
  919. case SystemZ::BI__builtin_s390_vstrczh:
  920. case SystemZ::BI__builtin_s390_vstrczf:
  921. case SystemZ::BI__builtin_s390_vstrcbs:
  922. case SystemZ::BI__builtin_s390_vstrchs:
  923. case SystemZ::BI__builtin_s390_vstrcfs:
  924. case SystemZ::BI__builtin_s390_vstrczbs:
  925. case SystemZ::BI__builtin_s390_vstrczhs:
  926. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  927. }
  928. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  929. }
  930. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  931. unsigned i = 0, l = 0, u = 0;
  932. switch (BuiltinID) {
  933. default: return false;
  934. case X86::BI__builtin_cpu_supports:
  935. return SemaBuiltinCpuSupports(TheCall);
  936. case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
  937. case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
  938. case X86::BI__builtin_ia32_vpermil2pd:
  939. case X86::BI__builtin_ia32_vpermil2pd256:
  940. case X86::BI__builtin_ia32_vpermil2ps:
  941. case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
  942. case X86::BI__builtin_ia32_cmpb128_mask:
  943. case X86::BI__builtin_ia32_cmpw128_mask:
  944. case X86::BI__builtin_ia32_cmpd128_mask:
  945. case X86::BI__builtin_ia32_cmpq128_mask:
  946. case X86::BI__builtin_ia32_cmpb256_mask:
  947. case X86::BI__builtin_ia32_cmpw256_mask:
  948. case X86::BI__builtin_ia32_cmpd256_mask:
  949. case X86::BI__builtin_ia32_cmpq256_mask:
  950. case X86::BI__builtin_ia32_cmpb512_mask:
  951. case X86::BI__builtin_ia32_cmpw512_mask:
  952. case X86::BI__builtin_ia32_cmpd512_mask:
  953. case X86::BI__builtin_ia32_cmpq512_mask:
  954. case X86::BI__builtin_ia32_ucmpb128_mask:
  955. case X86::BI__builtin_ia32_ucmpw128_mask:
  956. case X86::BI__builtin_ia32_ucmpd128_mask:
  957. case X86::BI__builtin_ia32_ucmpq128_mask:
  958. case X86::BI__builtin_ia32_ucmpb256_mask:
  959. case X86::BI__builtin_ia32_ucmpw256_mask:
  960. case X86::BI__builtin_ia32_ucmpd256_mask:
  961. case X86::BI__builtin_ia32_ucmpq256_mask:
  962. case X86::BI__builtin_ia32_ucmpb512_mask:
  963. case X86::BI__builtin_ia32_ucmpw512_mask:
  964. case X86::BI__builtin_ia32_ucmpd512_mask:
  965. case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
  966. case X86::BI__builtin_ia32_roundps:
  967. case X86::BI__builtin_ia32_roundpd:
  968. case X86::BI__builtin_ia32_roundps256:
  969. case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
  970. case X86::BI__builtin_ia32_roundss:
  971. case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
  972. case X86::BI__builtin_ia32_cmpps:
  973. case X86::BI__builtin_ia32_cmpss:
  974. case X86::BI__builtin_ia32_cmppd:
  975. case X86::BI__builtin_ia32_cmpsd:
  976. case X86::BI__builtin_ia32_cmpps256:
  977. case X86::BI__builtin_ia32_cmppd256:
  978. case X86::BI__builtin_ia32_cmpps512_mask:
  979. case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
  980. case X86::BI__builtin_ia32_vpcomub:
  981. case X86::BI__builtin_ia32_vpcomuw:
  982. case X86::BI__builtin_ia32_vpcomud:
  983. case X86::BI__builtin_ia32_vpcomuq:
  984. case X86::BI__builtin_ia32_vpcomb:
  985. case X86::BI__builtin_ia32_vpcomw:
  986. case X86::BI__builtin_ia32_vpcomd:
  987. case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
  988. }
  989. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  990. }
  991. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  992. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  993. /// Returns true when the format fits the function and the FormatStringInfo has
  994. /// been populated.
  995. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  996. FormatStringInfo *FSI) {
  997. FSI->HasVAListArg = Format->getFirstArg() == 0;
  998. FSI->FormatIdx = Format->getFormatIdx() - 1;
  999. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  1000. // The way the format attribute works in GCC, the implicit this argument
  1001. // of member functions is counted. However, it doesn't appear in our own
  1002. // lists, so decrement format_idx in that case.
  1003. if (IsCXXMember) {
  1004. if(FSI->FormatIdx == 0)
  1005. return false;
  1006. --FSI->FormatIdx;
  1007. if (FSI->FirstDataArg != 0)
  1008. --FSI->FirstDataArg;
  1009. }
  1010. return true;
  1011. }
  1012. /// Checks if a the given expression evaluates to null.
  1013. ///
  1014. /// \brief Returns true if the value evaluates to null.
  1015. static bool CheckNonNullExpr(Sema &S,
  1016. const Expr *Expr) {
  1017. // If the expression has non-null type, it doesn't evaluate to null.
  1018. if (auto nullability
  1019. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  1020. if (*nullability == NullabilityKind::NonNull)
  1021. return false;
  1022. }
  1023. // As a special case, transparent unions initialized with zero are
  1024. // considered null for the purposes of the nonnull attribute.
  1025. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  1026. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1027. if (const CompoundLiteralExpr *CLE =
  1028. dyn_cast<CompoundLiteralExpr>(Expr))
  1029. if (const InitListExpr *ILE =
  1030. dyn_cast<InitListExpr>(CLE->getInitializer()))
  1031. Expr = ILE->getInit(0);
  1032. }
  1033. bool Result;
  1034. return (!Expr->isValueDependent() &&
  1035. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  1036. !Result);
  1037. }
  1038. static void CheckNonNullArgument(Sema &S,
  1039. const Expr *ArgExpr,
  1040. SourceLocation CallSiteLoc) {
  1041. if (CheckNonNullExpr(S, ArgExpr))
  1042. S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  1043. }
  1044. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  1045. FormatStringInfo FSI;
  1046. if ((GetFormatStringType(Format) == FST_NSString) &&
  1047. getFormatStringInfo(Format, false, &FSI)) {
  1048. Idx = FSI.FormatIdx;
  1049. return true;
  1050. }
  1051. return false;
  1052. }
  1053. /// \brief Diagnose use of %s directive in an NSString which is being passed
  1054. /// as formatting string to formatting method.
  1055. static void
  1056. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  1057. const NamedDecl *FDecl,
  1058. Expr **Args,
  1059. unsigned NumArgs) {
  1060. unsigned Idx = 0;
  1061. bool Format = false;
  1062. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  1063. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  1064. Idx = 2;
  1065. Format = true;
  1066. }
  1067. else
  1068. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  1069. if (S.GetFormatNSStringIdx(I, Idx)) {
  1070. Format = true;
  1071. break;
  1072. }
  1073. }
  1074. if (!Format || NumArgs <= Idx)
  1075. return;
  1076. const Expr *FormatExpr = Args[Idx];
  1077. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  1078. FormatExpr = CSCE->getSubExpr();
  1079. const StringLiteral *FormatString;
  1080. if (const ObjCStringLiteral *OSL =
  1081. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  1082. FormatString = OSL->getString();
  1083. else
  1084. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  1085. if (!FormatString)
  1086. return;
  1087. if (S.FormatStringHasSArg(FormatString)) {
  1088. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  1089. << "%s" << 1 << 1;
  1090. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  1091. << FDecl->getDeclName();
  1092. }
  1093. }
  1094. /// Determine whether the given type has a non-null nullability annotation.
  1095. static bool isNonNullType(ASTContext &ctx, QualType type) {
  1096. if (auto nullability = type->getNullability(ctx))
  1097. return *nullability == NullabilityKind::NonNull;
  1098. return false;
  1099. }
  1100. static void CheckNonNullArguments(Sema &S,
  1101. const NamedDecl *FDecl,
  1102. const FunctionProtoType *Proto,
  1103. ArrayRef<const Expr *> Args,
  1104. SourceLocation CallSiteLoc) {
  1105. assert((FDecl || Proto) && "Need a function declaration or prototype");
  1106. // Check the attributes attached to the method/function itself.
  1107. llvm::SmallBitVector NonNullArgs;
  1108. if (FDecl) {
  1109. // Handle the nonnull attribute on the function/method declaration itself.
  1110. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  1111. if (!NonNull->args_size()) {
  1112. // Easy case: all pointer arguments are nonnull.
  1113. for (const auto *Arg : Args)
  1114. if (S.isValidPointerAttrType(Arg->getType()))
  1115. CheckNonNullArgument(S, Arg, CallSiteLoc);
  1116. return;
  1117. }
  1118. for (unsigned Val : NonNull->args()) {
  1119. if (Val >= Args.size())
  1120. continue;
  1121. if (NonNullArgs.empty())
  1122. NonNullArgs.resize(Args.size());
  1123. NonNullArgs.set(Val);
  1124. }
  1125. }
  1126. }
  1127. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  1128. // Handle the nonnull attribute on the parameters of the
  1129. // function/method.
  1130. ArrayRef<ParmVarDecl*> parms;
  1131. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  1132. parms = FD->parameters();
  1133. else
  1134. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  1135. unsigned ParamIndex = 0;
  1136. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  1137. I != E; ++I, ++ParamIndex) {
  1138. const ParmVarDecl *PVD = *I;
  1139. if (PVD->hasAttr<NonNullAttr>() ||
  1140. isNonNullType(S.Context, PVD->getType())) {
  1141. if (NonNullArgs.empty())
  1142. NonNullArgs.resize(Args.size());
  1143. NonNullArgs.set(ParamIndex);
  1144. }
  1145. }
  1146. } else {
  1147. // If we have a non-function, non-method declaration but no
  1148. // function prototype, try to dig out the function prototype.
  1149. if (!Proto) {
  1150. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  1151. QualType type = VD->getType().getNonReferenceType();
  1152. if (auto pointerType = type->getAs<PointerType>())
  1153. type = pointerType->getPointeeType();
  1154. else if (auto blockType = type->getAs<BlockPointerType>())
  1155. type = blockType->getPointeeType();
  1156. // FIXME: data member pointers?
  1157. // Dig out the function prototype, if there is one.
  1158. Proto = type->getAs<FunctionProtoType>();
  1159. }
  1160. }
  1161. // Fill in non-null argument information from the nullability
  1162. // information on the parameter types (if we have them).
  1163. if (Proto) {
  1164. unsigned Index = 0;
  1165. for (auto paramType : Proto->getParamTypes()) {
  1166. if (isNonNullType(S.Context, paramType)) {
  1167. if (NonNullArgs.empty())
  1168. NonNullArgs.resize(Args.size());
  1169. NonNullArgs.set(Index);
  1170. }
  1171. ++Index;
  1172. }
  1173. }
  1174. }
  1175. // Check for non-null arguments.
  1176. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  1177. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  1178. if (NonNullArgs[ArgIndex])
  1179. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  1180. }
  1181. }
  1182. /// Handles the checks for format strings, non-POD arguments to vararg
  1183. /// functions, and NULL arguments passed to non-NULL parameters.
  1184. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  1185. ArrayRef<const Expr *> Args, bool IsMemberFunction,
  1186. SourceLocation Loc, SourceRange Range,
  1187. VariadicCallType CallType) {
  1188. // FIXME: We should check as much as we can in the template definition.
  1189. if (CurContext->isDependentContext())
  1190. return;
  1191. // Printf and scanf checking.
  1192. llvm::SmallBitVector CheckedVarArgs;
  1193. if (FDecl) {
  1194. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  1195. // Only create vector if there are format attributes.
  1196. CheckedVarArgs.resize(Args.size());
  1197. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  1198. CheckedVarArgs);
  1199. }
  1200. }
  1201. // Refuse POD arguments that weren't caught by the format string
  1202. // checks above.
  1203. if (CallType != VariadicDoesNotApply) {
  1204. unsigned NumParams = Proto ? Proto->getNumParams()
  1205. : FDecl && isa<FunctionDecl>(FDecl)
  1206. ? cast<FunctionDecl>(FDecl)->getNumParams()
  1207. : FDecl && isa<ObjCMethodDecl>(FDecl)
  1208. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  1209. : 0;
  1210. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  1211. // Args[ArgIdx] can be null in malformed code.
  1212. if (const Expr *Arg = Args[ArgIdx]) {
  1213. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  1214. checkVariadicArgument(Arg, CallType);
  1215. }
  1216. }
  1217. }
  1218. if (FDecl || Proto) {
  1219. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  1220. // Type safety checking.
  1221. if (FDecl) {
  1222. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  1223. CheckArgumentWithTypeTag(I, Args.data());
  1224. }
  1225. }
  1226. }
  1227. /// CheckConstructorCall - Check a constructor call for correctness and safety
  1228. /// properties not enforced by the C type system.
  1229. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  1230. ArrayRef<const Expr *> Args,
  1231. const FunctionProtoType *Proto,
  1232. SourceLocation Loc) {
  1233. VariadicCallType CallType =
  1234. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  1235. checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
  1236. CallType);
  1237. }
  1238. /// CheckFunctionCall - Check a direct function call for various correctness
  1239. /// and safety properties not strictly enforced by the C type system.
  1240. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  1241. const FunctionProtoType *Proto) {
  1242. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  1243. isa<CXXMethodDecl>(FDecl);
  1244. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  1245. IsMemberOperatorCall;
  1246. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  1247. TheCall->getCallee());
  1248. Expr** Args = TheCall->getArgs();
  1249. unsigned NumArgs = TheCall->getNumArgs();
  1250. if (IsMemberOperatorCall) {
  1251. // If this is a call to a member operator, hide the first argument
  1252. // from checkCall.
  1253. // FIXME: Our choice of AST representation here is less than ideal.
  1254. ++Args;
  1255. --NumArgs;
  1256. }
  1257. checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
  1258. IsMemberFunction, TheCall->getRParenLoc(),
  1259. TheCall->getCallee()->getSourceRange(), CallType);
  1260. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  1261. // None of the checks below are needed for functions that don't have
  1262. // simple names (e.g., C++ conversion functions).
  1263. if (!FnInfo)
  1264. return false;
  1265. CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
  1266. if (getLangOpts().ObjC1)
  1267. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  1268. unsigned CMId = FDecl->getMemoryFunctionKind();
  1269. if (CMId == 0)
  1270. return false;
  1271. // Handle memory setting and copying functions.
  1272. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  1273. CheckStrlcpycatArguments(TheCall, FnInfo);
  1274. else if (CMId == Builtin::BIstrncat)
  1275. CheckStrncatArguments(TheCall, FnInfo);
  1276. else
  1277. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  1278. return false;
  1279. }
  1280. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  1281. ArrayRef<const Expr *> Args) {
  1282. VariadicCallType CallType =
  1283. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  1284. checkCall(Method, nullptr, Args,
  1285. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  1286. CallType);
  1287. return false;
  1288. }
  1289. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  1290. const FunctionProtoType *Proto) {
  1291. QualType Ty;
  1292. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  1293. Ty = V->getType().getNonReferenceType();
  1294. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  1295. Ty = F->getType().getNonReferenceType();
  1296. else
  1297. return false;
  1298. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  1299. !Ty->isFunctionProtoType())
  1300. return false;
  1301. VariadicCallType CallType;
  1302. if (!Proto || !Proto->isVariadic()) {
  1303. CallType = VariadicDoesNotApply;
  1304. } else if (Ty->isBlockPointerType()) {
  1305. CallType = VariadicBlock;
  1306. } else { // Ty->isFunctionPointerType()
  1307. CallType = VariadicFunction;
  1308. }
  1309. checkCall(NDecl, Proto,
  1310. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  1311. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  1312. TheCall->getCallee()->getSourceRange(), CallType);
  1313. return false;
  1314. }
  1315. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  1316. /// such as function pointers returned from functions.
  1317. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  1318. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  1319. TheCall->getCallee());
  1320. checkCall(/*FDecl=*/nullptr, Proto,
  1321. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  1322. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  1323. TheCall->getCallee()->getSourceRange(), CallType);
  1324. return false;
  1325. }
  1326. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  1327. if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
  1328. Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
  1329. return false;
  1330. switch (Op) {
  1331. case AtomicExpr::AO__c11_atomic_init:
  1332. llvm_unreachable("There is no ordering argument for an init");
  1333. case AtomicExpr::AO__c11_atomic_load:
  1334. case AtomicExpr::AO__atomic_load_n:
  1335. case AtomicExpr::AO__atomic_load:
  1336. return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
  1337. Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
  1338. case AtomicExpr::AO__c11_atomic_store:
  1339. case AtomicExpr::AO__atomic_store:
  1340. case AtomicExpr::AO__atomic_store_n:
  1341. return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
  1342. Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
  1343. Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
  1344. default:
  1345. return true;
  1346. }
  1347. }
  1348. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  1349. AtomicExpr::AtomicOp Op) {
  1350. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  1351. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1352. // All these operations take one of the following forms:
  1353. enum {
  1354. // C __c11_atomic_init(A *, C)
  1355. Init,
  1356. // C __c11_atomic_load(A *, int)
  1357. Load,
  1358. // void __atomic_load(A *, CP, int)
  1359. Copy,
  1360. // C __c11_atomic_add(A *, M, int)
  1361. Arithmetic,
  1362. // C __atomic_exchange_n(A *, CP, int)
  1363. Xchg,
  1364. // void __atomic_exchange(A *, C *, CP, int)
  1365. GNUXchg,
  1366. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  1367. C11CmpXchg,
  1368. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  1369. GNUCmpXchg
  1370. } Form = Init;
  1371. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
  1372. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
  1373. // where:
  1374. // C is an appropriate type,
  1375. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  1376. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  1377. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  1378. // the int parameters are for orderings.
  1379. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  1380. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  1381. AtomicExpr::AO__atomic_load,
  1382. "need to update code for modified C11 atomics");
  1383. bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
  1384. Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
  1385. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  1386. Op == AtomicExpr::AO__atomic_store_n ||
  1387. Op == AtomicExpr::AO__atomic_exchange_n ||
  1388. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  1389. bool IsAddSub = false;
  1390. switch (Op) {
  1391. case AtomicExpr::AO__c11_atomic_init:
  1392. Form = Init;
  1393. break;
  1394. case AtomicExpr::AO__c11_atomic_load:
  1395. case AtomicExpr::AO__atomic_load_n:
  1396. Form = Load;
  1397. break;
  1398. case AtomicExpr::AO__c11_atomic_store:
  1399. case AtomicExpr::AO__atomic_load:
  1400. case AtomicExpr::AO__atomic_store:
  1401. case AtomicExpr::AO__atomic_store_n:
  1402. Form = Copy;
  1403. break;
  1404. case AtomicExpr::AO__c11_atomic_fetch_add:
  1405. case AtomicExpr::AO__c11_atomic_fetch_sub:
  1406. case AtomicExpr::AO__atomic_fetch_add:
  1407. case AtomicExpr::AO__atomic_fetch_sub:
  1408. case AtomicExpr::AO__atomic_add_fetch:
  1409. case AtomicExpr::AO__atomic_sub_fetch:
  1410. IsAddSub = true;
  1411. // Fall through.
  1412. case AtomicExpr::AO__c11_atomic_fetch_and:
  1413. case AtomicExpr::AO__c11_atomic_fetch_or:
  1414. case AtomicExpr::AO__c11_atomic_fetch_xor:
  1415. case AtomicExpr::AO__atomic_fetch_and:
  1416. case AtomicExpr::AO__atomic_fetch_or:
  1417. case AtomicExpr::AO__atomic_fetch_xor:
  1418. case AtomicExpr::AO__atomic_fetch_nand:
  1419. case AtomicExpr::AO__atomic_and_fetch:
  1420. case AtomicExpr::AO__atomic_or_fetch:
  1421. case AtomicExpr::AO__atomic_xor_fetch:
  1422. case AtomicExpr::AO__atomic_nand_fetch:
  1423. Form = Arithmetic;
  1424. break;
  1425. case AtomicExpr::AO__c11_atomic_exchange:
  1426. case AtomicExpr::AO__atomic_exchange_n:
  1427. Form = Xchg;
  1428. break;
  1429. case AtomicExpr::AO__atomic_exchange:
  1430. Form = GNUXchg;
  1431. break;
  1432. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  1433. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  1434. Form = C11CmpXchg;
  1435. break;
  1436. case AtomicExpr::AO__atomic_compare_exchange:
  1437. case AtomicExpr::AO__atomic_compare_exchange_n:
  1438. Form = GNUCmpXchg;
  1439. break;
  1440. }
  1441. // Check we have the right number of arguments.
  1442. if (TheCall->getNumArgs() < NumArgs[Form]) {
  1443. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1444. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  1445. << TheCall->getCallee()->getSourceRange();
  1446. return ExprError();
  1447. } else if (TheCall->getNumArgs() > NumArgs[Form]) {
  1448. Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
  1449. diag::err_typecheck_call_too_many_args)
  1450. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  1451. << TheCall->getCallee()->getSourceRange();
  1452. return ExprError();
  1453. }
  1454. // Inspect the first argument of the atomic operation.
  1455. Expr *Ptr = TheCall->getArg(0);
  1456. Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
  1457. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  1458. if (!pointerType) {
  1459. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1460. << Ptr->getType() << Ptr->getSourceRange();
  1461. return ExprError();
  1462. }
  1463. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  1464. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  1465. QualType ValType = AtomTy; // 'C'
  1466. if (IsC11) {
  1467. if (!AtomTy->isAtomicType()) {
  1468. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  1469. << Ptr->getType() << Ptr->getSourceRange();
  1470. return ExprError();
  1471. }
  1472. if (AtomTy.isConstQualified()) {
  1473. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  1474. << Ptr->getType() << Ptr->getSourceRange();
  1475. return ExprError();
  1476. }
  1477. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  1478. }
  1479. // For an arithmetic operation, the implied arithmetic must be well-formed.
  1480. if (Form == Arithmetic) {
  1481. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  1482. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  1483. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  1484. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  1485. return ExprError();
  1486. }
  1487. if (!IsAddSub && !ValType->isIntegerType()) {
  1488. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  1489. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  1490. return ExprError();
  1491. }
  1492. if (IsC11 && ValType->isPointerType() &&
  1493. RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
  1494. diag::err_incomplete_type)) {
  1495. return ExprError();
  1496. }
  1497. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  1498. // For __atomic_*_n operations, the value type must be a scalar integral or
  1499. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  1500. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  1501. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  1502. return ExprError();
  1503. }
  1504. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  1505. !AtomTy->isScalarType()) {
  1506. // For GNU atomics, require a trivially-copyable type. This is not part of
  1507. // the GNU atomics specification, but we enforce it for sanity.
  1508. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  1509. << Ptr->getType() << Ptr->getSourceRange();
  1510. return ExprError();
  1511. }
  1512. // FIXME: For any builtin other than a load, the ValType must not be
  1513. // const-qualified.
  1514. switch (ValType.getObjCLifetime()) {
  1515. case Qualifiers::OCL_None:
  1516. case Qualifiers::OCL_ExplicitNone:
  1517. // okay
  1518. break;
  1519. case Qualifiers::OCL_Weak:
  1520. case Qualifiers::OCL_Strong:
  1521. case Qualifiers::OCL_Autoreleasing:
  1522. // FIXME: Can this happen? By this point, ValType should be known
  1523. // to be trivially copyable.
  1524. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1525. << ValType << Ptr->getSourceRange();
  1526. return ExprError();
  1527. }
  1528. // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
  1529. // volatile-ness of the pointee-type inject itself into the result or the
  1530. // other operands.
  1531. ValType.removeLocalVolatile();
  1532. QualType ResultType = ValType;
  1533. if (Form == Copy || Form == GNUXchg || Form == Init)
  1534. ResultType = Context.VoidTy;
  1535. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  1536. ResultType = Context.BoolTy;
  1537. // The type of a parameter passed 'by value'. In the GNU atomics, such
  1538. // arguments are actually passed as pointers.
  1539. QualType ByValType = ValType; // 'CP'
  1540. if (!IsC11 && !IsN)
  1541. ByValType = Ptr->getType();
  1542. // The first argument --- the pointer --- has a fixed type; we
  1543. // deduce the types of the rest of the arguments accordingly. Walk
  1544. // the remaining arguments, converting them to the deduced value type.
  1545. for (unsigned i = 1; i != NumArgs[Form]; ++i) {
  1546. QualType Ty;
  1547. if (i < NumVals[Form] + 1) {
  1548. switch (i) {
  1549. case 1:
  1550. // The second argument is the non-atomic operand. For arithmetic, this
  1551. // is always passed by value, and for a compare_exchange it is always
  1552. // passed by address. For the rest, GNU uses by-address and C11 uses
  1553. // by-value.
  1554. assert(Form != Load);
  1555. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  1556. Ty = ValType;
  1557. else if (Form == Copy || Form == Xchg)
  1558. Ty = ByValType;
  1559. else if (Form == Arithmetic)
  1560. Ty = Context.getPointerDiffType();
  1561. else
  1562. Ty = Context.getPointerType(ValType.getUnqualifiedType());
  1563. break;
  1564. case 2:
  1565. // The third argument to compare_exchange / GNU exchange is a
  1566. // (pointer to a) desired value.
  1567. Ty = ByValType;
  1568. break;
  1569. case 3:
  1570. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  1571. Ty = Context.BoolTy;
  1572. break;
  1573. }
  1574. } else {
  1575. // The order(s) are always converted to int.
  1576. Ty = Context.IntTy;
  1577. }
  1578. InitializedEntity Entity =
  1579. InitializedEntity::InitializeParameter(Context, Ty, false);
  1580. ExprResult Arg = TheCall->getArg(i);
  1581. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1582. if (Arg.isInvalid())
  1583. return true;
  1584. TheCall->setArg(i, Arg.get());
  1585. }
  1586. // Permute the arguments into a 'consistent' order.
  1587. SmallVector<Expr*, 5> SubExprs;
  1588. SubExprs.push_back(Ptr);
  1589. switch (Form) {
  1590. case Init:
  1591. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  1592. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1593. break;
  1594. case Load:
  1595. SubExprs.push_back(TheCall->getArg(1)); // Order
  1596. break;
  1597. case Copy:
  1598. case Arithmetic:
  1599. case Xchg:
  1600. SubExprs.push_back(TheCall->getArg(2)); // Order
  1601. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1602. break;
  1603. case GNUXchg:
  1604. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  1605. SubExprs.push_back(TheCall->getArg(3)); // Order
  1606. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1607. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1608. break;
  1609. case C11CmpXchg:
  1610. SubExprs.push_back(TheCall->getArg(3)); // Order
  1611. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1612. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  1613. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1614. break;
  1615. case GNUCmpXchg:
  1616. SubExprs.push_back(TheCall->getArg(4)); // Order
  1617. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1618. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  1619. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1620. SubExprs.push_back(TheCall->getArg(3)); // Weak
  1621. break;
  1622. }
  1623. if (SubExprs.size() >= 2 && Form != Init) {
  1624. llvm::APSInt Result(32);
  1625. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  1626. !isValidOrderingForOp(Result.getSExtValue(), Op))
  1627. Diag(SubExprs[1]->getLocStart(),
  1628. diag::warn_atomic_op_has_invalid_memory_order)
  1629. << SubExprs[1]->getSourceRange();
  1630. }
  1631. AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  1632. SubExprs, ResultType, Op,
  1633. TheCall->getRParenLoc());
  1634. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  1635. (Op == AtomicExpr::AO__c11_atomic_store)) &&
  1636. Context.AtomicUsesUnsupportedLibcall(AE))
  1637. Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
  1638. ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
  1639. return AE;
  1640. }
  1641. /// checkBuiltinArgument - Given a call to a builtin function, perform
  1642. /// normal type-checking on the given argument, updating the call in
  1643. /// place. This is useful when a builtin function requires custom
  1644. /// type-checking for some of its arguments but not necessarily all of
  1645. /// them.
  1646. ///
  1647. /// Returns true on error.
  1648. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  1649. FunctionDecl *Fn = E->getDirectCallee();
  1650. assert(Fn && "builtin call without direct callee!");
  1651. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  1652. InitializedEntity Entity =
  1653. InitializedEntity::InitializeParameter(S.Context, Param);
  1654. ExprResult Arg = E->getArg(0);
  1655. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1656. if (Arg.isInvalid())
  1657. return true;
  1658. E->setArg(ArgIndex, Arg.get());
  1659. return false;
  1660. }
  1661. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  1662. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  1663. /// type of its first argument. The main ActOnCallExpr routines have already
  1664. /// promoted the types of arguments because all of these calls are prototyped as
  1665. /// void(...).
  1666. ///
  1667. /// This function goes through and does final semantic checking for these
  1668. /// builtins,
  1669. ExprResult
  1670. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  1671. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  1672. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1673. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1674. // Ensure that we have at least one argument to do type inference from.
  1675. if (TheCall->getNumArgs() < 1) {
  1676. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1677. << 0 << 1 << TheCall->getNumArgs()
  1678. << TheCall->getCallee()->getSourceRange();
  1679. return ExprError();
  1680. }
  1681. // Inspect the first argument of the atomic builtin. This should always be
  1682. // a pointer type, whose element is an integral scalar or pointer type.
  1683. // Because it is a pointer type, we don't have to worry about any implicit
  1684. // casts here.
  1685. // FIXME: We don't allow floating point scalars as input.
  1686. Expr *FirstArg = TheCall->getArg(0);
  1687. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  1688. if (FirstArgResult.isInvalid())
  1689. return ExprError();
  1690. FirstArg = FirstArgResult.get();
  1691. TheCall->setArg(0, FirstArg);
  1692. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  1693. if (!pointerType) {
  1694. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1695. << FirstArg->getType() << FirstArg->getSourceRange();
  1696. return ExprError();
  1697. }
  1698. QualType ValType = pointerType->getPointeeType();
  1699. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1700. !ValType->isBlockPointerType()) {
  1701. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  1702. << FirstArg->getType() << FirstArg->getSourceRange();
  1703. return ExprError();
  1704. }
  1705. switch (ValType.getObjCLifetime()) {
  1706. case Qualifiers::OCL_None:
  1707. case Qualifiers::OCL_ExplicitNone:
  1708. // okay
  1709. break;
  1710. case Qualifiers::OCL_Weak:
  1711. case Qualifiers::OCL_Strong:
  1712. case Qualifiers::OCL_Autoreleasing:
  1713. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1714. << ValType << FirstArg->getSourceRange();
  1715. return ExprError();
  1716. }
  1717. // Strip any qualifiers off ValType.
  1718. ValType = ValType.getUnqualifiedType();
  1719. // The majority of builtins return a value, but a few have special return
  1720. // types, so allow them to override appropriately below.
  1721. QualType ResultType = ValType;
  1722. // We need to figure out which concrete builtin this maps onto. For example,
  1723. // __sync_fetch_and_add with a 2 byte object turns into
  1724. // __sync_fetch_and_add_2.
  1725. #define BUILTIN_ROW(x) \
  1726. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  1727. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  1728. static const unsigned BuiltinIndices[][5] = {
  1729. BUILTIN_ROW(__sync_fetch_and_add),
  1730. BUILTIN_ROW(__sync_fetch_and_sub),
  1731. BUILTIN_ROW(__sync_fetch_and_or),
  1732. BUILTIN_ROW(__sync_fetch_and_and),
  1733. BUILTIN_ROW(__sync_fetch_and_xor),
  1734. BUILTIN_ROW(__sync_fetch_and_nand),
  1735. BUILTIN_ROW(__sync_add_and_fetch),
  1736. BUILTIN_ROW(__sync_sub_and_fetch),
  1737. BUILTIN_ROW(__sync_and_and_fetch),
  1738. BUILTIN_ROW(__sync_or_and_fetch),
  1739. BUILTIN_ROW(__sync_xor_and_fetch),
  1740. BUILTIN_ROW(__sync_nand_and_fetch),
  1741. BUILTIN_ROW(__sync_val_compare_and_swap),
  1742. BUILTIN_ROW(__sync_bool_compare_and_swap),
  1743. BUILTIN_ROW(__sync_lock_test_and_set),
  1744. BUILTIN_ROW(__sync_lock_release),
  1745. BUILTIN_ROW(__sync_swap)
  1746. };
  1747. #undef BUILTIN_ROW
  1748. // Determine the index of the size.
  1749. unsigned SizeIndex;
  1750. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  1751. case 1: SizeIndex = 0; break;
  1752. case 2: SizeIndex = 1; break;
  1753. case 4: SizeIndex = 2; break;
  1754. case 8: SizeIndex = 3; break;
  1755. case 16: SizeIndex = 4; break;
  1756. default:
  1757. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  1758. << FirstArg->getType() << FirstArg->getSourceRange();
  1759. return ExprError();
  1760. }
  1761. // Each of these builtins has one pointer argument, followed by some number of
  1762. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  1763. // that we ignore. Find out which row of BuiltinIndices to read from as well
  1764. // as the number of fixed args.
  1765. unsigned BuiltinID = FDecl->getBuiltinID();
  1766. unsigned BuiltinIndex, NumFixed = 1;
  1767. bool WarnAboutSemanticsChange = false;
  1768. switch (BuiltinID) {
  1769. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  1770. case Builtin::BI__sync_fetch_and_add:
  1771. case Builtin::BI__sync_fetch_and_add_1:
  1772. case Builtin::BI__sync_fetch_and_add_2:
  1773. case Builtin::BI__sync_fetch_and_add_4:
  1774. case Builtin::BI__sync_fetch_and_add_8:
  1775. case Builtin::BI__sync_fetch_and_add_16:
  1776. BuiltinIndex = 0;
  1777. break;
  1778. case Builtin::BI__sync_fetch_and_sub:
  1779. case Builtin::BI__sync_fetch_and_sub_1:
  1780. case Builtin::BI__sync_fetch_and_sub_2:
  1781. case Builtin::BI__sync_fetch_and_sub_4:
  1782. case Builtin::BI__sync_fetch_and_sub_8:
  1783. case Builtin::BI__sync_fetch_and_sub_16:
  1784. BuiltinIndex = 1;
  1785. break;
  1786. case Builtin::BI__sync_fetch_and_or:
  1787. case Builtin::BI__sync_fetch_and_or_1:
  1788. case Builtin::BI__sync_fetch_and_or_2:
  1789. case Builtin::BI__sync_fetch_and_or_4:
  1790. case Builtin::BI__sync_fetch_and_or_8:
  1791. case Builtin::BI__sync_fetch_and_or_16:
  1792. BuiltinIndex = 2;
  1793. break;
  1794. case Builtin::BI__sync_fetch_and_and:
  1795. case Builtin::BI__sync_fetch_and_and_1:
  1796. case Builtin::BI__sync_fetch_and_and_2:
  1797. case Builtin::BI__sync_fetch_and_and_4:
  1798. case Builtin::BI__sync_fetch_and_and_8:
  1799. case Builtin::BI__sync_fetch_and_and_16:
  1800. BuiltinIndex = 3;
  1801. break;
  1802. case Builtin::BI__sync_fetch_and_xor:
  1803. case Builtin::BI__sync_fetch_and_xor_1:
  1804. case Builtin::BI__sync_fetch_and_xor_2:
  1805. case Builtin::BI__sync_fetch_and_xor_4:
  1806. case Builtin::BI__sync_fetch_and_xor_8:
  1807. case Builtin::BI__sync_fetch_and_xor_16:
  1808. BuiltinIndex = 4;
  1809. break;
  1810. case Builtin::BI__sync_fetch_and_nand:
  1811. case Builtin::BI__sync_fetch_and_nand_1:
  1812. case Builtin::BI__sync_fetch_and_nand_2:
  1813. case Builtin::BI__sync_fetch_and_nand_4:
  1814. case Builtin::BI__sync_fetch_and_nand_8:
  1815. case Builtin::BI__sync_fetch_and_nand_16:
  1816. BuiltinIndex = 5;
  1817. WarnAboutSemanticsChange = true;
  1818. break;
  1819. case Builtin::BI__sync_add_and_fetch:
  1820. case Builtin::BI__sync_add_and_fetch_1:
  1821. case Builtin::BI__sync_add_and_fetch_2:
  1822. case Builtin::BI__sync_add_and_fetch_4:
  1823. case Builtin::BI__sync_add_and_fetch_8:
  1824. case Builtin::BI__sync_add_and_fetch_16:
  1825. BuiltinIndex = 6;
  1826. break;
  1827. case Builtin::BI__sync_sub_and_fetch:
  1828. case Builtin::BI__sync_sub_and_fetch_1:
  1829. case Builtin::BI__sync_sub_and_fetch_2:
  1830. case Builtin::BI__sync_sub_and_fetch_4:
  1831. case Builtin::BI__sync_sub_and_fetch_8:
  1832. case Builtin::BI__sync_sub_and_fetch_16:
  1833. BuiltinIndex = 7;
  1834. break;
  1835. case Builtin::BI__sync_and_and_fetch:
  1836. case Builtin::BI__sync_and_and_fetch_1:
  1837. case Builtin::BI__sync_and_and_fetch_2:
  1838. case Builtin::BI__sync_and_and_fetch_4:
  1839. case Builtin::BI__sync_and_and_fetch_8:
  1840. case Builtin::BI__sync_and_and_fetch_16:
  1841. BuiltinIndex = 8;
  1842. break;
  1843. case Builtin::BI__sync_or_and_fetch:
  1844. case Builtin::BI__sync_or_and_fetch_1:
  1845. case Builtin::BI__sync_or_and_fetch_2:
  1846. case Builtin::BI__sync_or_and_fetch_4:
  1847. case Builtin::BI__sync_or_and_fetch_8:
  1848. case Builtin::BI__sync_or_and_fetch_16:
  1849. BuiltinIndex = 9;
  1850. break;
  1851. case Builtin::BI__sync_xor_and_fetch:
  1852. case Builtin::BI__sync_xor_and_fetch_1:
  1853. case Builtin::BI__sync_xor_and_fetch_2:
  1854. case Builtin::BI__sync_xor_and_fetch_4:
  1855. case Builtin::BI__sync_xor_and_fetch_8:
  1856. case Builtin::BI__sync_xor_and_fetch_16:
  1857. BuiltinIndex = 10;
  1858. break;
  1859. case Builtin::BI__sync_nand_and_fetch:
  1860. case Builtin::BI__sync_nand_and_fetch_1:
  1861. case Builtin::BI__sync_nand_and_fetch_2:
  1862. case Builtin::BI__sync_nand_and_fetch_4:
  1863. case Builtin::BI__sync_nand_and_fetch_8:
  1864. case Builtin::BI__sync_nand_and_fetch_16:
  1865. BuiltinIndex = 11;
  1866. WarnAboutSemanticsChange = true;
  1867. break;
  1868. case Builtin::BI__sync_val_compare_and_swap:
  1869. case Builtin::BI__sync_val_compare_and_swap_1:
  1870. case Builtin::BI__sync_val_compare_and_swap_2:
  1871. case Builtin::BI__sync_val_compare_and_swap_4:
  1872. case Builtin::BI__sync_val_compare_and_swap_8:
  1873. case Builtin::BI__sync_val_compare_and_swap_16:
  1874. BuiltinIndex = 12;
  1875. NumFixed = 2;
  1876. break;
  1877. case Builtin::BI__sync_bool_compare_and_swap:
  1878. case Builtin::BI__sync_bool_compare_and_swap_1:
  1879. case Builtin::BI__sync_bool_compare_and_swap_2:
  1880. case Builtin::BI__sync_bool_compare_and_swap_4:
  1881. case Builtin::BI__sync_bool_compare_and_swap_8:
  1882. case Builtin::BI__sync_bool_compare_and_swap_16:
  1883. BuiltinIndex = 13;
  1884. NumFixed = 2;
  1885. ResultType = Context.BoolTy;
  1886. break;
  1887. case Builtin::BI__sync_lock_test_and_set:
  1888. case Builtin::BI__sync_lock_test_and_set_1:
  1889. case Builtin::BI__sync_lock_test_and_set_2:
  1890. case Builtin::BI__sync_lock_test_and_set_4:
  1891. case Builtin::BI__sync_lock_test_and_set_8:
  1892. case Builtin::BI__sync_lock_test_and_set_16:
  1893. BuiltinIndex = 14;
  1894. break;
  1895. case Builtin::BI__sync_lock_release:
  1896. case Builtin::BI__sync_lock_release_1:
  1897. case Builtin::BI__sync_lock_release_2:
  1898. case Builtin::BI__sync_lock_release_4:
  1899. case Builtin::BI__sync_lock_release_8:
  1900. case Builtin::BI__sync_lock_release_16:
  1901. BuiltinIndex = 15;
  1902. NumFixed = 0;
  1903. ResultType = Context.VoidTy;
  1904. break;
  1905. case Builtin::BI__sync_swap:
  1906. case Builtin::BI__sync_swap_1:
  1907. case Builtin::BI__sync_swap_2:
  1908. case Builtin::BI__sync_swap_4:
  1909. case Builtin::BI__sync_swap_8:
  1910. case Builtin::BI__sync_swap_16:
  1911. BuiltinIndex = 16;
  1912. break;
  1913. }
  1914. // Now that we know how many fixed arguments we expect, first check that we
  1915. // have at least that many.
  1916. if (TheCall->getNumArgs() < 1+NumFixed) {
  1917. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1918. << 0 << 1+NumFixed << TheCall->getNumArgs()
  1919. << TheCall->getCallee()->getSourceRange();
  1920. return ExprError();
  1921. }
  1922. if (WarnAboutSemanticsChange) {
  1923. Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
  1924. << TheCall->getCallee()->getSourceRange();
  1925. }
  1926. // Get the decl for the concrete builtin from this, we can tell what the
  1927. // concrete integer type we should convert to is.
  1928. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  1929. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  1930. FunctionDecl *NewBuiltinDecl;
  1931. if (NewBuiltinID == BuiltinID)
  1932. NewBuiltinDecl = FDecl;
  1933. else {
  1934. // Perform builtin lookup to avoid redeclaring it.
  1935. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  1936. LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
  1937. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  1938. assert(Res.getFoundDecl());
  1939. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  1940. if (!NewBuiltinDecl)
  1941. return ExprError();
  1942. }
  1943. // The first argument --- the pointer --- has a fixed type; we
  1944. // deduce the types of the rest of the arguments accordingly. Walk
  1945. // the remaining arguments, converting them to the deduced value type.
  1946. for (unsigned i = 0; i != NumFixed; ++i) {
  1947. ExprResult Arg = TheCall->getArg(i+1);
  1948. // GCC does an implicit conversion to the pointer or integer ValType. This
  1949. // can fail in some cases (1i -> int**), check for this error case now.
  1950. // Initialize the argument.
  1951. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  1952. ValType, /*consume*/ false);
  1953. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1954. if (Arg.isInvalid())
  1955. return ExprError();
  1956. // Okay, we have something that *can* be converted to the right type. Check
  1957. // to see if there is a potentially weird extension going on here. This can
  1958. // happen when you do an atomic operation on something like an char* and
  1959. // pass in 42. The 42 gets converted to char. This is even more strange
  1960. // for things like 45.123 -> char, etc.
  1961. // FIXME: Do this check.
  1962. TheCall->setArg(i+1, Arg.get());
  1963. }
  1964. ASTContext& Context = this->getASTContext();
  1965. // Create a new DeclRefExpr to refer to the new decl.
  1966. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  1967. Context,
  1968. DRE->getQualifierLoc(),
  1969. SourceLocation(),
  1970. NewBuiltinDecl,
  1971. /*enclosing*/ false,
  1972. DRE->getLocation(),
  1973. Context.BuiltinFnTy,
  1974. DRE->getValueKind());
  1975. // Set the callee in the CallExpr.
  1976. // FIXME: This loses syntactic information.
  1977. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  1978. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  1979. CK_BuiltinFnToFnPtr);
  1980. TheCall->setCallee(PromotedCall.get());
  1981. // Change the result type of the call to match the original value type. This
  1982. // is arbitrary, but the codegen for these builtins ins design to handle it
  1983. // gracefully.
  1984. TheCall->setType(ResultType);
  1985. return TheCallResult;
  1986. }
  1987. /// CheckObjCString - Checks that the argument to the builtin
  1988. /// CFString constructor is correct
  1989. /// Note: It might also make sense to do the UTF-16 conversion here (would
  1990. /// simplify the backend).
  1991. bool Sema::CheckObjCString(Expr *Arg) {
  1992. Arg = Arg->IgnoreParenCasts();
  1993. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  1994. if (!Literal || !Literal->isAscii()) {
  1995. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  1996. << Arg->getSourceRange();
  1997. return true;
  1998. }
  1999. if (Literal->containsNonAsciiOrNull()) {
  2000. StringRef String = Literal->getString();
  2001. unsigned NumBytes = String.size();
  2002. SmallVector<UTF16, 128> ToBuf(NumBytes);
  2003. const UTF8 *FromPtr = (const UTF8 *)String.data();
  2004. UTF16 *ToPtr = &ToBuf[0];
  2005. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  2006. &ToPtr, ToPtr + NumBytes,
  2007. strictConversion);
  2008. // Check for conversion failure.
  2009. if (Result != conversionOK)
  2010. Diag(Arg->getLocStart(),
  2011. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  2012. }
  2013. return false;
  2014. }
  2015. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  2016. /// Emit an error and return true on failure, return false on success.
  2017. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  2018. Expr *Fn = TheCall->getCallee();
  2019. if (TheCall->getNumArgs() > 2) {
  2020. Diag(TheCall->getArg(2)->getLocStart(),
  2021. diag::err_typecheck_call_too_many_args)
  2022. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  2023. << Fn->getSourceRange()
  2024. << SourceRange(TheCall->getArg(2)->getLocStart(),
  2025. (*(TheCall->arg_end()-1))->getLocEnd());
  2026. return true;
  2027. }
  2028. if (TheCall->getNumArgs() < 2) {
  2029. return Diag(TheCall->getLocEnd(),
  2030. diag::err_typecheck_call_too_few_args_at_least)
  2031. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  2032. }
  2033. // Type-check the first argument normally.
  2034. if (checkBuiltinArgument(*this, TheCall, 0))
  2035. return true;
  2036. // Determine whether the current function is variadic or not.
  2037. BlockScopeInfo *CurBlock = getCurBlock();
  2038. bool isVariadic;
  2039. if (CurBlock)
  2040. isVariadic = CurBlock->TheDecl->isVariadic();
  2041. else if (FunctionDecl *FD = getCurFunctionDecl())
  2042. isVariadic = FD->isVariadic();
  2043. else
  2044. isVariadic = getCurMethodDecl()->isVariadic();
  2045. if (!isVariadic) {
  2046. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  2047. return true;
  2048. }
  2049. // Verify that the second argument to the builtin is the last argument of the
  2050. // current function or method.
  2051. bool SecondArgIsLastNamedArgument = false;
  2052. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  2053. // These are valid if SecondArgIsLastNamedArgument is false after the next
  2054. // block.
  2055. QualType Type;
  2056. SourceLocation ParamLoc;
  2057. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  2058. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  2059. // FIXME: This isn't correct for methods (results in bogus warning).
  2060. // Get the last formal in the current function.
  2061. const ParmVarDecl *LastArg;
  2062. if (CurBlock)
  2063. LastArg = *(CurBlock->TheDecl->param_end()-1);
  2064. else if (FunctionDecl *FD = getCurFunctionDecl())
  2065. LastArg = *(FD->param_end()-1);
  2066. else
  2067. LastArg = *(getCurMethodDecl()->param_end()-1);
  2068. SecondArgIsLastNamedArgument = PV == LastArg;
  2069. Type = PV->getType();
  2070. ParamLoc = PV->getLocation();
  2071. }
  2072. }
  2073. if (!SecondArgIsLastNamedArgument)
  2074. Diag(TheCall->getArg(1)->getLocStart(),
  2075. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  2076. else if (Type->isReferenceType()) {
  2077. Diag(Arg->getLocStart(),
  2078. diag::warn_va_start_of_reference_type_is_undefined);
  2079. Diag(ParamLoc, diag::note_parameter_type) << Type;
  2080. }
  2081. TheCall->setType(Context.VoidTy);
  2082. return false;
  2083. }
  2084. bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
  2085. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  2086. // const char *named_addr);
  2087. Expr *Func = Call->getCallee();
  2088. if (Call->getNumArgs() < 3)
  2089. return Diag(Call->getLocEnd(),
  2090. diag::err_typecheck_call_too_few_args_at_least)
  2091. << 0 /*function call*/ << 3 << Call->getNumArgs();
  2092. // Determine whether the current function is variadic or not.
  2093. bool IsVariadic;
  2094. if (BlockScopeInfo *CurBlock = getCurBlock())
  2095. IsVariadic = CurBlock->TheDecl->isVariadic();
  2096. else if (FunctionDecl *FD = getCurFunctionDecl())
  2097. IsVariadic = FD->isVariadic();
  2098. else if (ObjCMethodDecl *MD = getCurMethodDecl())
  2099. IsVariadic = MD->isVariadic();
  2100. else
  2101. llvm_unreachable("unexpected statement type");
  2102. if (!IsVariadic) {
  2103. Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  2104. return true;
  2105. }
  2106. // Type-check the first argument normally.
  2107. if (checkBuiltinArgument(*this, Call, 0))
  2108. return true;
  2109. const struct {
  2110. unsigned ArgNo;
  2111. QualType Type;
  2112. } ArgumentTypes[] = {
  2113. { 1, Context.getPointerType(Context.CharTy.withConst()) },
  2114. { 2, Context.getSizeType() },
  2115. };
  2116. for (const auto &AT : ArgumentTypes) {
  2117. const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
  2118. if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
  2119. continue;
  2120. Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
  2121. << Arg->getType() << AT.Type << 1 /* different class */
  2122. << 0 /* qualifier difference */ << 3 /* parameter mismatch */
  2123. << AT.ArgNo + 1 << Arg->getType() << AT.Type;
  2124. }
  2125. return false;
  2126. }
  2127. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  2128. /// friends. This is declared to take (...), so we have to check everything.
  2129. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  2130. if (TheCall->getNumArgs() < 2)
  2131. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2132. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  2133. if (TheCall->getNumArgs() > 2)
  2134. return Diag(TheCall->getArg(2)->getLocStart(),
  2135. diag::err_typecheck_call_too_many_args)
  2136. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  2137. << SourceRange(TheCall->getArg(2)->getLocStart(),
  2138. (*(TheCall->arg_end()-1))->getLocEnd());
  2139. ExprResult OrigArg0 = TheCall->getArg(0);
  2140. ExprResult OrigArg1 = TheCall->getArg(1);
  2141. // Do standard promotions between the two arguments, returning their common
  2142. // type.
  2143. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  2144. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  2145. return true;
  2146. // Make sure any conversions are pushed back into the call; this is
  2147. // type safe since unordered compare builtins are declared as "_Bool
  2148. // foo(...)".
  2149. TheCall->setArg(0, OrigArg0.get());
  2150. TheCall->setArg(1, OrigArg1.get());
  2151. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  2152. return false;
  2153. // If the common type isn't a real floating type, then the arguments were
  2154. // invalid for this operation.
  2155. if (Res.isNull() || !Res->isRealFloatingType())
  2156. return Diag(OrigArg0.get()->getLocStart(),
  2157. diag::err_typecheck_call_invalid_ordered_compare)
  2158. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  2159. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  2160. return false;
  2161. }
  2162. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  2163. /// __builtin_isnan and friends. This is declared to take (...), so we have
  2164. /// to check everything. We expect the last argument to be a floating point
  2165. /// value.
  2166. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  2167. if (TheCall->getNumArgs() < NumArgs)
  2168. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2169. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  2170. if (TheCall->getNumArgs() > NumArgs)
  2171. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  2172. diag::err_typecheck_call_too_many_args)
  2173. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  2174. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  2175. (*(TheCall->arg_end()-1))->getLocEnd());
  2176. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  2177. if (OrigArg->isTypeDependent())
  2178. return false;
  2179. // This operation requires a non-_Complex floating-point number.
  2180. if (!OrigArg->getType()->isRealFloatingType())
  2181. return Diag(OrigArg->getLocStart(),
  2182. diag::err_typecheck_call_invalid_unary_fp)
  2183. << OrigArg->getType() << OrigArg->getSourceRange();
  2184. // If this is an implicit conversion from float -> double, remove it.
  2185. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  2186. Expr *CastArg = Cast->getSubExpr();
  2187. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  2188. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  2189. "promotion from float to double is the only expected cast here");
  2190. Cast->setSubExpr(nullptr);
  2191. TheCall->setArg(NumArgs-1, CastArg);
  2192. }
  2193. }
  2194. return false;
  2195. }
  2196. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  2197. // This is declared to take (...), so we have to check everything.
  2198. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  2199. if (TheCall->getNumArgs() < 2)
  2200. return ExprError(Diag(TheCall->getLocEnd(),
  2201. diag::err_typecheck_call_too_few_args_at_least)
  2202. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  2203. << TheCall->getSourceRange());
  2204. // Determine which of the following types of shufflevector we're checking:
  2205. // 1) unary, vector mask: (lhs, mask)
  2206. // 2) binary, vector mask: (lhs, rhs, mask)
  2207. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  2208. QualType resType = TheCall->getArg(0)->getType();
  2209. unsigned numElements = 0;
  2210. if (!TheCall->getArg(0)->isTypeDependent() &&
  2211. !TheCall->getArg(1)->isTypeDependent()) {
  2212. QualType LHSType = TheCall->getArg(0)->getType();
  2213. QualType RHSType = TheCall->getArg(1)->getType();
  2214. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  2215. return ExprError(Diag(TheCall->getLocStart(),
  2216. diag::err_shufflevector_non_vector)
  2217. << SourceRange(TheCall->getArg(0)->getLocStart(),
  2218. TheCall->getArg(1)->getLocEnd()));
  2219. numElements = LHSType->getAs<VectorType>()->getNumElements();
  2220. unsigned numResElements = TheCall->getNumArgs() - 2;
  2221. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  2222. // with mask. If so, verify that RHS is an integer vector type with the
  2223. // same number of elts as lhs.
  2224. if (TheCall->getNumArgs() == 2) {
  2225. if (!RHSType->hasIntegerRepresentation() ||
  2226. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  2227. return ExprError(Diag(TheCall->getLocStart(),
  2228. diag::err_shufflevector_incompatible_vector)
  2229. << SourceRange(TheCall->getArg(1)->getLocStart(),
  2230. TheCall->getArg(1)->getLocEnd()));
  2231. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  2232. return ExprError(Diag(TheCall->getLocStart(),
  2233. diag::err_shufflevector_incompatible_vector)
  2234. << SourceRange(TheCall->getArg(0)->getLocStart(),
  2235. TheCall->getArg(1)->getLocEnd()));
  2236. } else if (numElements != numResElements) {
  2237. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  2238. resType = Context.getVectorType(eltType, numResElements,
  2239. VectorType::GenericVector);
  2240. }
  2241. }
  2242. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  2243. if (TheCall->getArg(i)->isTypeDependent() ||
  2244. TheCall->getArg(i)->isValueDependent())
  2245. continue;
  2246. llvm::APSInt Result(32);
  2247. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  2248. return ExprError(Diag(TheCall->getLocStart(),
  2249. diag::err_shufflevector_nonconstant_argument)
  2250. << TheCall->getArg(i)->getSourceRange());
  2251. // Allow -1 which will be translated to undef in the IR.
  2252. if (Result.isSigned() && Result.isAllOnesValue())
  2253. continue;
  2254. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  2255. return ExprError(Diag(TheCall->getLocStart(),
  2256. diag::err_shufflevector_argument_too_large)
  2257. << TheCall->getArg(i)->getSourceRange());
  2258. }
  2259. SmallVector<Expr*, 32> exprs;
  2260. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  2261. exprs.push_back(TheCall->getArg(i));
  2262. TheCall->setArg(i, nullptr);
  2263. }
  2264. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  2265. TheCall->getCallee()->getLocStart(),
  2266. TheCall->getRParenLoc());
  2267. }
  2268. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  2269. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  2270. SourceLocation BuiltinLoc,
  2271. SourceLocation RParenLoc) {
  2272. ExprValueKind VK = VK_RValue;
  2273. ExprObjectKind OK = OK_Ordinary;
  2274. QualType DstTy = TInfo->getType();
  2275. QualType SrcTy = E->getType();
  2276. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  2277. return ExprError(Diag(BuiltinLoc,
  2278. diag::err_convertvector_non_vector)
  2279. << E->getSourceRange());
  2280. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  2281. return ExprError(Diag(BuiltinLoc,
  2282. diag::err_convertvector_non_vector_type));
  2283. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  2284. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  2285. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  2286. if (SrcElts != DstElts)
  2287. return ExprError(Diag(BuiltinLoc,
  2288. diag::err_convertvector_incompatible_vector)
  2289. << E->getSourceRange());
  2290. }
  2291. return new (Context)
  2292. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  2293. }
  2294. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  2295. // This is declared to take (const void*, ...) and can take two
  2296. // optional constant int args.
  2297. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  2298. unsigned NumArgs = TheCall->getNumArgs();
  2299. if (NumArgs > 3)
  2300. return Diag(TheCall->getLocEnd(),
  2301. diag::err_typecheck_call_too_many_args_at_most)
  2302. << 0 /*function call*/ << 3 << NumArgs
  2303. << TheCall->getSourceRange();
  2304. // Argument 0 is checked for us and the remaining arguments must be
  2305. // constant integers.
  2306. for (unsigned i = 1; i != NumArgs; ++i)
  2307. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  2308. return true;
  2309. return false;
  2310. }
  2311. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  2312. // __assume does not evaluate its arguments, and should warn if its argument
  2313. // has side effects.
  2314. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  2315. Expr *Arg = TheCall->getArg(0);
  2316. if (Arg->isInstantiationDependent()) return false;
  2317. if (Arg->HasSideEffects(Context))
  2318. Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
  2319. << Arg->getSourceRange()
  2320. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  2321. return false;
  2322. }
  2323. /// Handle __builtin_assume_aligned. This is declared
  2324. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  2325. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  2326. unsigned NumArgs = TheCall->getNumArgs();
  2327. if (NumArgs > 3)
  2328. return Diag(TheCall->getLocEnd(),
  2329. diag::err_typecheck_call_too_many_args_at_most)
  2330. << 0 /*function call*/ << 3 << NumArgs
  2331. << TheCall->getSourceRange();
  2332. // The alignment must be a constant integer.
  2333. Expr *Arg = TheCall->getArg(1);
  2334. // We can't check the value of a dependent argument.
  2335. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  2336. llvm::APSInt Result;
  2337. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  2338. return true;
  2339. if (!Result.isPowerOf2())
  2340. return Diag(TheCall->getLocStart(),
  2341. diag::err_alignment_not_power_of_two)
  2342. << Arg->getSourceRange();
  2343. }
  2344. if (NumArgs > 2) {
  2345. ExprResult Arg(TheCall->getArg(2));
  2346. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  2347. Context.getSizeType(), false);
  2348. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  2349. if (Arg.isInvalid()) return true;
  2350. TheCall->setArg(2, Arg.get());
  2351. }
  2352. return false;
  2353. }
  2354. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  2355. /// TheCall is a constant expression.
  2356. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  2357. llvm::APSInt &Result) {
  2358. Expr *Arg = TheCall->getArg(ArgNum);
  2359. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2360. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  2361. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  2362. if (!Arg->isIntegerConstantExpr(Result, Context))
  2363. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  2364. << FDecl->getDeclName() << Arg->getSourceRange();
  2365. return false;
  2366. }
  2367. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  2368. /// TheCall is a constant expression in the range [Low, High].
  2369. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  2370. int Low, int High) {
  2371. llvm::APSInt Result;
  2372. // We can't check the value of a dependent argument.
  2373. Expr *Arg = TheCall->getArg(ArgNum);
  2374. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2375. return false;
  2376. // Check constant-ness first.
  2377. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  2378. return true;
  2379. if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
  2380. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  2381. << Low << High << Arg->getSourceRange();
  2382. return false;
  2383. }
  2384. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  2385. /// TheCall is an ARM/AArch64 special register string literal.
  2386. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  2387. int ArgNum, unsigned ExpectedFieldNum,
  2388. bool AllowName) {
  2389. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  2390. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  2391. BuiltinID == ARM::BI__builtin_arm_rsr ||
  2392. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  2393. BuiltinID == ARM::BI__builtin_arm_wsr ||
  2394. BuiltinID == ARM::BI__builtin_arm_wsrp;
  2395. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  2396. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  2397. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  2398. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  2399. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  2400. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  2401. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  2402. // We can't check the value of a dependent argument.
  2403. Expr *Arg = TheCall->getArg(ArgNum);
  2404. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2405. return false;
  2406. // Check if the argument is a string literal.
  2407. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2408. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  2409. << Arg->getSourceRange();
  2410. // Check the type of special register given.
  2411. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2412. SmallVector<StringRef, 6> Fields;
  2413. Reg.split(Fields, ":");
  2414. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  2415. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  2416. << Arg->getSourceRange();
  2417. // If the string is the name of a register then we cannot check that it is
  2418. // valid here but if the string is of one the forms described in ACLE then we
  2419. // can check that the supplied fields are integers and within the valid
  2420. // ranges.
  2421. if (Fields.size() > 1) {
  2422. bool FiveFields = Fields.size() == 5;
  2423. bool ValidString = true;
  2424. if (IsARMBuiltin) {
  2425. ValidString &= Fields[0].startswith_lower("cp") ||
  2426. Fields[0].startswith_lower("p");
  2427. if (ValidString)
  2428. Fields[0] =
  2429. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  2430. ValidString &= Fields[2].startswith_lower("c");
  2431. if (ValidString)
  2432. Fields[2] = Fields[2].drop_front(1);
  2433. if (FiveFields) {
  2434. ValidString &= Fields[3].startswith_lower("c");
  2435. if (ValidString)
  2436. Fields[3] = Fields[3].drop_front(1);
  2437. }
  2438. }
  2439. SmallVector<int, 5> Ranges;
  2440. if (FiveFields)
  2441. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
  2442. else
  2443. Ranges.append({15, 7, 15});
  2444. for (unsigned i=0; i<Fields.size(); ++i) {
  2445. int IntField;
  2446. ValidString &= !Fields[i].getAsInteger(10, IntField);
  2447. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  2448. }
  2449. if (!ValidString)
  2450. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  2451. << Arg->getSourceRange();
  2452. } else if (IsAArch64Builtin && Fields.size() == 1) {
  2453. // If the register name is one of those that appear in the condition below
  2454. // and the special register builtin being used is one of the write builtins,
  2455. // then we require that the argument provided for writing to the register
  2456. // is an integer constant expression. This is because it will be lowered to
  2457. // an MSR (immediate) instruction, so we need to know the immediate at
  2458. // compile time.
  2459. if (TheCall->getNumArgs() != 2)
  2460. return false;
  2461. std::string RegLower = Reg.lower();
  2462. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  2463. RegLower != "pan" && RegLower != "uao")
  2464. return false;
  2465. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  2466. }
  2467. return false;
  2468. }
  2469. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  2470. /// This checks that the target supports __builtin_cpu_supports and
  2471. /// that the string argument is constant and valid.
  2472. bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
  2473. Expr *Arg = TheCall->getArg(0);
  2474. // Check if the argument is a string literal.
  2475. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2476. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  2477. << Arg->getSourceRange();
  2478. // Check the contents of the string.
  2479. StringRef Feature =
  2480. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2481. if (!Context.getTargetInfo().validateCpuSupports(Feature))
  2482. return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
  2483. << Arg->getSourceRange();
  2484. return false;
  2485. }
  2486. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  2487. /// This checks that the target supports __builtin_longjmp and
  2488. /// that val is a constant 1.
  2489. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  2490. if (!Context.getTargetInfo().hasSjLjLowering())
  2491. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
  2492. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  2493. Expr *Arg = TheCall->getArg(1);
  2494. llvm::APSInt Result;
  2495. // TODO: This is less than ideal. Overload this to take a value.
  2496. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  2497. return true;
  2498. if (Result != 1)
  2499. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  2500. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  2501. return false;
  2502. }
  2503. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  2504. /// This checks that the target supports __builtin_setjmp.
  2505. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  2506. if (!Context.getTargetInfo().hasSjLjLowering())
  2507. return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
  2508. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  2509. return false;
  2510. }
  2511. namespace {
  2512. enum StringLiteralCheckType {
  2513. SLCT_NotALiteral,
  2514. SLCT_UncheckedLiteral,
  2515. SLCT_CheckedLiteral
  2516. };
  2517. }
  2518. // Determine if an expression is a string literal or constant string.
  2519. // If this function returns false on the arguments to a function expecting a
  2520. // format string, we will usually need to emit a warning.
  2521. // True string literals are then checked by CheckFormatString.
  2522. static StringLiteralCheckType
  2523. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  2524. bool HasVAListArg, unsigned format_idx,
  2525. unsigned firstDataArg, Sema::FormatStringType Type,
  2526. Sema::VariadicCallType CallType, bool InFunctionCall,
  2527. llvm::SmallBitVector &CheckedVarArgs) {
  2528. tryAgain:
  2529. if (E->isTypeDependent() || E->isValueDependent())
  2530. return SLCT_NotALiteral;
  2531. E = E->IgnoreParenCasts();
  2532. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  2533. // Technically -Wformat-nonliteral does not warn about this case.
  2534. // The behavior of printf and friends in this case is implementation
  2535. // dependent. Ideally if the format string cannot be null then
  2536. // it should have a 'nonnull' attribute in the function prototype.
  2537. return SLCT_UncheckedLiteral;
  2538. switch (E->getStmtClass()) {
  2539. case Stmt::BinaryConditionalOperatorClass:
  2540. case Stmt::ConditionalOperatorClass: {
  2541. // The expression is a literal if both sub-expressions were, and it was
  2542. // completely checked only if both sub-expressions were checked.
  2543. const AbstractConditionalOperator *C =
  2544. cast<AbstractConditionalOperator>(E);
  2545. StringLiteralCheckType Left =
  2546. checkFormatStringExpr(S, C->getTrueExpr(), Args,
  2547. HasVAListArg, format_idx, firstDataArg,
  2548. Type, CallType, InFunctionCall, CheckedVarArgs);
  2549. if (Left == SLCT_NotALiteral)
  2550. return SLCT_NotALiteral;
  2551. StringLiteralCheckType Right =
  2552. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  2553. HasVAListArg, format_idx, firstDataArg,
  2554. Type, CallType, InFunctionCall, CheckedVarArgs);
  2555. return Left < Right ? Left : Right;
  2556. }
  2557. case Stmt::ImplicitCastExprClass: {
  2558. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  2559. goto tryAgain;
  2560. }
  2561. case Stmt::OpaqueValueExprClass:
  2562. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  2563. E = src;
  2564. goto tryAgain;
  2565. }
  2566. return SLCT_NotALiteral;
  2567. case Stmt::PredefinedExprClass:
  2568. // While __func__, etc., are technically not string literals, they
  2569. // cannot contain format specifiers and thus are not a security
  2570. // liability.
  2571. return SLCT_UncheckedLiteral;
  2572. case Stmt::DeclRefExprClass: {
  2573. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  2574. // As an exception, do not flag errors for variables binding to
  2575. // const string literals.
  2576. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  2577. bool isConstant = false;
  2578. QualType T = DR->getType();
  2579. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  2580. isConstant = AT->getElementType().isConstant(S.Context);
  2581. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  2582. isConstant = T.isConstant(S.Context) &&
  2583. PT->getPointeeType().isConstant(S.Context);
  2584. } else if (T->isObjCObjectPointerType()) {
  2585. // In ObjC, there is usually no "const ObjectPointer" type,
  2586. // so don't check if the pointee type is constant.
  2587. isConstant = T.isConstant(S.Context);
  2588. }
  2589. if (isConstant) {
  2590. if (const Expr *Init = VD->getAnyInitializer()) {
  2591. // Look through initializers like const char c[] = { "foo" }
  2592. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  2593. if (InitList->isStringLiteralInit())
  2594. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  2595. }
  2596. return checkFormatStringExpr(S, Init, Args,
  2597. HasVAListArg, format_idx,
  2598. firstDataArg, Type, CallType,
  2599. /*InFunctionCall*/false, CheckedVarArgs);
  2600. }
  2601. }
  2602. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  2603. // special check to see if the format string is a function parameter
  2604. // of the function calling the printf function. If the function
  2605. // has an attribute indicating it is a printf-like function, then we
  2606. // should suppress warnings concerning non-literals being used in a call
  2607. // to a vprintf function. For example:
  2608. //
  2609. // void
  2610. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  2611. // va_list ap;
  2612. // va_start(ap, fmt);
  2613. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  2614. // ...
  2615. // }
  2616. if (HasVAListArg) {
  2617. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  2618. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  2619. int PVIndex = PV->getFunctionScopeIndex() + 1;
  2620. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  2621. // adjust for implicit parameter
  2622. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  2623. if (MD->isInstance())
  2624. ++PVIndex;
  2625. // We also check if the formats are compatible.
  2626. // We can't pass a 'scanf' string to a 'printf' function.
  2627. if (PVIndex == PVFormat->getFormatIdx() &&
  2628. Type == S.GetFormatStringType(PVFormat))
  2629. return SLCT_UncheckedLiteral;
  2630. }
  2631. }
  2632. }
  2633. }
  2634. }
  2635. return SLCT_NotALiteral;
  2636. }
  2637. case Stmt::CallExprClass:
  2638. case Stmt::CXXMemberCallExprClass: {
  2639. const CallExpr *CE = cast<CallExpr>(E);
  2640. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  2641. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  2642. unsigned ArgIndex = FA->getFormatIdx();
  2643. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  2644. if (MD->isInstance())
  2645. --ArgIndex;
  2646. const Expr *Arg = CE->getArg(ArgIndex - 1);
  2647. return checkFormatStringExpr(S, Arg, Args,
  2648. HasVAListArg, format_idx, firstDataArg,
  2649. Type, CallType, InFunctionCall,
  2650. CheckedVarArgs);
  2651. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  2652. unsigned BuiltinID = FD->getBuiltinID();
  2653. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  2654. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  2655. const Expr *Arg = CE->getArg(0);
  2656. return checkFormatStringExpr(S, Arg, Args,
  2657. HasVAListArg, format_idx,
  2658. firstDataArg, Type, CallType,
  2659. InFunctionCall, CheckedVarArgs);
  2660. }
  2661. }
  2662. }
  2663. return SLCT_NotALiteral;
  2664. }
  2665. case Stmt::ObjCStringLiteralClass:
  2666. case Stmt::StringLiteralClass: {
  2667. const StringLiteral *StrE = nullptr;
  2668. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  2669. StrE = ObjCFExpr->getString();
  2670. else
  2671. StrE = cast<StringLiteral>(E);
  2672. if (StrE) {
  2673. S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
  2674. Type, InFunctionCall, CallType, CheckedVarArgs);
  2675. return SLCT_CheckedLiteral;
  2676. }
  2677. return SLCT_NotALiteral;
  2678. }
  2679. default:
  2680. return SLCT_NotALiteral;
  2681. }
  2682. }
  2683. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  2684. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  2685. .Case("scanf", FST_Scanf)
  2686. .Cases("printf", "printf0", FST_Printf)
  2687. .Cases("NSString", "CFString", FST_NSString)
  2688. .Case("strftime", FST_Strftime)
  2689. .Case("strfmon", FST_Strfmon)
  2690. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  2691. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  2692. .Case("os_trace", FST_OSTrace)
  2693. .Default(FST_Unknown);
  2694. }
  2695. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  2696. /// functions) for correct use of format strings.
  2697. /// Returns true if a format string has been fully checked.
  2698. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  2699. ArrayRef<const Expr *> Args,
  2700. bool IsCXXMember,
  2701. VariadicCallType CallType,
  2702. SourceLocation Loc, SourceRange Range,
  2703. llvm::SmallBitVector &CheckedVarArgs) {
  2704. FormatStringInfo FSI;
  2705. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  2706. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  2707. FSI.FirstDataArg, GetFormatStringType(Format),
  2708. CallType, Loc, Range, CheckedVarArgs);
  2709. return false;
  2710. }
  2711. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  2712. bool HasVAListArg, unsigned format_idx,
  2713. unsigned firstDataArg, FormatStringType Type,
  2714. VariadicCallType CallType,
  2715. SourceLocation Loc, SourceRange Range,
  2716. llvm::SmallBitVector &CheckedVarArgs) {
  2717. // CHECK: printf/scanf-like function is called with no format string.
  2718. if (format_idx >= Args.size()) {
  2719. Diag(Loc, diag::warn_missing_format_string) << Range;
  2720. return false;
  2721. }
  2722. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  2723. // CHECK: format string is not a string literal.
  2724. //
  2725. // Dynamically generated format strings are difficult to
  2726. // automatically vet at compile time. Requiring that format strings
  2727. // are string literals: (1) permits the checking of format strings by
  2728. // the compiler and thereby (2) can practically remove the source of
  2729. // many format string exploits.
  2730. // Format string can be either ObjC string (e.g. @"%d") or
  2731. // C string (e.g. "%d")
  2732. // ObjC string uses the same format specifiers as C string, so we can use
  2733. // the same format string checking logic for both ObjC and C strings.
  2734. StringLiteralCheckType CT =
  2735. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  2736. format_idx, firstDataArg, Type, CallType,
  2737. /*IsFunctionCall*/true, CheckedVarArgs);
  2738. if (CT != SLCT_NotALiteral)
  2739. // Literal format string found, check done!
  2740. return CT == SLCT_CheckedLiteral;
  2741. // Strftime is particular as it always uses a single 'time' argument,
  2742. // so it is safe to pass a non-literal string.
  2743. if (Type == FST_Strftime)
  2744. return false;
  2745. // Do not emit diag when the string param is a macro expansion and the
  2746. // format is either NSString or CFString. This is a hack to prevent
  2747. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  2748. // which are usually used in place of NS and CF string literals.
  2749. if (Type == FST_NSString &&
  2750. SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
  2751. return false;
  2752. // If there are no arguments specified, warn with -Wformat-security, otherwise
  2753. // warn only with -Wformat-nonliteral.
  2754. if (Args.size() == firstDataArg)
  2755. Diag(Args[format_idx]->getLocStart(),
  2756. diag::warn_format_nonliteral_noargs)
  2757. << OrigFormatExpr->getSourceRange();
  2758. else
  2759. Diag(Args[format_idx]->getLocStart(),
  2760. diag::warn_format_nonliteral)
  2761. << OrigFormatExpr->getSourceRange();
  2762. return false;
  2763. }
  2764. namespace {
  2765. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  2766. protected:
  2767. Sema &S;
  2768. const StringLiteral *FExpr;
  2769. const Expr *OrigFormatExpr;
  2770. const unsigned FirstDataArg;
  2771. const unsigned NumDataArgs;
  2772. const char *Beg; // Start of format string.
  2773. const bool HasVAListArg;
  2774. ArrayRef<const Expr *> Args;
  2775. unsigned FormatIdx;
  2776. llvm::SmallBitVector CoveredArgs;
  2777. bool usesPositionalArgs;
  2778. bool atFirstArg;
  2779. bool inFunctionCall;
  2780. Sema::VariadicCallType CallType;
  2781. llvm::SmallBitVector &CheckedVarArgs;
  2782. public:
  2783. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  2784. const Expr *origFormatExpr, unsigned firstDataArg,
  2785. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  2786. ArrayRef<const Expr *> Args,
  2787. unsigned formatIdx, bool inFunctionCall,
  2788. Sema::VariadicCallType callType,
  2789. llvm::SmallBitVector &CheckedVarArgs)
  2790. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  2791. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
  2792. Beg(beg), HasVAListArg(hasVAListArg),
  2793. Args(Args), FormatIdx(formatIdx),
  2794. usesPositionalArgs(false), atFirstArg(true),
  2795. inFunctionCall(inFunctionCall), CallType(callType),
  2796. CheckedVarArgs(CheckedVarArgs) {
  2797. CoveredArgs.resize(numDataArgs);
  2798. CoveredArgs.reset();
  2799. }
  2800. void DoneProcessing();
  2801. void HandleIncompleteSpecifier(const char *startSpecifier,
  2802. unsigned specifierLen) override;
  2803. void HandleInvalidLengthModifier(
  2804. const analyze_format_string::FormatSpecifier &FS,
  2805. const analyze_format_string::ConversionSpecifier &CS,
  2806. const char *startSpecifier, unsigned specifierLen,
  2807. unsigned DiagID);
  2808. void HandleNonStandardLengthModifier(
  2809. const analyze_format_string::FormatSpecifier &FS,
  2810. const char *startSpecifier, unsigned specifierLen);
  2811. void HandleNonStandardConversionSpecifier(
  2812. const analyze_format_string::ConversionSpecifier &CS,
  2813. const char *startSpecifier, unsigned specifierLen);
  2814. void HandlePosition(const char *startPos, unsigned posLen) override;
  2815. void HandleInvalidPosition(const char *startSpecifier,
  2816. unsigned specifierLen,
  2817. analyze_format_string::PositionContext p) override;
  2818. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  2819. void HandleNullChar(const char *nullCharacter) override;
  2820. template <typename Range>
  2821. static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
  2822. const Expr *ArgumentExpr,
  2823. PartialDiagnostic PDiag,
  2824. SourceLocation StringLoc,
  2825. bool IsStringLocation, Range StringRange,
  2826. ArrayRef<FixItHint> Fixit = None);
  2827. protected:
  2828. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  2829. const char *startSpec,
  2830. unsigned specifierLen,
  2831. const char *csStart, unsigned csLen);
  2832. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  2833. const char *startSpec,
  2834. unsigned specifierLen);
  2835. SourceRange getFormatStringRange();
  2836. CharSourceRange getSpecifierRange(const char *startSpecifier,
  2837. unsigned specifierLen);
  2838. SourceLocation getLocationOfByte(const char *x);
  2839. const Expr *getDataArg(unsigned i) const;
  2840. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  2841. const analyze_format_string::ConversionSpecifier &CS,
  2842. const char *startSpecifier, unsigned specifierLen,
  2843. unsigned argIndex);
  2844. template <typename Range>
  2845. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  2846. bool IsStringLocation, Range StringRange,
  2847. ArrayRef<FixItHint> Fixit = None);
  2848. };
  2849. }
  2850. SourceRange CheckFormatHandler::getFormatStringRange() {
  2851. return OrigFormatExpr->getSourceRange();
  2852. }
  2853. CharSourceRange CheckFormatHandler::
  2854. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  2855. SourceLocation Start = getLocationOfByte(startSpecifier);
  2856. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  2857. // Advance the end SourceLocation by one due to half-open ranges.
  2858. End = End.getLocWithOffset(1);
  2859. return CharSourceRange::getCharRange(Start, End);
  2860. }
  2861. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  2862. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  2863. }
  2864. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  2865. unsigned specifierLen){
  2866. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  2867. getLocationOfByte(startSpecifier),
  2868. /*IsStringLocation*/true,
  2869. getSpecifierRange(startSpecifier, specifierLen));
  2870. }
  2871. void CheckFormatHandler::HandleInvalidLengthModifier(
  2872. const analyze_format_string::FormatSpecifier &FS,
  2873. const analyze_format_string::ConversionSpecifier &CS,
  2874. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  2875. using namespace analyze_format_string;
  2876. const LengthModifier &LM = FS.getLengthModifier();
  2877. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  2878. // See if we know how to fix this length modifier.
  2879. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  2880. if (FixedLM) {
  2881. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  2882. getLocationOfByte(LM.getStart()),
  2883. /*IsStringLocation*/true,
  2884. getSpecifierRange(startSpecifier, specifierLen));
  2885. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  2886. << FixedLM->toString()
  2887. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  2888. } else {
  2889. FixItHint Hint;
  2890. if (DiagID == diag::warn_format_nonsensical_length)
  2891. Hint = FixItHint::CreateRemoval(LMRange);
  2892. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  2893. getLocationOfByte(LM.getStart()),
  2894. /*IsStringLocation*/true,
  2895. getSpecifierRange(startSpecifier, specifierLen),
  2896. Hint);
  2897. }
  2898. }
  2899. void CheckFormatHandler::HandleNonStandardLengthModifier(
  2900. const analyze_format_string::FormatSpecifier &FS,
  2901. const char *startSpecifier, unsigned specifierLen) {
  2902. using namespace analyze_format_string;
  2903. const LengthModifier &LM = FS.getLengthModifier();
  2904. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  2905. // See if we know how to fix this length modifier.
  2906. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  2907. if (FixedLM) {
  2908. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2909. << LM.toString() << 0,
  2910. getLocationOfByte(LM.getStart()),
  2911. /*IsStringLocation*/true,
  2912. getSpecifierRange(startSpecifier, specifierLen));
  2913. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  2914. << FixedLM->toString()
  2915. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  2916. } else {
  2917. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2918. << LM.toString() << 0,
  2919. getLocationOfByte(LM.getStart()),
  2920. /*IsStringLocation*/true,
  2921. getSpecifierRange(startSpecifier, specifierLen));
  2922. }
  2923. }
  2924. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  2925. const analyze_format_string::ConversionSpecifier &CS,
  2926. const char *startSpecifier, unsigned specifierLen) {
  2927. using namespace analyze_format_string;
  2928. // See if we know how to fix this conversion specifier.
  2929. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  2930. if (FixedCS) {
  2931. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2932. << CS.toString() << /*conversion specifier*/1,
  2933. getLocationOfByte(CS.getStart()),
  2934. /*IsStringLocation*/true,
  2935. getSpecifierRange(startSpecifier, specifierLen));
  2936. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  2937. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  2938. << FixedCS->toString()
  2939. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  2940. } else {
  2941. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2942. << CS.toString() << /*conversion specifier*/1,
  2943. getLocationOfByte(CS.getStart()),
  2944. /*IsStringLocation*/true,
  2945. getSpecifierRange(startSpecifier, specifierLen));
  2946. }
  2947. }
  2948. void CheckFormatHandler::HandlePosition(const char *startPos,
  2949. unsigned posLen) {
  2950. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  2951. getLocationOfByte(startPos),
  2952. /*IsStringLocation*/true,
  2953. getSpecifierRange(startPos, posLen));
  2954. }
  2955. void
  2956. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  2957. analyze_format_string::PositionContext p) {
  2958. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  2959. << (unsigned) p,
  2960. getLocationOfByte(startPos), /*IsStringLocation*/true,
  2961. getSpecifierRange(startPos, posLen));
  2962. }
  2963. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  2964. unsigned posLen) {
  2965. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  2966. getLocationOfByte(startPos),
  2967. /*IsStringLocation*/true,
  2968. getSpecifierRange(startPos, posLen));
  2969. }
  2970. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  2971. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  2972. // The presence of a null character is likely an error.
  2973. EmitFormatDiagnostic(
  2974. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  2975. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  2976. getFormatStringRange());
  2977. }
  2978. }
  2979. // Note that this may return NULL if there was an error parsing or building
  2980. // one of the argument expressions.
  2981. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  2982. return Args[FirstDataArg + i];
  2983. }
  2984. void CheckFormatHandler::DoneProcessing() {
  2985. // Does the number of data arguments exceed the number of
  2986. // format conversions in the format string?
  2987. if (!HasVAListArg) {
  2988. // Find any arguments that weren't covered.
  2989. CoveredArgs.flip();
  2990. signed notCoveredArg = CoveredArgs.find_first();
  2991. if (notCoveredArg >= 0) {
  2992. assert((unsigned)notCoveredArg < NumDataArgs);
  2993. if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
  2994. SourceLocation Loc = E->getLocStart();
  2995. if (!S.getSourceManager().isInSystemMacro(Loc)) {
  2996. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
  2997. Loc, /*IsStringLocation*/false,
  2998. getFormatStringRange());
  2999. }
  3000. }
  3001. }
  3002. }
  3003. }
  3004. bool
  3005. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  3006. SourceLocation Loc,
  3007. const char *startSpec,
  3008. unsigned specifierLen,
  3009. const char *csStart,
  3010. unsigned csLen) {
  3011. bool keepGoing = true;
  3012. if (argIndex < NumDataArgs) {
  3013. // Consider the argument coverered, even though the specifier doesn't
  3014. // make sense.
  3015. CoveredArgs.set(argIndex);
  3016. }
  3017. else {
  3018. // If argIndex exceeds the number of data arguments we
  3019. // don't issue a warning because that is just a cascade of warnings (and
  3020. // they may have intended '%%' anyway). We don't want to continue processing
  3021. // the format string after this point, however, as we will like just get
  3022. // gibberish when trying to match arguments.
  3023. keepGoing = false;
  3024. }
  3025. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
  3026. << StringRef(csStart, csLen),
  3027. Loc, /*IsStringLocation*/true,
  3028. getSpecifierRange(startSpec, specifierLen));
  3029. return keepGoing;
  3030. }
  3031. void
  3032. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  3033. const char *startSpec,
  3034. unsigned specifierLen) {
  3035. EmitFormatDiagnostic(
  3036. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  3037. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  3038. }
  3039. bool
  3040. CheckFormatHandler::CheckNumArgs(
  3041. const analyze_format_string::FormatSpecifier &FS,
  3042. const analyze_format_string::ConversionSpecifier &CS,
  3043. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  3044. if (argIndex >= NumDataArgs) {
  3045. PartialDiagnostic PDiag = FS.usesPositionalArg()
  3046. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  3047. << (argIndex+1) << NumDataArgs)
  3048. : S.PDiag(diag::warn_printf_insufficient_data_args);
  3049. EmitFormatDiagnostic(
  3050. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  3051. getSpecifierRange(startSpecifier, specifierLen));
  3052. return false;
  3053. }
  3054. return true;
  3055. }
  3056. template<typename Range>
  3057. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  3058. SourceLocation Loc,
  3059. bool IsStringLocation,
  3060. Range StringRange,
  3061. ArrayRef<FixItHint> FixIt) {
  3062. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  3063. Loc, IsStringLocation, StringRange, FixIt);
  3064. }
  3065. /// \brief If the format string is not within the funcion call, emit a note
  3066. /// so that the function call and string are in diagnostic messages.
  3067. ///
  3068. /// \param InFunctionCall if true, the format string is within the function
  3069. /// call and only one diagnostic message will be produced. Otherwise, an
  3070. /// extra note will be emitted pointing to location of the format string.
  3071. ///
  3072. /// \param ArgumentExpr the expression that is passed as the format string
  3073. /// argument in the function call. Used for getting locations when two
  3074. /// diagnostics are emitted.
  3075. ///
  3076. /// \param PDiag the callee should already have provided any strings for the
  3077. /// diagnostic message. This function only adds locations and fixits
  3078. /// to diagnostics.
  3079. ///
  3080. /// \param Loc primary location for diagnostic. If two diagnostics are
  3081. /// required, one will be at Loc and a new SourceLocation will be created for
  3082. /// the other one.
  3083. ///
  3084. /// \param IsStringLocation if true, Loc points to the format string should be
  3085. /// used for the note. Otherwise, Loc points to the argument list and will
  3086. /// be used with PDiag.
  3087. ///
  3088. /// \param StringRange some or all of the string to highlight. This is
  3089. /// templated so it can accept either a CharSourceRange or a SourceRange.
  3090. ///
  3091. /// \param FixIt optional fix it hint for the format string.
  3092. template<typename Range>
  3093. void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
  3094. const Expr *ArgumentExpr,
  3095. PartialDiagnostic PDiag,
  3096. SourceLocation Loc,
  3097. bool IsStringLocation,
  3098. Range StringRange,
  3099. ArrayRef<FixItHint> FixIt) {
  3100. if (InFunctionCall) {
  3101. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  3102. D << StringRange;
  3103. D << FixIt;
  3104. } else {
  3105. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  3106. << ArgumentExpr->getSourceRange();
  3107. const Sema::SemaDiagnosticBuilder &Note =
  3108. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  3109. diag::note_format_string_defined);
  3110. Note << StringRange;
  3111. Note << FixIt;
  3112. }
  3113. }
  3114. //===--- CHECK: Printf format string checking ------------------------------===//
  3115. namespace {
  3116. class CheckPrintfHandler : public CheckFormatHandler {
  3117. bool ObjCContext;
  3118. public:
  3119. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  3120. const Expr *origFormatExpr, unsigned firstDataArg,
  3121. unsigned numDataArgs, bool isObjC,
  3122. const char *beg, bool hasVAListArg,
  3123. ArrayRef<const Expr *> Args,
  3124. unsigned formatIdx, bool inFunctionCall,
  3125. Sema::VariadicCallType CallType,
  3126. llvm::SmallBitVector &CheckedVarArgs)
  3127. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  3128. numDataArgs, beg, hasVAListArg, Args,
  3129. formatIdx, inFunctionCall, CallType, CheckedVarArgs),
  3130. ObjCContext(isObjC)
  3131. {}
  3132. bool HandleInvalidPrintfConversionSpecifier(
  3133. const analyze_printf::PrintfSpecifier &FS,
  3134. const char *startSpecifier,
  3135. unsigned specifierLen) override;
  3136. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  3137. const char *startSpecifier,
  3138. unsigned specifierLen) override;
  3139. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  3140. const char *StartSpecifier,
  3141. unsigned SpecifierLen,
  3142. const Expr *E);
  3143. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  3144. const char *startSpecifier, unsigned specifierLen);
  3145. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  3146. const analyze_printf::OptionalAmount &Amt,
  3147. unsigned type,
  3148. const char *startSpecifier, unsigned specifierLen);
  3149. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  3150. const analyze_printf::OptionalFlag &flag,
  3151. const char *startSpecifier, unsigned specifierLen);
  3152. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  3153. const analyze_printf::OptionalFlag &ignoredFlag,
  3154. const analyze_printf::OptionalFlag &flag,
  3155. const char *startSpecifier, unsigned specifierLen);
  3156. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  3157. const Expr *E);
  3158. void HandleEmptyObjCModifierFlag(const char *startFlag,
  3159. unsigned flagLen) override;
  3160. void HandleInvalidObjCModifierFlag(const char *startFlag,
  3161. unsigned flagLen) override;
  3162. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  3163. const char *flagsEnd,
  3164. const char *conversionPosition)
  3165. override;
  3166. };
  3167. }
  3168. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  3169. const analyze_printf::PrintfSpecifier &FS,
  3170. const char *startSpecifier,
  3171. unsigned specifierLen) {
  3172. const analyze_printf::PrintfConversionSpecifier &CS =
  3173. FS.getConversionSpecifier();
  3174. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  3175. getLocationOfByte(CS.getStart()),
  3176. startSpecifier, specifierLen,
  3177. CS.getStart(), CS.getLength());
  3178. }
  3179. bool CheckPrintfHandler::HandleAmount(
  3180. const analyze_format_string::OptionalAmount &Amt,
  3181. unsigned k, const char *startSpecifier,
  3182. unsigned specifierLen) {
  3183. if (Amt.hasDataArgument()) {
  3184. if (!HasVAListArg) {
  3185. unsigned argIndex = Amt.getArgIndex();
  3186. if (argIndex >= NumDataArgs) {
  3187. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  3188. << k,
  3189. getLocationOfByte(Amt.getStart()),
  3190. /*IsStringLocation*/true,
  3191. getSpecifierRange(startSpecifier, specifierLen));
  3192. // Don't do any more checking. We will just emit
  3193. // spurious errors.
  3194. return false;
  3195. }
  3196. // Type check the data argument. It should be an 'int'.
  3197. // Although not in conformance with C99, we also allow the argument to be
  3198. // an 'unsigned int' as that is a reasonably safe case. GCC also
  3199. // doesn't emit a warning for that case.
  3200. CoveredArgs.set(argIndex);
  3201. const Expr *Arg = getDataArg(argIndex);
  3202. if (!Arg)
  3203. return false;
  3204. QualType T = Arg->getType();
  3205. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  3206. assert(AT.isValid());
  3207. if (!AT.matchesType(S.Context, T)) {
  3208. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  3209. << k << AT.getRepresentativeTypeName(S.Context)
  3210. << T << Arg->getSourceRange(),
  3211. getLocationOfByte(Amt.getStart()),
  3212. /*IsStringLocation*/true,
  3213. getSpecifierRange(startSpecifier, specifierLen));
  3214. // Don't do any more checking. We will just emit
  3215. // spurious errors.
  3216. return false;
  3217. }
  3218. }
  3219. }
  3220. return true;
  3221. }
  3222. void CheckPrintfHandler::HandleInvalidAmount(
  3223. const analyze_printf::PrintfSpecifier &FS,
  3224. const analyze_printf::OptionalAmount &Amt,
  3225. unsigned type,
  3226. const char *startSpecifier,
  3227. unsigned specifierLen) {
  3228. const analyze_printf::PrintfConversionSpecifier &CS =
  3229. FS.getConversionSpecifier();
  3230. FixItHint fixit =
  3231. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  3232. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  3233. Amt.getConstantLength()))
  3234. : FixItHint();
  3235. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  3236. << type << CS.toString(),
  3237. getLocationOfByte(Amt.getStart()),
  3238. /*IsStringLocation*/true,
  3239. getSpecifierRange(startSpecifier, specifierLen),
  3240. fixit);
  3241. }
  3242. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  3243. const analyze_printf::OptionalFlag &flag,
  3244. const char *startSpecifier,
  3245. unsigned specifierLen) {
  3246. // Warn about pointless flag with a fixit removal.
  3247. const analyze_printf::PrintfConversionSpecifier &CS =
  3248. FS.getConversionSpecifier();
  3249. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  3250. << flag.toString() << CS.toString(),
  3251. getLocationOfByte(flag.getPosition()),
  3252. /*IsStringLocation*/true,
  3253. getSpecifierRange(startSpecifier, specifierLen),
  3254. FixItHint::CreateRemoval(
  3255. getSpecifierRange(flag.getPosition(), 1)));
  3256. }
  3257. void CheckPrintfHandler::HandleIgnoredFlag(
  3258. const analyze_printf::PrintfSpecifier &FS,
  3259. const analyze_printf::OptionalFlag &ignoredFlag,
  3260. const analyze_printf::OptionalFlag &flag,
  3261. const char *startSpecifier,
  3262. unsigned specifierLen) {
  3263. // Warn about ignored flag with a fixit removal.
  3264. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  3265. << ignoredFlag.toString() << flag.toString(),
  3266. getLocationOfByte(ignoredFlag.getPosition()),
  3267. /*IsStringLocation*/true,
  3268. getSpecifierRange(startSpecifier, specifierLen),
  3269. FixItHint::CreateRemoval(
  3270. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  3271. }
  3272. // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  3273. // bool IsStringLocation, Range StringRange,
  3274. // ArrayRef<FixItHint> Fixit = None);
  3275. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  3276. unsigned flagLen) {
  3277. // Warn about an empty flag.
  3278. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  3279. getLocationOfByte(startFlag),
  3280. /*IsStringLocation*/true,
  3281. getSpecifierRange(startFlag, flagLen));
  3282. }
  3283. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  3284. unsigned flagLen) {
  3285. // Warn about an invalid flag.
  3286. auto Range = getSpecifierRange(startFlag, flagLen);
  3287. StringRef flag(startFlag, flagLen);
  3288. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  3289. getLocationOfByte(startFlag),
  3290. /*IsStringLocation*/true,
  3291. Range, FixItHint::CreateRemoval(Range));
  3292. }
  3293. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  3294. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  3295. // Warn about using '[...]' without a '@' conversion.
  3296. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  3297. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  3298. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  3299. getLocationOfByte(conversionPosition),
  3300. /*IsStringLocation*/true,
  3301. Range, FixItHint::CreateRemoval(Range));
  3302. }
  3303. // Determines if the specified is a C++ class or struct containing
  3304. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  3305. // "c_str()").
  3306. template<typename MemberKind>
  3307. static llvm::SmallPtrSet<MemberKind*, 1>
  3308. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  3309. const RecordType *RT = Ty->getAs<RecordType>();
  3310. llvm::SmallPtrSet<MemberKind*, 1> Results;
  3311. if (!RT)
  3312. return Results;
  3313. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  3314. if (!RD || !RD->getDefinition())
  3315. return Results;
  3316. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  3317. Sema::LookupMemberName);
  3318. R.suppressDiagnostics();
  3319. // We just need to include all members of the right kind turned up by the
  3320. // filter, at this point.
  3321. if (S.LookupQualifiedName(R, RT->getDecl()))
  3322. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  3323. NamedDecl *decl = (*I)->getUnderlyingDecl();
  3324. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  3325. Results.insert(FK);
  3326. }
  3327. return Results;
  3328. }
  3329. /// Check if we could call '.c_str()' on an object.
  3330. ///
  3331. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  3332. /// allow the call, or if it would be ambiguous).
  3333. bool Sema::hasCStrMethod(const Expr *E) {
  3334. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  3335. MethodSet Results =
  3336. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  3337. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  3338. MI != ME; ++MI)
  3339. if ((*MI)->getMinRequiredArguments() == 0)
  3340. return true;
  3341. return false;
  3342. }
  3343. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  3344. // better diagnostic if so. AT is assumed to be valid.
  3345. // Returns true when a c_str() conversion method is found.
  3346. bool CheckPrintfHandler::checkForCStrMembers(
  3347. const analyze_printf::ArgType &AT, const Expr *E) {
  3348. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  3349. MethodSet Results =
  3350. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  3351. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  3352. MI != ME; ++MI) {
  3353. const CXXMethodDecl *Method = *MI;
  3354. if (Method->getMinRequiredArguments() == 0 &&
  3355. AT.matchesType(S.Context, Method->getReturnType())) {
  3356. // FIXME: Suggest parens if the expression needs them.
  3357. SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
  3358. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  3359. << "c_str()"
  3360. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  3361. return true;
  3362. }
  3363. }
  3364. return false;
  3365. }
  3366. bool
  3367. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  3368. &FS,
  3369. const char *startSpecifier,
  3370. unsigned specifierLen) {
  3371. using namespace analyze_format_string;
  3372. using namespace analyze_printf;
  3373. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  3374. if (FS.consumesDataArgument()) {
  3375. if (atFirstArg) {
  3376. atFirstArg = false;
  3377. usesPositionalArgs = FS.usesPositionalArg();
  3378. }
  3379. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  3380. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  3381. startSpecifier, specifierLen);
  3382. return false;
  3383. }
  3384. }
  3385. // First check if the field width, precision, and conversion specifier
  3386. // have matching data arguments.
  3387. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  3388. startSpecifier, specifierLen)) {
  3389. return false;
  3390. }
  3391. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  3392. startSpecifier, specifierLen)) {
  3393. return false;
  3394. }
  3395. if (!CS.consumesDataArgument()) {
  3396. // FIXME: Technically specifying a precision or field width here
  3397. // makes no sense. Worth issuing a warning at some point.
  3398. return true;
  3399. }
  3400. // Consume the argument.
  3401. unsigned argIndex = FS.getArgIndex();
  3402. if (argIndex < NumDataArgs) {
  3403. // The check to see if the argIndex is valid will come later.
  3404. // We set the bit here because we may exit early from this
  3405. // function if we encounter some other error.
  3406. CoveredArgs.set(argIndex);
  3407. }
  3408. // FreeBSD kernel extensions.
  3409. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  3410. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  3411. // We need at least two arguments.
  3412. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  3413. return false;
  3414. // Claim the second argument.
  3415. CoveredArgs.set(argIndex + 1);
  3416. // Type check the first argument (int for %b, pointer for %D)
  3417. const Expr *Ex = getDataArg(argIndex);
  3418. const analyze_printf::ArgType &AT =
  3419. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  3420. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  3421. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  3422. EmitFormatDiagnostic(
  3423. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  3424. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  3425. << false << Ex->getSourceRange(),
  3426. Ex->getLocStart(), /*IsStringLocation*/false,
  3427. getSpecifierRange(startSpecifier, specifierLen));
  3428. // Type check the second argument (char * for both %b and %D)
  3429. Ex = getDataArg(argIndex + 1);
  3430. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  3431. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  3432. EmitFormatDiagnostic(
  3433. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  3434. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  3435. << false << Ex->getSourceRange(),
  3436. Ex->getLocStart(), /*IsStringLocation*/false,
  3437. getSpecifierRange(startSpecifier, specifierLen));
  3438. return true;
  3439. }
  3440. // Check for using an Objective-C specific conversion specifier
  3441. // in a non-ObjC literal.
  3442. if (!ObjCContext && CS.isObjCArg()) {
  3443. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  3444. specifierLen);
  3445. }
  3446. // Check for invalid use of field width
  3447. if (!FS.hasValidFieldWidth()) {
  3448. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  3449. startSpecifier, specifierLen);
  3450. }
  3451. // Check for invalid use of precision
  3452. if (!FS.hasValidPrecision()) {
  3453. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  3454. startSpecifier, specifierLen);
  3455. }
  3456. // Check each flag does not conflict with any other component.
  3457. if (!FS.hasValidThousandsGroupingPrefix())
  3458. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  3459. if (!FS.hasValidLeadingZeros())
  3460. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  3461. if (!FS.hasValidPlusPrefix())
  3462. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  3463. if (!FS.hasValidSpacePrefix())
  3464. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  3465. if (!FS.hasValidAlternativeForm())
  3466. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  3467. if (!FS.hasValidLeftJustified())
  3468. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  3469. // Check that flags are not ignored by another flag
  3470. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  3471. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  3472. startSpecifier, specifierLen);
  3473. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  3474. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  3475. startSpecifier, specifierLen);
  3476. // Check the length modifier is valid with the given conversion specifier.
  3477. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  3478. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3479. diag::warn_format_nonsensical_length);
  3480. else if (!FS.hasStandardLengthModifier())
  3481. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  3482. else if (!FS.hasStandardLengthConversionCombination())
  3483. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3484. diag::warn_format_non_standard_conversion_spec);
  3485. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  3486. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  3487. // The remaining checks depend on the data arguments.
  3488. if (HasVAListArg)
  3489. return true;
  3490. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  3491. return false;
  3492. const Expr *Arg = getDataArg(argIndex);
  3493. if (!Arg)
  3494. return true;
  3495. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  3496. }
  3497. static bool requiresParensToAddCast(const Expr *E) {
  3498. // FIXME: We should have a general way to reason about operator
  3499. // precedence and whether parens are actually needed here.
  3500. // Take care of a few common cases where they aren't.
  3501. const Expr *Inside = E->IgnoreImpCasts();
  3502. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  3503. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  3504. switch (Inside->getStmtClass()) {
  3505. case Stmt::ArraySubscriptExprClass:
  3506. case Stmt::CallExprClass:
  3507. case Stmt::CharacterLiteralClass:
  3508. case Stmt::CXXBoolLiteralExprClass:
  3509. case Stmt::DeclRefExprClass:
  3510. case Stmt::FloatingLiteralClass:
  3511. case Stmt::IntegerLiteralClass:
  3512. case Stmt::MemberExprClass:
  3513. case Stmt::ObjCArrayLiteralClass:
  3514. case Stmt::ObjCBoolLiteralExprClass:
  3515. case Stmt::ObjCBoxedExprClass:
  3516. case Stmt::ObjCDictionaryLiteralClass:
  3517. case Stmt::ObjCEncodeExprClass:
  3518. case Stmt::ObjCIvarRefExprClass:
  3519. case Stmt::ObjCMessageExprClass:
  3520. case Stmt::ObjCPropertyRefExprClass:
  3521. case Stmt::ObjCStringLiteralClass:
  3522. case Stmt::ObjCSubscriptRefExprClass:
  3523. case Stmt::ParenExprClass:
  3524. case Stmt::StringLiteralClass:
  3525. case Stmt::UnaryOperatorClass:
  3526. return false;
  3527. default:
  3528. return true;
  3529. }
  3530. }
  3531. static std::pair<QualType, StringRef>
  3532. shouldNotPrintDirectly(const ASTContext &Context,
  3533. QualType IntendedTy,
  3534. const Expr *E) {
  3535. // Use a 'while' to peel off layers of typedefs.
  3536. QualType TyTy = IntendedTy;
  3537. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  3538. StringRef Name = UserTy->getDecl()->getName();
  3539. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  3540. .Case("NSInteger", Context.LongTy)
  3541. .Case("NSUInteger", Context.UnsignedLongTy)
  3542. .Case("SInt32", Context.IntTy)
  3543. .Case("UInt32", Context.UnsignedIntTy)
  3544. .Default(QualType());
  3545. if (!CastTy.isNull())
  3546. return std::make_pair(CastTy, Name);
  3547. TyTy = UserTy->desugar();
  3548. }
  3549. // Strip parens if necessary.
  3550. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  3551. return shouldNotPrintDirectly(Context,
  3552. PE->getSubExpr()->getType(),
  3553. PE->getSubExpr());
  3554. // If this is a conditional expression, then its result type is constructed
  3555. // via usual arithmetic conversions and thus there might be no necessary
  3556. // typedef sugar there. Recurse to operands to check for NSInteger &
  3557. // Co. usage condition.
  3558. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3559. QualType TrueTy, FalseTy;
  3560. StringRef TrueName, FalseName;
  3561. std::tie(TrueTy, TrueName) =
  3562. shouldNotPrintDirectly(Context,
  3563. CO->getTrueExpr()->getType(),
  3564. CO->getTrueExpr());
  3565. std::tie(FalseTy, FalseName) =
  3566. shouldNotPrintDirectly(Context,
  3567. CO->getFalseExpr()->getType(),
  3568. CO->getFalseExpr());
  3569. if (TrueTy == FalseTy)
  3570. return std::make_pair(TrueTy, TrueName);
  3571. else if (TrueTy.isNull())
  3572. return std::make_pair(FalseTy, FalseName);
  3573. else if (FalseTy.isNull())
  3574. return std::make_pair(TrueTy, TrueName);
  3575. }
  3576. return std::make_pair(QualType(), StringRef());
  3577. }
  3578. bool
  3579. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  3580. const char *StartSpecifier,
  3581. unsigned SpecifierLen,
  3582. const Expr *E) {
  3583. using namespace analyze_format_string;
  3584. using namespace analyze_printf;
  3585. // Now type check the data expression that matches the
  3586. // format specifier.
  3587. const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
  3588. ObjCContext);
  3589. if (!AT.isValid())
  3590. return true;
  3591. QualType ExprTy = E->getType();
  3592. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  3593. ExprTy = TET->getUnderlyingExpr()->getType();
  3594. }
  3595. analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
  3596. if (match == analyze_printf::ArgType::Match) {
  3597. return true;
  3598. }
  3599. // Look through argument promotions for our error message's reported type.
  3600. // This includes the integral and floating promotions, but excludes array
  3601. // and function pointer decay; seeing that an argument intended to be a
  3602. // string has type 'char [6]' is probably more confusing than 'char *'.
  3603. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3604. if (ICE->getCastKind() == CK_IntegralCast ||
  3605. ICE->getCastKind() == CK_FloatingCast) {
  3606. E = ICE->getSubExpr();
  3607. ExprTy = E->getType();
  3608. // Check if we didn't match because of an implicit cast from a 'char'
  3609. // or 'short' to an 'int'. This is done because printf is a varargs
  3610. // function.
  3611. if (ICE->getType() == S.Context.IntTy ||
  3612. ICE->getType() == S.Context.UnsignedIntTy) {
  3613. // All further checking is done on the subexpression.
  3614. if (AT.matchesType(S.Context, ExprTy))
  3615. return true;
  3616. }
  3617. }
  3618. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  3619. // Special case for 'a', which has type 'int' in C.
  3620. // Note, however, that we do /not/ want to treat multibyte constants like
  3621. // 'MooV' as characters! This form is deprecated but still exists.
  3622. if (ExprTy == S.Context.IntTy)
  3623. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  3624. ExprTy = S.Context.CharTy;
  3625. }
  3626. // Look through enums to their underlying type.
  3627. bool IsEnum = false;
  3628. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  3629. ExprTy = EnumTy->getDecl()->getIntegerType();
  3630. IsEnum = true;
  3631. }
  3632. // %C in an Objective-C context prints a unichar, not a wchar_t.
  3633. // If the argument is an integer of some kind, believe the %C and suggest
  3634. // a cast instead of changing the conversion specifier.
  3635. QualType IntendedTy = ExprTy;
  3636. if (ObjCContext &&
  3637. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  3638. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  3639. !ExprTy->isCharType()) {
  3640. // 'unichar' is defined as a typedef of unsigned short, but we should
  3641. // prefer using the typedef if it is visible.
  3642. IntendedTy = S.Context.UnsignedShortTy;
  3643. // While we are here, check if the value is an IntegerLiteral that happens
  3644. // to be within the valid range.
  3645. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  3646. const llvm::APInt &V = IL->getValue();
  3647. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  3648. return true;
  3649. }
  3650. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
  3651. Sema::LookupOrdinaryName);
  3652. if (S.LookupName(Result, S.getCurScope())) {
  3653. NamedDecl *ND = Result.getFoundDecl();
  3654. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  3655. if (TD->getUnderlyingType() == IntendedTy)
  3656. IntendedTy = S.Context.getTypedefType(TD);
  3657. }
  3658. }
  3659. }
  3660. // Special-case some of Darwin's platform-independence types by suggesting
  3661. // casts to primitive types that are known to be large enough.
  3662. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  3663. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  3664. QualType CastTy;
  3665. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  3666. if (!CastTy.isNull()) {
  3667. IntendedTy = CastTy;
  3668. ShouldNotPrintDirectly = true;
  3669. }
  3670. }
  3671. // We may be able to offer a FixItHint if it is a supported type.
  3672. PrintfSpecifier fixedFS = FS;
  3673. bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
  3674. S.Context, ObjCContext);
  3675. if (success) {
  3676. // Get the fix string from the fixed format specifier
  3677. SmallString<16> buf;
  3678. llvm::raw_svector_ostream os(buf);
  3679. fixedFS.toString(os);
  3680. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  3681. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  3682. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  3683. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  3684. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  3685. }
  3686. // In this case, the specifier is wrong and should be changed to match
  3687. // the argument.
  3688. EmitFormatDiagnostic(S.PDiag(diag)
  3689. << AT.getRepresentativeTypeName(S.Context)
  3690. << IntendedTy << IsEnum << E->getSourceRange(),
  3691. E->getLocStart(),
  3692. /*IsStringLocation*/ false, SpecRange,
  3693. FixItHint::CreateReplacement(SpecRange, os.str()));
  3694. } else {
  3695. // The canonical type for formatting this value is different from the
  3696. // actual type of the expression. (This occurs, for example, with Darwin's
  3697. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  3698. // should be printed as 'long' for 64-bit compatibility.)
  3699. // Rather than emitting a normal format/argument mismatch, we want to
  3700. // add a cast to the recommended type (and correct the format string
  3701. // if necessary).
  3702. SmallString<16> CastBuf;
  3703. llvm::raw_svector_ostream CastFix(CastBuf);
  3704. CastFix << "(";
  3705. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  3706. CastFix << ")";
  3707. SmallVector<FixItHint,4> Hints;
  3708. if (!AT.matchesType(S.Context, IntendedTy))
  3709. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  3710. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  3711. // If there's already a cast present, just replace it.
  3712. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  3713. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  3714. } else if (!requiresParensToAddCast(E)) {
  3715. // If the expression has high enough precedence,
  3716. // just write the C-style cast.
  3717. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  3718. CastFix.str()));
  3719. } else {
  3720. // Otherwise, add parens around the expression as well as the cast.
  3721. CastFix << "(";
  3722. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  3723. CastFix.str()));
  3724. SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
  3725. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  3726. }
  3727. if (ShouldNotPrintDirectly) {
  3728. // The expression has a type that should not be printed directly.
  3729. // We extract the name from the typedef because we don't want to show
  3730. // the underlying type in the diagnostic.
  3731. StringRef Name;
  3732. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  3733. Name = TypedefTy->getDecl()->getName();
  3734. else
  3735. Name = CastTyName;
  3736. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  3737. << Name << IntendedTy << IsEnum
  3738. << E->getSourceRange(),
  3739. E->getLocStart(), /*IsStringLocation=*/false,
  3740. SpecRange, Hints);
  3741. } else {
  3742. // In this case, the expression could be printed using a different
  3743. // specifier, but we've decided that the specifier is probably correct
  3744. // and we should cast instead. Just use the normal warning message.
  3745. EmitFormatDiagnostic(
  3746. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  3747. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  3748. << E->getSourceRange(),
  3749. E->getLocStart(), /*IsStringLocation*/false,
  3750. SpecRange, Hints);
  3751. }
  3752. }
  3753. } else {
  3754. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  3755. SpecifierLen);
  3756. // Since the warning for passing non-POD types to variadic functions
  3757. // was deferred until now, we emit a warning for non-POD
  3758. // arguments here.
  3759. switch (S.isValidVarArgType(ExprTy)) {
  3760. case Sema::VAK_Valid:
  3761. case Sema::VAK_ValidInCXX11: {
  3762. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  3763. if (match == analyze_printf::ArgType::NoMatchPedantic) {
  3764. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  3765. }
  3766. EmitFormatDiagnostic(
  3767. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  3768. << IsEnum << CSR << E->getSourceRange(),
  3769. E->getLocStart(), /*IsStringLocation*/ false, CSR);
  3770. break;
  3771. }
  3772. case Sema::VAK_Undefined:
  3773. case Sema::VAK_MSVCUndefined:
  3774. EmitFormatDiagnostic(
  3775. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  3776. << S.getLangOpts().CPlusPlus11
  3777. << ExprTy
  3778. << CallType
  3779. << AT.getRepresentativeTypeName(S.Context)
  3780. << CSR
  3781. << E->getSourceRange(),
  3782. E->getLocStart(), /*IsStringLocation*/false, CSR);
  3783. checkForCStrMembers(AT, E);
  3784. break;
  3785. case Sema::VAK_Invalid:
  3786. if (ExprTy->isObjCObjectType())
  3787. EmitFormatDiagnostic(
  3788. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  3789. << S.getLangOpts().CPlusPlus11
  3790. << ExprTy
  3791. << CallType
  3792. << AT.getRepresentativeTypeName(S.Context)
  3793. << CSR
  3794. << E->getSourceRange(),
  3795. E->getLocStart(), /*IsStringLocation*/false, CSR);
  3796. else
  3797. // FIXME: If this is an initializer list, suggest removing the braces
  3798. // or inserting a cast to the target type.
  3799. S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
  3800. << isa<InitListExpr>(E) << ExprTy << CallType
  3801. << AT.getRepresentativeTypeName(S.Context)
  3802. << E->getSourceRange();
  3803. break;
  3804. }
  3805. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  3806. "format string specifier index out of range");
  3807. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  3808. }
  3809. return true;
  3810. }
  3811. //===--- CHECK: Scanf format string checking ------------------------------===//
  3812. namespace {
  3813. class CheckScanfHandler : public CheckFormatHandler {
  3814. public:
  3815. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  3816. const Expr *origFormatExpr, unsigned firstDataArg,
  3817. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  3818. ArrayRef<const Expr *> Args,
  3819. unsigned formatIdx, bool inFunctionCall,
  3820. Sema::VariadicCallType CallType,
  3821. llvm::SmallBitVector &CheckedVarArgs)
  3822. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  3823. numDataArgs, beg, hasVAListArg,
  3824. Args, formatIdx, inFunctionCall, CallType,
  3825. CheckedVarArgs)
  3826. {}
  3827. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  3828. const char *startSpecifier,
  3829. unsigned specifierLen) override;
  3830. bool HandleInvalidScanfConversionSpecifier(
  3831. const analyze_scanf::ScanfSpecifier &FS,
  3832. const char *startSpecifier,
  3833. unsigned specifierLen) override;
  3834. void HandleIncompleteScanList(const char *start, const char *end) override;
  3835. };
  3836. }
  3837. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  3838. const char *end) {
  3839. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  3840. getLocationOfByte(end), /*IsStringLocation*/true,
  3841. getSpecifierRange(start, end - start));
  3842. }
  3843. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  3844. const analyze_scanf::ScanfSpecifier &FS,
  3845. const char *startSpecifier,
  3846. unsigned specifierLen) {
  3847. const analyze_scanf::ScanfConversionSpecifier &CS =
  3848. FS.getConversionSpecifier();
  3849. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  3850. getLocationOfByte(CS.getStart()),
  3851. startSpecifier, specifierLen,
  3852. CS.getStart(), CS.getLength());
  3853. }
  3854. bool CheckScanfHandler::HandleScanfSpecifier(
  3855. const analyze_scanf::ScanfSpecifier &FS,
  3856. const char *startSpecifier,
  3857. unsigned specifierLen) {
  3858. using namespace analyze_scanf;
  3859. using namespace analyze_format_string;
  3860. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  3861. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  3862. // be used to decide if we are using positional arguments consistently.
  3863. if (FS.consumesDataArgument()) {
  3864. if (atFirstArg) {
  3865. atFirstArg = false;
  3866. usesPositionalArgs = FS.usesPositionalArg();
  3867. }
  3868. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  3869. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  3870. startSpecifier, specifierLen);
  3871. return false;
  3872. }
  3873. }
  3874. // Check if the field with is non-zero.
  3875. const OptionalAmount &Amt = FS.getFieldWidth();
  3876. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  3877. if (Amt.getConstantAmount() == 0) {
  3878. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  3879. Amt.getConstantLength());
  3880. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  3881. getLocationOfByte(Amt.getStart()),
  3882. /*IsStringLocation*/true, R,
  3883. FixItHint::CreateRemoval(R));
  3884. }
  3885. }
  3886. if (!FS.consumesDataArgument()) {
  3887. // FIXME: Technically specifying a precision or field width here
  3888. // makes no sense. Worth issuing a warning at some point.
  3889. return true;
  3890. }
  3891. // Consume the argument.
  3892. unsigned argIndex = FS.getArgIndex();
  3893. if (argIndex < NumDataArgs) {
  3894. // The check to see if the argIndex is valid will come later.
  3895. // We set the bit here because we may exit early from this
  3896. // function if we encounter some other error.
  3897. CoveredArgs.set(argIndex);
  3898. }
  3899. // Check the length modifier is valid with the given conversion specifier.
  3900. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  3901. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3902. diag::warn_format_nonsensical_length);
  3903. else if (!FS.hasStandardLengthModifier())
  3904. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  3905. else if (!FS.hasStandardLengthConversionCombination())
  3906. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3907. diag::warn_format_non_standard_conversion_spec);
  3908. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  3909. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  3910. // The remaining checks depend on the data arguments.
  3911. if (HasVAListArg)
  3912. return true;
  3913. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  3914. return false;
  3915. // Check that the argument type matches the format specifier.
  3916. const Expr *Ex = getDataArg(argIndex);
  3917. if (!Ex)
  3918. return true;
  3919. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  3920. if (!AT.isValid()) {
  3921. return true;
  3922. }
  3923. analyze_format_string::ArgType::MatchKind match =
  3924. AT.matchesType(S.Context, Ex->getType());
  3925. if (match == analyze_format_string::ArgType::Match) {
  3926. return true;
  3927. }
  3928. ScanfSpecifier fixedFS = FS;
  3929. bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  3930. S.getLangOpts(), S.Context);
  3931. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  3932. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  3933. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  3934. }
  3935. if (success) {
  3936. // Get the fix string from the fixed format specifier.
  3937. SmallString<128> buf;
  3938. llvm::raw_svector_ostream os(buf);
  3939. fixedFS.toString(os);
  3940. EmitFormatDiagnostic(
  3941. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
  3942. << Ex->getType() << false << Ex->getSourceRange(),
  3943. Ex->getLocStart(),
  3944. /*IsStringLocation*/ false,
  3945. getSpecifierRange(startSpecifier, specifierLen),
  3946. FixItHint::CreateReplacement(
  3947. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  3948. } else {
  3949. EmitFormatDiagnostic(S.PDiag(diag)
  3950. << AT.getRepresentativeTypeName(S.Context)
  3951. << Ex->getType() << false << Ex->getSourceRange(),
  3952. Ex->getLocStart(),
  3953. /*IsStringLocation*/ false,
  3954. getSpecifierRange(startSpecifier, specifierLen));
  3955. }
  3956. return true;
  3957. }
  3958. void Sema::CheckFormatString(const StringLiteral *FExpr,
  3959. const Expr *OrigFormatExpr,
  3960. ArrayRef<const Expr *> Args,
  3961. bool HasVAListArg, unsigned format_idx,
  3962. unsigned firstDataArg, FormatStringType Type,
  3963. bool inFunctionCall, VariadicCallType CallType,
  3964. llvm::SmallBitVector &CheckedVarArgs) {
  3965. // CHECK: is the format string a wide literal?
  3966. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  3967. CheckFormatHandler::EmitFormatDiagnostic(
  3968. *this, inFunctionCall, Args[format_idx],
  3969. PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  3970. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  3971. return;
  3972. }
  3973. // Str - The format string. NOTE: this is NOT null-terminated!
  3974. StringRef StrRef = FExpr->getString();
  3975. const char *Str = StrRef.data();
  3976. // Account for cases where the string literal is truncated in a declaration.
  3977. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  3978. assert(T && "String literal not of constant array type!");
  3979. size_t TypeSize = T->getSize().getZExtValue();
  3980. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  3981. const unsigned numDataArgs = Args.size() - firstDataArg;
  3982. // Emit a warning if the string literal is truncated and does not contain an
  3983. // embedded null character.
  3984. if (TypeSize <= StrRef.size() &&
  3985. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  3986. CheckFormatHandler::EmitFormatDiagnostic(
  3987. *this, inFunctionCall, Args[format_idx],
  3988. PDiag(diag::warn_printf_format_string_not_null_terminated),
  3989. FExpr->getLocStart(),
  3990. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  3991. return;
  3992. }
  3993. // CHECK: empty format string?
  3994. if (StrLen == 0 && numDataArgs > 0) {
  3995. CheckFormatHandler::EmitFormatDiagnostic(
  3996. *this, inFunctionCall, Args[format_idx],
  3997. PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  3998. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  3999. return;
  4000. }
  4001. if (Type == FST_Printf || Type == FST_NSString ||
  4002. Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
  4003. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  4004. numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
  4005. Str, HasVAListArg, Args, format_idx,
  4006. inFunctionCall, CallType, CheckedVarArgs);
  4007. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  4008. getLangOpts(),
  4009. Context.getTargetInfo(),
  4010. Type == FST_FreeBSDKPrintf))
  4011. H.DoneProcessing();
  4012. } else if (Type == FST_Scanf) {
  4013. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
  4014. Str, HasVAListArg, Args, format_idx,
  4015. inFunctionCall, CallType, CheckedVarArgs);
  4016. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  4017. getLangOpts(),
  4018. Context.getTargetInfo()))
  4019. H.DoneProcessing();
  4020. } // TODO: handle other formats
  4021. }
  4022. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  4023. // Str - The format string. NOTE: this is NOT null-terminated!
  4024. StringRef StrRef = FExpr->getString();
  4025. const char *Str = StrRef.data();
  4026. // Account for cases where the string literal is truncated in a declaration.
  4027. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  4028. assert(T && "String literal not of constant array type!");
  4029. size_t TypeSize = T->getSize().getZExtValue();
  4030. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  4031. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  4032. getLangOpts(),
  4033. Context.getTargetInfo());
  4034. }
  4035. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  4036. // Returns the related absolute value function that is larger, of 0 if one
  4037. // does not exist.
  4038. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  4039. switch (AbsFunction) {
  4040. default:
  4041. return 0;
  4042. case Builtin::BI__builtin_abs:
  4043. return Builtin::BI__builtin_labs;
  4044. case Builtin::BI__builtin_labs:
  4045. return Builtin::BI__builtin_llabs;
  4046. case Builtin::BI__builtin_llabs:
  4047. return 0;
  4048. case Builtin::BI__builtin_fabsf:
  4049. return Builtin::BI__builtin_fabs;
  4050. case Builtin::BI__builtin_fabs:
  4051. return Builtin::BI__builtin_fabsl;
  4052. case Builtin::BI__builtin_fabsl:
  4053. return 0;
  4054. case Builtin::BI__builtin_cabsf:
  4055. return Builtin::BI__builtin_cabs;
  4056. case Builtin::BI__builtin_cabs:
  4057. return Builtin::BI__builtin_cabsl;
  4058. case Builtin::BI__builtin_cabsl:
  4059. return 0;
  4060. case Builtin::BIabs:
  4061. return Builtin::BIlabs;
  4062. case Builtin::BIlabs:
  4063. return Builtin::BIllabs;
  4064. case Builtin::BIllabs:
  4065. return 0;
  4066. case Builtin::BIfabsf:
  4067. return Builtin::BIfabs;
  4068. case Builtin::BIfabs:
  4069. return Builtin::BIfabsl;
  4070. case Builtin::BIfabsl:
  4071. return 0;
  4072. case Builtin::BIcabsf:
  4073. return Builtin::BIcabs;
  4074. case Builtin::BIcabs:
  4075. return Builtin::BIcabsl;
  4076. case Builtin::BIcabsl:
  4077. return 0;
  4078. }
  4079. }
  4080. // Returns the argument type of the absolute value function.
  4081. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  4082. unsigned AbsType) {
  4083. if (AbsType == 0)
  4084. return QualType();
  4085. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  4086. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  4087. if (Error != ASTContext::GE_None)
  4088. return QualType();
  4089. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  4090. if (!FT)
  4091. return QualType();
  4092. if (FT->getNumParams() != 1)
  4093. return QualType();
  4094. return FT->getParamType(0);
  4095. }
  4096. // Returns the best absolute value function, or zero, based on type and
  4097. // current absolute value function.
  4098. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  4099. unsigned AbsFunctionKind) {
  4100. unsigned BestKind = 0;
  4101. uint64_t ArgSize = Context.getTypeSize(ArgType);
  4102. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  4103. Kind = getLargerAbsoluteValueFunction(Kind)) {
  4104. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  4105. if (Context.getTypeSize(ParamType) >= ArgSize) {
  4106. if (BestKind == 0)
  4107. BestKind = Kind;
  4108. else if (Context.hasSameType(ParamType, ArgType)) {
  4109. BestKind = Kind;
  4110. break;
  4111. }
  4112. }
  4113. }
  4114. return BestKind;
  4115. }
  4116. enum AbsoluteValueKind {
  4117. AVK_Integer,
  4118. AVK_Floating,
  4119. AVK_Complex
  4120. };
  4121. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  4122. if (T->isIntegralOrEnumerationType())
  4123. return AVK_Integer;
  4124. if (T->isRealFloatingType())
  4125. return AVK_Floating;
  4126. if (T->isAnyComplexType())
  4127. return AVK_Complex;
  4128. llvm_unreachable("Type not integer, floating, or complex");
  4129. }
  4130. // Changes the absolute value function to a different type. Preserves whether
  4131. // the function is a builtin.
  4132. static unsigned changeAbsFunction(unsigned AbsKind,
  4133. AbsoluteValueKind ValueKind) {
  4134. switch (ValueKind) {
  4135. case AVK_Integer:
  4136. switch (AbsKind) {
  4137. default:
  4138. return 0;
  4139. case Builtin::BI__builtin_fabsf:
  4140. case Builtin::BI__builtin_fabs:
  4141. case Builtin::BI__builtin_fabsl:
  4142. case Builtin::BI__builtin_cabsf:
  4143. case Builtin::BI__builtin_cabs:
  4144. case Builtin::BI__builtin_cabsl:
  4145. return Builtin::BI__builtin_abs;
  4146. case Builtin::BIfabsf:
  4147. case Builtin::BIfabs:
  4148. case Builtin::BIfabsl:
  4149. case Builtin::BIcabsf:
  4150. case Builtin::BIcabs:
  4151. case Builtin::BIcabsl:
  4152. return Builtin::BIabs;
  4153. }
  4154. case AVK_Floating:
  4155. switch (AbsKind) {
  4156. default:
  4157. return 0;
  4158. case Builtin::BI__builtin_abs:
  4159. case Builtin::BI__builtin_labs:
  4160. case Builtin::BI__builtin_llabs:
  4161. case Builtin::BI__builtin_cabsf:
  4162. case Builtin::BI__builtin_cabs:
  4163. case Builtin::BI__builtin_cabsl:
  4164. return Builtin::BI__builtin_fabsf;
  4165. case Builtin::BIabs:
  4166. case Builtin::BIlabs:
  4167. case Builtin::BIllabs:
  4168. case Builtin::BIcabsf:
  4169. case Builtin::BIcabs:
  4170. case Builtin::BIcabsl:
  4171. return Builtin::BIfabsf;
  4172. }
  4173. case AVK_Complex:
  4174. switch (AbsKind) {
  4175. default:
  4176. return 0;
  4177. case Builtin::BI__builtin_abs:
  4178. case Builtin::BI__builtin_labs:
  4179. case Builtin::BI__builtin_llabs:
  4180. case Builtin::BI__builtin_fabsf:
  4181. case Builtin::BI__builtin_fabs:
  4182. case Builtin::BI__builtin_fabsl:
  4183. return Builtin::BI__builtin_cabsf;
  4184. case Builtin::BIabs:
  4185. case Builtin::BIlabs:
  4186. case Builtin::BIllabs:
  4187. case Builtin::BIfabsf:
  4188. case Builtin::BIfabs:
  4189. case Builtin::BIfabsl:
  4190. return Builtin::BIcabsf;
  4191. }
  4192. }
  4193. llvm_unreachable("Unable to convert function");
  4194. }
  4195. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  4196. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4197. if (!FnInfo)
  4198. return 0;
  4199. switch (FDecl->getBuiltinID()) {
  4200. default:
  4201. return 0;
  4202. case Builtin::BI__builtin_abs:
  4203. case Builtin::BI__builtin_fabs:
  4204. case Builtin::BI__builtin_fabsf:
  4205. case Builtin::BI__builtin_fabsl:
  4206. case Builtin::BI__builtin_labs:
  4207. case Builtin::BI__builtin_llabs:
  4208. case Builtin::BI__builtin_cabs:
  4209. case Builtin::BI__builtin_cabsf:
  4210. case Builtin::BI__builtin_cabsl:
  4211. case Builtin::BIabs:
  4212. case Builtin::BIlabs:
  4213. case Builtin::BIllabs:
  4214. case Builtin::BIfabs:
  4215. case Builtin::BIfabsf:
  4216. case Builtin::BIfabsl:
  4217. case Builtin::BIcabs:
  4218. case Builtin::BIcabsf:
  4219. case Builtin::BIcabsl:
  4220. return FDecl->getBuiltinID();
  4221. }
  4222. llvm_unreachable("Unknown Builtin type");
  4223. }
  4224. // If the replacement is valid, emit a note with replacement function.
  4225. // Additionally, suggest including the proper header if not already included.
  4226. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  4227. unsigned AbsKind, QualType ArgType) {
  4228. bool EmitHeaderHint = true;
  4229. const char *HeaderName = nullptr;
  4230. const char *FunctionName = nullptr;
  4231. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  4232. FunctionName = "std::abs";
  4233. if (ArgType->isIntegralOrEnumerationType()) {
  4234. HeaderName = "cstdlib";
  4235. } else if (ArgType->isRealFloatingType()) {
  4236. HeaderName = "cmath";
  4237. } else {
  4238. llvm_unreachable("Invalid Type");
  4239. }
  4240. // Lookup all std::abs
  4241. if (NamespaceDecl *Std = S.getStdNamespace()) {
  4242. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  4243. R.suppressDiagnostics();
  4244. S.LookupQualifiedName(R, Std);
  4245. for (const auto *I : R) {
  4246. const FunctionDecl *FDecl = nullptr;
  4247. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  4248. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  4249. } else {
  4250. FDecl = dyn_cast<FunctionDecl>(I);
  4251. }
  4252. if (!FDecl)
  4253. continue;
  4254. // Found std::abs(), check that they are the right ones.
  4255. if (FDecl->getNumParams() != 1)
  4256. continue;
  4257. // Check that the parameter type can handle the argument.
  4258. QualType ParamType = FDecl->getParamDecl(0)->getType();
  4259. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  4260. S.Context.getTypeSize(ArgType) <=
  4261. S.Context.getTypeSize(ParamType)) {
  4262. // Found a function, don't need the header hint.
  4263. EmitHeaderHint = false;
  4264. break;
  4265. }
  4266. }
  4267. }
  4268. } else {
  4269. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  4270. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  4271. if (HeaderName) {
  4272. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  4273. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  4274. R.suppressDiagnostics();
  4275. S.LookupName(R, S.getCurScope());
  4276. if (R.isSingleResult()) {
  4277. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  4278. if (FD && FD->getBuiltinID() == AbsKind) {
  4279. EmitHeaderHint = false;
  4280. } else {
  4281. return;
  4282. }
  4283. } else if (!R.empty()) {
  4284. return;
  4285. }
  4286. }
  4287. }
  4288. S.Diag(Loc, diag::note_replace_abs_function)
  4289. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  4290. if (!HeaderName)
  4291. return;
  4292. if (!EmitHeaderHint)
  4293. return;
  4294. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  4295. << FunctionName;
  4296. }
  4297. static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
  4298. if (!FDecl)
  4299. return false;
  4300. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
  4301. return false;
  4302. const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
  4303. while (ND && ND->isInlineNamespace()) {
  4304. ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
  4305. }
  4306. if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
  4307. return false;
  4308. if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
  4309. return false;
  4310. return true;
  4311. }
  4312. // Warn when using the wrong abs() function.
  4313. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  4314. const FunctionDecl *FDecl,
  4315. IdentifierInfo *FnInfo) {
  4316. if (Call->getNumArgs() != 1)
  4317. return;
  4318. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  4319. bool IsStdAbs = IsFunctionStdAbs(FDecl);
  4320. if (AbsKind == 0 && !IsStdAbs)
  4321. return;
  4322. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  4323. QualType ParamType = Call->getArg(0)->getType();
  4324. // Unsigned types cannot be negative. Suggest removing the absolute value
  4325. // function call.
  4326. if (ArgType->isUnsignedIntegerType()) {
  4327. const char *FunctionName =
  4328. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  4329. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  4330. Diag(Call->getExprLoc(), diag::note_remove_abs)
  4331. << FunctionName
  4332. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  4333. return;
  4334. }
  4335. // std::abs has overloads which prevent most of the absolute value problems
  4336. // from occurring.
  4337. if (IsStdAbs)
  4338. return;
  4339. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  4340. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  4341. // The argument and parameter are the same kind. Check if they are the right
  4342. // size.
  4343. if (ArgValueKind == ParamValueKind) {
  4344. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  4345. return;
  4346. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  4347. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  4348. << FDecl << ArgType << ParamType;
  4349. if (NewAbsKind == 0)
  4350. return;
  4351. emitReplacement(*this, Call->getExprLoc(),
  4352. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  4353. return;
  4354. }
  4355. // ArgValueKind != ParamValueKind
  4356. // The wrong type of absolute value function was used. Attempt to find the
  4357. // proper one.
  4358. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  4359. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  4360. if (NewAbsKind == 0)
  4361. return;
  4362. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  4363. << FDecl << ParamValueKind << ArgValueKind;
  4364. emitReplacement(*this, Call->getExprLoc(),
  4365. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  4366. return;
  4367. }
  4368. //===--- CHECK: Standard memory functions ---------------------------------===//
  4369. /// \brief Takes the expression passed to the size_t parameter of functions
  4370. /// such as memcmp, strncat, etc and warns if it's a comparison.
  4371. ///
  4372. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  4373. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  4374. IdentifierInfo *FnName,
  4375. SourceLocation FnLoc,
  4376. SourceLocation RParenLoc) {
  4377. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  4378. if (!Size)
  4379. return false;
  4380. // if E is binop and op is >, <, >=, <=, ==, &&, ||:
  4381. if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
  4382. return false;
  4383. SourceRange SizeRange = Size->getSourceRange();
  4384. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  4385. << SizeRange << FnName;
  4386. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  4387. << FnName << FixItHint::CreateInsertion(
  4388. S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
  4389. << FixItHint::CreateRemoval(RParenLoc);
  4390. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  4391. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  4392. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  4393. ")");
  4394. return true;
  4395. }
  4396. /// \brief Determine whether the given type is or contains a dynamic class type
  4397. /// (e.g., whether it has a vtable).
  4398. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  4399. bool &IsContained) {
  4400. // Look through array types while ignoring qualifiers.
  4401. const Type *Ty = T->getBaseElementTypeUnsafe();
  4402. IsContained = false;
  4403. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  4404. RD = RD ? RD->getDefinition() : nullptr;
  4405. if (!RD)
  4406. return nullptr;
  4407. if (RD->isDynamicClass())
  4408. return RD;
  4409. // Check all the fields. If any bases were dynamic, the class is dynamic.
  4410. // It's impossible for a class to transitively contain itself by value, so
  4411. // infinite recursion is impossible.
  4412. for (auto *FD : RD->fields()) {
  4413. bool SubContained;
  4414. if (const CXXRecordDecl *ContainedRD =
  4415. getContainedDynamicClass(FD->getType(), SubContained)) {
  4416. IsContained = true;
  4417. return ContainedRD;
  4418. }
  4419. }
  4420. return nullptr;
  4421. }
  4422. /// \brief If E is a sizeof expression, returns its argument expression,
  4423. /// otherwise returns NULL.
  4424. static const Expr *getSizeOfExprArg(const Expr *E) {
  4425. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  4426. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  4427. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  4428. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  4429. return nullptr;
  4430. }
  4431. /// \brief If E is a sizeof expression, returns its argument type.
  4432. static QualType getSizeOfArgType(const Expr *E) {
  4433. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  4434. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  4435. if (SizeOf->getKind() == clang::UETT_SizeOf)
  4436. return SizeOf->getTypeOfArgument();
  4437. return QualType();
  4438. }
  4439. /// \brief Check for dangerous or invalid arguments to memset().
  4440. ///
  4441. /// This issues warnings on known problematic, dangerous or unspecified
  4442. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  4443. /// function calls.
  4444. ///
  4445. /// \param Call The call expression to diagnose.
  4446. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  4447. unsigned BId,
  4448. IdentifierInfo *FnName) {
  4449. assert(BId != 0);
  4450. // It is possible to have a non-standard definition of memset. Validate
  4451. // we have enough arguments, and if not, abort further checking.
  4452. unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
  4453. if (Call->getNumArgs() < ExpectedNumArgs)
  4454. return;
  4455. unsigned LastArg = (BId == Builtin::BImemset ||
  4456. BId == Builtin::BIstrndup ? 1 : 2);
  4457. unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
  4458. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  4459. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  4460. Call->getLocStart(), Call->getRParenLoc()))
  4461. return;
  4462. // We have special checking when the length is a sizeof expression.
  4463. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  4464. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  4465. llvm::FoldingSetNodeID SizeOfArgID;
  4466. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  4467. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  4468. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  4469. QualType DestTy = Dest->getType();
  4470. QualType PointeeTy;
  4471. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  4472. PointeeTy = DestPtrTy->getPointeeType();
  4473. // Never warn about void type pointers. This can be used to suppress
  4474. // false positives.
  4475. if (PointeeTy->isVoidType())
  4476. continue;
  4477. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  4478. // actually comparing the expressions for equality. Because computing the
  4479. // expression IDs can be expensive, we only do this if the diagnostic is
  4480. // enabled.
  4481. if (SizeOfArg &&
  4482. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  4483. SizeOfArg->getExprLoc())) {
  4484. // We only compute IDs for expressions if the warning is enabled, and
  4485. // cache the sizeof arg's ID.
  4486. if (SizeOfArgID == llvm::FoldingSetNodeID())
  4487. SizeOfArg->Profile(SizeOfArgID, Context, true);
  4488. llvm::FoldingSetNodeID DestID;
  4489. Dest->Profile(DestID, Context, true);
  4490. if (DestID == SizeOfArgID) {
  4491. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  4492. // over sizeof(src) as well.
  4493. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  4494. StringRef ReadableName = FnName->getName();
  4495. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  4496. if (UnaryOp->getOpcode() == UO_AddrOf)
  4497. ActionIdx = 1; // If its an address-of operator, just remove it.
  4498. if (!PointeeTy->isIncompleteType() &&
  4499. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  4500. ActionIdx = 2; // If the pointee's size is sizeof(char),
  4501. // suggest an explicit length.
  4502. // If the function is defined as a builtin macro, do not show macro
  4503. // expansion.
  4504. SourceLocation SL = SizeOfArg->getExprLoc();
  4505. SourceRange DSR = Dest->getSourceRange();
  4506. SourceRange SSR = SizeOfArg->getSourceRange();
  4507. SourceManager &SM = getSourceManager();
  4508. if (SM.isMacroArgExpansion(SL)) {
  4509. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  4510. SL = SM.getSpellingLoc(SL);
  4511. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  4512. SM.getSpellingLoc(DSR.getEnd()));
  4513. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  4514. SM.getSpellingLoc(SSR.getEnd()));
  4515. }
  4516. DiagRuntimeBehavior(SL, SizeOfArg,
  4517. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  4518. << ReadableName
  4519. << PointeeTy
  4520. << DestTy
  4521. << DSR
  4522. << SSR);
  4523. DiagRuntimeBehavior(SL, SizeOfArg,
  4524. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  4525. << ActionIdx
  4526. << SSR);
  4527. break;
  4528. }
  4529. }
  4530. // Also check for cases where the sizeof argument is the exact same
  4531. // type as the memory argument, and where it points to a user-defined
  4532. // record type.
  4533. if (SizeOfArgTy != QualType()) {
  4534. if (PointeeTy->isRecordType() &&
  4535. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  4536. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  4537. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  4538. << FnName << SizeOfArgTy << ArgIdx
  4539. << PointeeTy << Dest->getSourceRange()
  4540. << LenExpr->getSourceRange());
  4541. break;
  4542. }
  4543. }
  4544. } else if (DestTy->isArrayType()) {
  4545. PointeeTy = DestTy;
  4546. }
  4547. if (PointeeTy == QualType())
  4548. continue;
  4549. // Always complain about dynamic classes.
  4550. bool IsContained;
  4551. if (const CXXRecordDecl *ContainedRD =
  4552. getContainedDynamicClass(PointeeTy, IsContained)) {
  4553. unsigned OperationType = 0;
  4554. // "overwritten" if we're warning about the destination for any call
  4555. // but memcmp; otherwise a verb appropriate to the call.
  4556. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  4557. if (BId == Builtin::BImemcpy)
  4558. OperationType = 1;
  4559. else if(BId == Builtin::BImemmove)
  4560. OperationType = 2;
  4561. else if (BId == Builtin::BImemcmp)
  4562. OperationType = 3;
  4563. }
  4564. DiagRuntimeBehavior(
  4565. Dest->getExprLoc(), Dest,
  4566. PDiag(diag::warn_dyn_class_memaccess)
  4567. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  4568. << FnName << IsContained << ContainedRD << OperationType
  4569. << Call->getCallee()->getSourceRange());
  4570. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  4571. BId != Builtin::BImemset)
  4572. DiagRuntimeBehavior(
  4573. Dest->getExprLoc(), Dest,
  4574. PDiag(diag::warn_arc_object_memaccess)
  4575. << ArgIdx << FnName << PointeeTy
  4576. << Call->getCallee()->getSourceRange());
  4577. else
  4578. continue;
  4579. DiagRuntimeBehavior(
  4580. Dest->getExprLoc(), Dest,
  4581. PDiag(diag::note_bad_memaccess_silence)
  4582. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  4583. break;
  4584. }
  4585. }
  4586. // A little helper routine: ignore addition and subtraction of integer literals.
  4587. // This intentionally does not ignore all integer constant expressions because
  4588. // we don't want to remove sizeof().
  4589. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  4590. Ex = Ex->IgnoreParenCasts();
  4591. for (;;) {
  4592. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  4593. if (!BO || !BO->isAdditiveOp())
  4594. break;
  4595. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  4596. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  4597. if (isa<IntegerLiteral>(RHS))
  4598. Ex = LHS;
  4599. else if (isa<IntegerLiteral>(LHS))
  4600. Ex = RHS;
  4601. else
  4602. break;
  4603. }
  4604. return Ex;
  4605. }
  4606. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  4607. ASTContext &Context) {
  4608. // Only handle constant-sized or VLAs, but not flexible members.
  4609. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  4610. // Only issue the FIXIT for arrays of size > 1.
  4611. if (CAT->getSize().getSExtValue() <= 1)
  4612. return false;
  4613. } else if (!Ty->isVariableArrayType()) {
  4614. return false;
  4615. }
  4616. return true;
  4617. }
  4618. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  4619. // be the size of the source, instead of the destination.
  4620. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  4621. IdentifierInfo *FnName) {
  4622. // Don't crash if the user has the wrong number of arguments
  4623. unsigned NumArgs = Call->getNumArgs();
  4624. if ((NumArgs != 3) && (NumArgs != 4))
  4625. return;
  4626. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  4627. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  4628. const Expr *CompareWithSrc = nullptr;
  4629. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  4630. Call->getLocStart(), Call->getRParenLoc()))
  4631. return;
  4632. // Look for 'strlcpy(dst, x, sizeof(x))'
  4633. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  4634. CompareWithSrc = Ex;
  4635. else {
  4636. // Look for 'strlcpy(dst, x, strlen(x))'
  4637. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  4638. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  4639. SizeCall->getNumArgs() == 1)
  4640. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  4641. }
  4642. }
  4643. if (!CompareWithSrc)
  4644. return;
  4645. // Determine if the argument to sizeof/strlen is equal to the source
  4646. // argument. In principle there's all kinds of things you could do
  4647. // here, for instance creating an == expression and evaluating it with
  4648. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  4649. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  4650. if (!SrcArgDRE)
  4651. return;
  4652. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  4653. if (!CompareWithSrcDRE ||
  4654. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  4655. return;
  4656. const Expr *OriginalSizeArg = Call->getArg(2);
  4657. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  4658. << OriginalSizeArg->getSourceRange() << FnName;
  4659. // Output a FIXIT hint if the destination is an array (rather than a
  4660. // pointer to an array). This could be enhanced to handle some
  4661. // pointers if we know the actual size, like if DstArg is 'array+2'
  4662. // we could say 'sizeof(array)-2'.
  4663. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  4664. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  4665. return;
  4666. SmallString<128> sizeString;
  4667. llvm::raw_svector_ostream OS(sizeString);
  4668. OS << "sizeof(";
  4669. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  4670. OS << ")";
  4671. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  4672. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  4673. OS.str());
  4674. }
  4675. /// Check if two expressions refer to the same declaration.
  4676. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  4677. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  4678. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  4679. return D1->getDecl() == D2->getDecl();
  4680. return false;
  4681. }
  4682. static const Expr *getStrlenExprArg(const Expr *E) {
  4683. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  4684. const FunctionDecl *FD = CE->getDirectCallee();
  4685. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  4686. return nullptr;
  4687. return CE->getArg(0)->IgnoreParenCasts();
  4688. }
  4689. return nullptr;
  4690. }
  4691. // Warn on anti-patterns as the 'size' argument to strncat.
  4692. // The correct size argument should look like following:
  4693. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  4694. void Sema::CheckStrncatArguments(const CallExpr *CE,
  4695. IdentifierInfo *FnName) {
  4696. // Don't crash if the user has the wrong number of arguments.
  4697. if (CE->getNumArgs() < 3)
  4698. return;
  4699. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  4700. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  4701. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  4702. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
  4703. CE->getRParenLoc()))
  4704. return;
  4705. // Identify common expressions, which are wrongly used as the size argument
  4706. // to strncat and may lead to buffer overflows.
  4707. unsigned PatternType = 0;
  4708. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  4709. // - sizeof(dst)
  4710. if (referToTheSameDecl(SizeOfArg, DstArg))
  4711. PatternType = 1;
  4712. // - sizeof(src)
  4713. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  4714. PatternType = 2;
  4715. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  4716. if (BE->getOpcode() == BO_Sub) {
  4717. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  4718. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  4719. // - sizeof(dst) - strlen(dst)
  4720. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  4721. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  4722. PatternType = 1;
  4723. // - sizeof(src) - (anything)
  4724. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  4725. PatternType = 2;
  4726. }
  4727. }
  4728. if (PatternType == 0)
  4729. return;
  4730. // Generate the diagnostic.
  4731. SourceLocation SL = LenArg->getLocStart();
  4732. SourceRange SR = LenArg->getSourceRange();
  4733. SourceManager &SM = getSourceManager();
  4734. // If the function is defined as a builtin macro, do not show macro expansion.
  4735. if (SM.isMacroArgExpansion(SL)) {
  4736. SL = SM.getSpellingLoc(SL);
  4737. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  4738. SM.getSpellingLoc(SR.getEnd()));
  4739. }
  4740. // Check if the destination is an array (rather than a pointer to an array).
  4741. QualType DstTy = DstArg->getType();
  4742. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  4743. Context);
  4744. if (!isKnownSizeArray) {
  4745. if (PatternType == 1)
  4746. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  4747. else
  4748. Diag(SL, diag::warn_strncat_src_size) << SR;
  4749. return;
  4750. }
  4751. if (PatternType == 1)
  4752. Diag(SL, diag::warn_strncat_large_size) << SR;
  4753. else
  4754. Diag(SL, diag::warn_strncat_src_size) << SR;
  4755. SmallString<128> sizeString;
  4756. llvm::raw_svector_ostream OS(sizeString);
  4757. OS << "sizeof(";
  4758. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  4759. OS << ") - ";
  4760. OS << "strlen(";
  4761. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  4762. OS << ") - 1";
  4763. Diag(SL, diag::note_strncat_wrong_size)
  4764. << FixItHint::CreateReplacement(SR, OS.str());
  4765. }
  4766. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  4767. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4768. Decl *ParentDecl);
  4769. static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4770. Decl *ParentDecl);
  4771. /// CheckReturnStackAddr - Check if a return statement returns the address
  4772. /// of a stack variable.
  4773. static void
  4774. CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
  4775. SourceLocation ReturnLoc) {
  4776. Expr *stackE = nullptr;
  4777. SmallVector<DeclRefExpr *, 8> refVars;
  4778. // Perform checking for returned stack addresses, local blocks,
  4779. // label addresses or references to temporaries.
  4780. if (lhsType->isPointerType() ||
  4781. (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  4782. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
  4783. } else if (lhsType->isReferenceType()) {
  4784. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
  4785. }
  4786. if (!stackE)
  4787. return; // Nothing suspicious was found.
  4788. SourceLocation diagLoc;
  4789. SourceRange diagRange;
  4790. if (refVars.empty()) {
  4791. diagLoc = stackE->getLocStart();
  4792. diagRange = stackE->getSourceRange();
  4793. } else {
  4794. // We followed through a reference variable. 'stackE' contains the
  4795. // problematic expression but we will warn at the return statement pointing
  4796. // at the reference variable. We will later display the "trail" of
  4797. // reference variables using notes.
  4798. diagLoc = refVars[0]->getLocStart();
  4799. diagRange = refVars[0]->getSourceRange();
  4800. }
  4801. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  4802. S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  4803. : diag::warn_ret_stack_addr)
  4804. << DR->getDecl()->getDeclName() << diagRange;
  4805. } else if (isa<BlockExpr>(stackE)) { // local block.
  4806. S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  4807. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  4808. S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  4809. } else { // local temporary.
  4810. S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  4811. : diag::warn_ret_local_temp_addr)
  4812. << diagRange;
  4813. }
  4814. // Display the "trail" of reference variables that we followed until we
  4815. // found the problematic expression using notes.
  4816. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  4817. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  4818. // If this var binds to another reference var, show the range of the next
  4819. // var, otherwise the var binds to the problematic expression, in which case
  4820. // show the range of the expression.
  4821. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  4822. : stackE->getSourceRange();
  4823. S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  4824. << VD->getDeclName() << range;
  4825. }
  4826. }
  4827. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  4828. /// check if the expression in a return statement evaluates to an address
  4829. /// to a location on the stack, a local block, an address of a label, or a
  4830. /// reference to local temporary. The recursion is used to traverse the
  4831. /// AST of the return expression, with recursion backtracking when we
  4832. /// encounter a subexpression that (1) clearly does not lead to one of the
  4833. /// above problematic expressions (2) is something we cannot determine leads to
  4834. /// a problematic expression based on such local checking.
  4835. ///
  4836. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  4837. /// the expression that they point to. Such variables are added to the
  4838. /// 'refVars' vector so that we know what the reference variable "trail" was.
  4839. ///
  4840. /// EvalAddr processes expressions that are pointers that are used as
  4841. /// references (and not L-values). EvalVal handles all other values.
  4842. /// At the base case of the recursion is a check for the above problematic
  4843. /// expressions.
  4844. ///
  4845. /// This implementation handles:
  4846. ///
  4847. /// * pointer-to-pointer casts
  4848. /// * implicit conversions from array references to pointers
  4849. /// * taking the address of fields
  4850. /// * arbitrary interplay between "&" and "*" operators
  4851. /// * pointer arithmetic from an address of a stack variable
  4852. /// * taking the address of an array element where the array is on the stack
  4853. static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4854. Decl *ParentDecl) {
  4855. if (E->isTypeDependent())
  4856. return nullptr;
  4857. // We should only be called for evaluating pointer expressions.
  4858. assert((E->getType()->isAnyPointerType() ||
  4859. E->getType()->isBlockPointerType() ||
  4860. E->getType()->isObjCQualifiedIdType()) &&
  4861. "EvalAddr only works on pointers");
  4862. E = E->IgnoreParens();
  4863. // Our "symbolic interpreter" is just a dispatch off the currently
  4864. // viewed AST node. We then recursively traverse the AST by calling
  4865. // EvalAddr and EvalVal appropriately.
  4866. switch (E->getStmtClass()) {
  4867. case Stmt::DeclRefExprClass: {
  4868. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  4869. // If we leave the immediate function, the lifetime isn't about to end.
  4870. if (DR->refersToEnclosingVariableOrCapture())
  4871. return nullptr;
  4872. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  4873. // If this is a reference variable, follow through to the expression that
  4874. // it points to.
  4875. if (V->hasLocalStorage() &&
  4876. V->getType()->isReferenceType() && V->hasInit()) {
  4877. // Add the reference variable to the "trail".
  4878. refVars.push_back(DR);
  4879. return EvalAddr(V->getInit(), refVars, ParentDecl);
  4880. }
  4881. return nullptr;
  4882. }
  4883. case Stmt::UnaryOperatorClass: {
  4884. // The only unary operator that make sense to handle here
  4885. // is AddrOf. All others don't make sense as pointers.
  4886. UnaryOperator *U = cast<UnaryOperator>(E);
  4887. if (U->getOpcode() == UO_AddrOf)
  4888. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  4889. else
  4890. return nullptr;
  4891. }
  4892. case Stmt::BinaryOperatorClass: {
  4893. // Handle pointer arithmetic. All other binary operators are not valid
  4894. // in this context.
  4895. BinaryOperator *B = cast<BinaryOperator>(E);
  4896. BinaryOperatorKind op = B->getOpcode();
  4897. if (op != BO_Add && op != BO_Sub)
  4898. return nullptr;
  4899. Expr *Base = B->getLHS();
  4900. // Determine which argument is the real pointer base. It could be
  4901. // the RHS argument instead of the LHS.
  4902. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  4903. assert (Base->getType()->isPointerType());
  4904. return EvalAddr(Base, refVars, ParentDecl);
  4905. }
  4906. // For conditional operators we need to see if either the LHS or RHS are
  4907. // valid DeclRefExpr*s. If one of them is valid, we return it.
  4908. case Stmt::ConditionalOperatorClass: {
  4909. ConditionalOperator *C = cast<ConditionalOperator>(E);
  4910. // Handle the GNU extension for missing LHS.
  4911. // FIXME: That isn't a ConditionalOperator, so doesn't get here.
  4912. if (Expr *LHSExpr = C->getLHS()) {
  4913. // In C++, we can have a throw-expression, which has 'void' type.
  4914. if (!LHSExpr->getType()->isVoidType())
  4915. if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
  4916. return LHS;
  4917. }
  4918. // In C++, we can have a throw-expression, which has 'void' type.
  4919. if (C->getRHS()->getType()->isVoidType())
  4920. return nullptr;
  4921. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  4922. }
  4923. case Stmt::BlockExprClass:
  4924. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  4925. return E; // local block.
  4926. return nullptr;
  4927. case Stmt::AddrLabelExprClass:
  4928. return E; // address of label.
  4929. case Stmt::ExprWithCleanupsClass:
  4930. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  4931. ParentDecl);
  4932. // For casts, we need to handle conversions from arrays to
  4933. // pointer values, and pointer-to-pointer conversions.
  4934. case Stmt::ImplicitCastExprClass:
  4935. case Stmt::CStyleCastExprClass:
  4936. case Stmt::CXXFunctionalCastExprClass:
  4937. case Stmt::ObjCBridgedCastExprClass:
  4938. case Stmt::CXXStaticCastExprClass:
  4939. case Stmt::CXXDynamicCastExprClass:
  4940. case Stmt::CXXConstCastExprClass:
  4941. case Stmt::CXXReinterpretCastExprClass: {
  4942. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  4943. switch (cast<CastExpr>(E)->getCastKind()) {
  4944. case CK_LValueToRValue:
  4945. case CK_NoOp:
  4946. case CK_BaseToDerived:
  4947. case CK_DerivedToBase:
  4948. case CK_UncheckedDerivedToBase:
  4949. case CK_Dynamic:
  4950. case CK_CPointerToObjCPointerCast:
  4951. case CK_BlockPointerToObjCPointerCast:
  4952. case CK_AnyPointerToBlockPointerCast:
  4953. return EvalAddr(SubExpr, refVars, ParentDecl);
  4954. case CK_ArrayToPointerDecay:
  4955. return EvalVal(SubExpr, refVars, ParentDecl);
  4956. case CK_BitCast:
  4957. if (SubExpr->getType()->isAnyPointerType() ||
  4958. SubExpr->getType()->isBlockPointerType() ||
  4959. SubExpr->getType()->isObjCQualifiedIdType())
  4960. return EvalAddr(SubExpr, refVars, ParentDecl);
  4961. else
  4962. return nullptr;
  4963. default:
  4964. return nullptr;
  4965. }
  4966. }
  4967. case Stmt::MaterializeTemporaryExprClass:
  4968. if (Expr *Result = EvalAddr(
  4969. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  4970. refVars, ParentDecl))
  4971. return Result;
  4972. return E;
  4973. // Everything else: we simply don't reason about them.
  4974. default:
  4975. return nullptr;
  4976. }
  4977. }
  4978. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  4979. /// See the comments for EvalAddr for more details.
  4980. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4981. Decl *ParentDecl) {
  4982. do {
  4983. // We should only be called for evaluating non-pointer expressions, or
  4984. // expressions with a pointer type that are not used as references but instead
  4985. // are l-values (e.g., DeclRefExpr with a pointer type).
  4986. // Our "symbolic interpreter" is just a dispatch off the currently
  4987. // viewed AST node. We then recursively traverse the AST by calling
  4988. // EvalAddr and EvalVal appropriately.
  4989. E = E->IgnoreParens();
  4990. switch (E->getStmtClass()) {
  4991. case Stmt::ImplicitCastExprClass: {
  4992. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  4993. if (IE->getValueKind() == VK_LValue) {
  4994. E = IE->getSubExpr();
  4995. continue;
  4996. }
  4997. return nullptr;
  4998. }
  4999. case Stmt::ExprWithCleanupsClass:
  5000. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
  5001. case Stmt::DeclRefExprClass: {
  5002. // When we hit a DeclRefExpr we are looking at code that refers to a
  5003. // variable's name. If it's not a reference variable we check if it has
  5004. // local storage within the function, and if so, return the expression.
  5005. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  5006. // If we leave the immediate function, the lifetime isn't about to end.
  5007. if (DR->refersToEnclosingVariableOrCapture())
  5008. return nullptr;
  5009. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  5010. // Check if it refers to itself, e.g. "int& i = i;".
  5011. if (V == ParentDecl)
  5012. return DR;
  5013. if (V->hasLocalStorage()) {
  5014. if (!V->getType()->isReferenceType())
  5015. return DR;
  5016. // Reference variable, follow through to the expression that
  5017. // it points to.
  5018. if (V->hasInit()) {
  5019. // Add the reference variable to the "trail".
  5020. refVars.push_back(DR);
  5021. return EvalVal(V->getInit(), refVars, V);
  5022. }
  5023. }
  5024. }
  5025. return nullptr;
  5026. }
  5027. case Stmt::UnaryOperatorClass: {
  5028. // The only unary operator that make sense to handle here
  5029. // is Deref. All others don't resolve to a "name." This includes
  5030. // handling all sorts of rvalues passed to a unary operator.
  5031. UnaryOperator *U = cast<UnaryOperator>(E);
  5032. if (U->getOpcode() == UO_Deref)
  5033. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  5034. return nullptr;
  5035. }
  5036. case Stmt::ArraySubscriptExprClass: {
  5037. // Array subscripts are potential references to data on the stack. We
  5038. // retrieve the DeclRefExpr* for the array variable if it indeed
  5039. // has local storage.
  5040. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
  5041. }
  5042. case Stmt::ConditionalOperatorClass: {
  5043. // For conditional operators we need to see if either the LHS or RHS are
  5044. // non-NULL Expr's. If one is non-NULL, we return it.
  5045. ConditionalOperator *C = cast<ConditionalOperator>(E);
  5046. // Handle the GNU extension for missing LHS.
  5047. if (Expr *LHSExpr = C->getLHS()) {
  5048. // In C++, we can have a throw-expression, which has 'void' type.
  5049. if (!LHSExpr->getType()->isVoidType())
  5050. if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
  5051. return LHS;
  5052. }
  5053. // In C++, we can have a throw-expression, which has 'void' type.
  5054. if (C->getRHS()->getType()->isVoidType())
  5055. return nullptr;
  5056. return EvalVal(C->getRHS(), refVars, ParentDecl);
  5057. }
  5058. // Accesses to members are potential references to data on the stack.
  5059. case Stmt::MemberExprClass: {
  5060. MemberExpr *M = cast<MemberExpr>(E);
  5061. // Check for indirect access. We only want direct field accesses.
  5062. if (M->isArrow())
  5063. return nullptr;
  5064. // Check whether the member type is itself a reference, in which case
  5065. // we're not going to refer to the member, but to what the member refers to.
  5066. if (M->getMemberDecl()->getType()->isReferenceType())
  5067. return nullptr;
  5068. return EvalVal(M->getBase(), refVars, ParentDecl);
  5069. }
  5070. case Stmt::MaterializeTemporaryExprClass:
  5071. if (Expr *Result = EvalVal(
  5072. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  5073. refVars, ParentDecl))
  5074. return Result;
  5075. return E;
  5076. default:
  5077. // Check that we don't return or take the address of a reference to a
  5078. // temporary. This is only useful in C++.
  5079. if (!E->isTypeDependent() && E->isRValue())
  5080. return E;
  5081. // Everything else: we simply don't reason about them.
  5082. return nullptr;
  5083. }
  5084. } while (true);
  5085. }
  5086. void
  5087. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  5088. SourceLocation ReturnLoc,
  5089. bool isObjCMethod,
  5090. const AttrVec *Attrs,
  5091. const FunctionDecl *FD) {
  5092. CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
  5093. // Check if the return value is null but should not be.
  5094. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  5095. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  5096. CheckNonNullExpr(*this, RetValExp))
  5097. Diag(ReturnLoc, diag::warn_null_ret)
  5098. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  5099. // C++11 [basic.stc.dynamic.allocation]p4:
  5100. // If an allocation function declared with a non-throwing
  5101. // exception-specification fails to allocate storage, it shall return
  5102. // a null pointer. Any other allocation function that fails to allocate
  5103. // storage shall indicate failure only by throwing an exception [...]
  5104. if (FD) {
  5105. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  5106. if (Op == OO_New || Op == OO_Array_New) {
  5107. const FunctionProtoType *Proto
  5108. = FD->getType()->castAs<FunctionProtoType>();
  5109. if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
  5110. CheckNonNullExpr(*this, RetValExp))
  5111. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  5112. << FD << getLangOpts().CPlusPlus11;
  5113. }
  5114. }
  5115. }
  5116. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  5117. /// Check for comparisons of floating point operands using != and ==.
  5118. /// Issue a warning if these are no self-comparisons, as they are not likely
  5119. /// to do what the programmer intended.
  5120. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  5121. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  5122. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  5123. // Special case: check for x == x (which is OK).
  5124. // Do not emit warnings for such cases.
  5125. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  5126. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  5127. if (DRL->getDecl() == DRR->getDecl())
  5128. return;
  5129. // Special case: check for comparisons against literals that can be exactly
  5130. // represented by APFloat. In such cases, do not emit a warning. This
  5131. // is a heuristic: often comparison against such literals are used to
  5132. // detect if a value in a variable has not changed. This clearly can
  5133. // lead to false negatives.
  5134. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  5135. if (FLL->isExact())
  5136. return;
  5137. } else
  5138. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  5139. if (FLR->isExact())
  5140. return;
  5141. // Check for comparisons with builtin types.
  5142. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  5143. if (CL->getBuiltinCallee())
  5144. return;
  5145. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  5146. if (CR->getBuiltinCallee())
  5147. return;
  5148. // Emit the diagnostic.
  5149. Diag(Loc, diag::warn_floatingpoint_eq)
  5150. << LHS->getSourceRange() << RHS->getSourceRange();
  5151. }
  5152. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  5153. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  5154. namespace {
  5155. /// Structure recording the 'active' range of an integer-valued
  5156. /// expression.
  5157. struct IntRange {
  5158. /// The number of bits active in the int.
  5159. unsigned Width;
  5160. /// True if the int is known not to have negative values.
  5161. bool NonNegative;
  5162. IntRange(unsigned Width, bool NonNegative)
  5163. : Width(Width), NonNegative(NonNegative)
  5164. {}
  5165. /// Returns the range of the bool type.
  5166. static IntRange forBoolType() {
  5167. return IntRange(1, true);
  5168. }
  5169. /// Returns the range of an opaque value of the given integral type.
  5170. static IntRange forValueOfType(ASTContext &C, QualType T) {
  5171. return forValueOfCanonicalType(C,
  5172. T->getCanonicalTypeInternal().getTypePtr());
  5173. }
  5174. /// Returns the range of an opaque value of a canonical integral type.
  5175. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  5176. assert(T->isCanonicalUnqualified());
  5177. if (const VectorType *VT = dyn_cast<VectorType>(T))
  5178. T = VT->getElementType().getTypePtr();
  5179. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  5180. T = CT->getElementType().getTypePtr();
  5181. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  5182. T = AT->getValueType().getTypePtr();
  5183. // For enum types, use the known bit width of the enumerators.
  5184. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  5185. EnumDecl *Enum = ET->getDecl();
  5186. if (!Enum->isCompleteDefinition())
  5187. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  5188. unsigned NumPositive = Enum->getNumPositiveBits();
  5189. unsigned NumNegative = Enum->getNumNegativeBits();
  5190. if (NumNegative == 0)
  5191. return IntRange(NumPositive, true/*NonNegative*/);
  5192. else
  5193. return IntRange(std::max(NumPositive + 1, NumNegative),
  5194. false/*NonNegative*/);
  5195. }
  5196. const BuiltinType *BT = cast<BuiltinType>(T);
  5197. assert(BT->isInteger());
  5198. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  5199. }
  5200. /// Returns the "target" range of a canonical integral type, i.e.
  5201. /// the range of values expressible in the type.
  5202. ///
  5203. /// This matches forValueOfCanonicalType except that enums have the
  5204. /// full range of their type, not the range of their enumerators.
  5205. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  5206. assert(T->isCanonicalUnqualified());
  5207. if (const VectorType *VT = dyn_cast<VectorType>(T))
  5208. T = VT->getElementType().getTypePtr();
  5209. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  5210. T = CT->getElementType().getTypePtr();
  5211. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  5212. T = AT->getValueType().getTypePtr();
  5213. if (const EnumType *ET = dyn_cast<EnumType>(T))
  5214. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  5215. const BuiltinType *BT = cast<BuiltinType>(T);
  5216. assert(BT->isInteger());
  5217. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  5218. }
  5219. /// Returns the supremum of two ranges: i.e. their conservative merge.
  5220. static IntRange join(IntRange L, IntRange R) {
  5221. return IntRange(std::max(L.Width, R.Width),
  5222. L.NonNegative && R.NonNegative);
  5223. }
  5224. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  5225. static IntRange meet(IntRange L, IntRange R) {
  5226. return IntRange(std::min(L.Width, R.Width),
  5227. L.NonNegative || R.NonNegative);
  5228. }
  5229. };
  5230. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  5231. unsigned MaxWidth) {
  5232. if (value.isSigned() && value.isNegative())
  5233. return IntRange(value.getMinSignedBits(), false);
  5234. if (value.getBitWidth() > MaxWidth)
  5235. value = value.trunc(MaxWidth);
  5236. // isNonNegative() just checks the sign bit without considering
  5237. // signedness.
  5238. return IntRange(value.getActiveBits(), true);
  5239. }
  5240. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  5241. unsigned MaxWidth) {
  5242. if (result.isInt())
  5243. return GetValueRange(C, result.getInt(), MaxWidth);
  5244. if (result.isVector()) {
  5245. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  5246. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  5247. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  5248. R = IntRange::join(R, El);
  5249. }
  5250. return R;
  5251. }
  5252. if (result.isComplexInt()) {
  5253. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  5254. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  5255. return IntRange::join(R, I);
  5256. }
  5257. // This can happen with lossless casts to intptr_t of "based" lvalues.
  5258. // Assume it might use arbitrary bits.
  5259. // FIXME: The only reason we need to pass the type in here is to get
  5260. // the sign right on this one case. It would be nice if APValue
  5261. // preserved this.
  5262. assert(result.isLValue() || result.isAddrLabelDiff());
  5263. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  5264. }
  5265. static QualType GetExprType(Expr *E) {
  5266. QualType Ty = E->getType();
  5267. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  5268. Ty = AtomicRHS->getValueType();
  5269. return Ty;
  5270. }
  5271. /// Pseudo-evaluate the given integer expression, estimating the
  5272. /// range of values it might take.
  5273. ///
  5274. /// \param MaxWidth - the width to which the value will be truncated
  5275. static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  5276. E = E->IgnoreParens();
  5277. // Try a full evaluation first.
  5278. Expr::EvalResult result;
  5279. if (E->EvaluateAsRValue(result, C))
  5280. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  5281. // I think we only want to look through implicit casts here; if the
  5282. // user has an explicit widening cast, we should treat the value as
  5283. // being of the new, wider type.
  5284. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  5285. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  5286. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  5287. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  5288. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  5289. // Assume that non-integer casts can span the full range of the type.
  5290. if (!isIntegerCast)
  5291. return OutputTypeRange;
  5292. IntRange SubRange
  5293. = GetExprRange(C, CE->getSubExpr(),
  5294. std::min(MaxWidth, OutputTypeRange.Width));
  5295. // Bail out if the subexpr's range is as wide as the cast type.
  5296. if (SubRange.Width >= OutputTypeRange.Width)
  5297. return OutputTypeRange;
  5298. // Otherwise, we take the smaller width, and we're non-negative if
  5299. // either the output type or the subexpr is.
  5300. return IntRange(SubRange.Width,
  5301. SubRange.NonNegative || OutputTypeRange.NonNegative);
  5302. }
  5303. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5304. // If we can fold the condition, just take that operand.
  5305. bool CondResult;
  5306. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  5307. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  5308. : CO->getFalseExpr(),
  5309. MaxWidth);
  5310. // Otherwise, conservatively merge.
  5311. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  5312. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  5313. return IntRange::join(L, R);
  5314. }
  5315. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  5316. switch (BO->getOpcode()) {
  5317. // Boolean-valued operations are single-bit and positive.
  5318. case BO_LAnd:
  5319. case BO_LOr:
  5320. case BO_LT:
  5321. case BO_GT:
  5322. case BO_LE:
  5323. case BO_GE:
  5324. case BO_EQ:
  5325. case BO_NE:
  5326. return IntRange::forBoolType();
  5327. // The type of the assignments is the type of the LHS, so the RHS
  5328. // is not necessarily the same type.
  5329. case BO_MulAssign:
  5330. case BO_DivAssign:
  5331. case BO_RemAssign:
  5332. case BO_AddAssign:
  5333. case BO_SubAssign:
  5334. case BO_XorAssign:
  5335. case BO_OrAssign:
  5336. // TODO: bitfields?
  5337. return IntRange::forValueOfType(C, GetExprType(E));
  5338. // Simple assignments just pass through the RHS, which will have
  5339. // been coerced to the LHS type.
  5340. case BO_Assign:
  5341. // TODO: bitfields?
  5342. return GetExprRange(C, BO->getRHS(), MaxWidth);
  5343. // Operations with opaque sources are black-listed.
  5344. case BO_PtrMemD:
  5345. case BO_PtrMemI:
  5346. return IntRange::forValueOfType(C, GetExprType(E));
  5347. // Bitwise-and uses the *infinum* of the two source ranges.
  5348. case BO_And:
  5349. case BO_AndAssign:
  5350. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  5351. GetExprRange(C, BO->getRHS(), MaxWidth));
  5352. // Left shift gets black-listed based on a judgement call.
  5353. case BO_Shl:
  5354. // ...except that we want to treat '1 << (blah)' as logically
  5355. // positive. It's an important idiom.
  5356. if (IntegerLiteral *I
  5357. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  5358. if (I->getValue() == 1) {
  5359. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  5360. return IntRange(R.Width, /*NonNegative*/ true);
  5361. }
  5362. }
  5363. // fallthrough
  5364. case BO_ShlAssign:
  5365. return IntRange::forValueOfType(C, GetExprType(E));
  5366. // Right shift by a constant can narrow its left argument.
  5367. case BO_Shr:
  5368. case BO_ShrAssign: {
  5369. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  5370. // If the shift amount is a positive constant, drop the width by
  5371. // that much.
  5372. llvm::APSInt shift;
  5373. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  5374. shift.isNonNegative()) {
  5375. unsigned zext = shift.getZExtValue();
  5376. if (zext >= L.Width)
  5377. L.Width = (L.NonNegative ? 0 : 1);
  5378. else
  5379. L.Width -= zext;
  5380. }
  5381. return L;
  5382. }
  5383. // Comma acts as its right operand.
  5384. case BO_Comma:
  5385. return GetExprRange(C, BO->getRHS(), MaxWidth);
  5386. // Black-list pointer subtractions.
  5387. case BO_Sub:
  5388. if (BO->getLHS()->getType()->isPointerType())
  5389. return IntRange::forValueOfType(C, GetExprType(E));
  5390. break;
  5391. // The width of a division result is mostly determined by the size
  5392. // of the LHS.
  5393. case BO_Div: {
  5394. // Don't 'pre-truncate' the operands.
  5395. unsigned opWidth = C.getIntWidth(GetExprType(E));
  5396. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  5397. // If the divisor is constant, use that.
  5398. llvm::APSInt divisor;
  5399. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  5400. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  5401. if (log2 >= L.Width)
  5402. L.Width = (L.NonNegative ? 0 : 1);
  5403. else
  5404. L.Width = std::min(L.Width - log2, MaxWidth);
  5405. return L;
  5406. }
  5407. // Otherwise, just use the LHS's width.
  5408. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  5409. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  5410. }
  5411. // The result of a remainder can't be larger than the result of
  5412. // either side.
  5413. case BO_Rem: {
  5414. // Don't 'pre-truncate' the operands.
  5415. unsigned opWidth = C.getIntWidth(GetExprType(E));
  5416. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  5417. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  5418. IntRange meet = IntRange::meet(L, R);
  5419. meet.Width = std::min(meet.Width, MaxWidth);
  5420. return meet;
  5421. }
  5422. // The default behavior is okay for these.
  5423. case BO_Mul:
  5424. case BO_Add:
  5425. case BO_Xor:
  5426. case BO_Or:
  5427. break;
  5428. }
  5429. // The default case is to treat the operation as if it were closed
  5430. // on the narrowest type that encompasses both operands.
  5431. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  5432. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  5433. return IntRange::join(L, R);
  5434. }
  5435. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  5436. switch (UO->getOpcode()) {
  5437. // Boolean-valued operations are white-listed.
  5438. case UO_LNot:
  5439. return IntRange::forBoolType();
  5440. // Operations with opaque sources are black-listed.
  5441. case UO_Deref:
  5442. case UO_AddrOf: // should be impossible
  5443. return IntRange::forValueOfType(C, GetExprType(E));
  5444. default:
  5445. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  5446. }
  5447. }
  5448. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
  5449. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  5450. if (FieldDecl *BitField = E->getSourceBitField())
  5451. return IntRange(BitField->getBitWidthValue(C),
  5452. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  5453. return IntRange::forValueOfType(C, GetExprType(E));
  5454. }
  5455. static IntRange GetExprRange(ASTContext &C, Expr *E) {
  5456. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  5457. }
  5458. /// Checks whether the given value, which currently has the given
  5459. /// source semantics, has the same value when coerced through the
  5460. /// target semantics.
  5461. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  5462. const llvm::fltSemantics &Src,
  5463. const llvm::fltSemantics &Tgt) {
  5464. llvm::APFloat truncated = value;
  5465. bool ignored;
  5466. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  5467. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  5468. return truncated.bitwiseIsEqual(value);
  5469. }
  5470. /// Checks whether the given value, which currently has the given
  5471. /// source semantics, has the same value when coerced through the
  5472. /// target semantics.
  5473. ///
  5474. /// The value might be a vector of floats (or a complex number).
  5475. static bool IsSameFloatAfterCast(const APValue &value,
  5476. const llvm::fltSemantics &Src,
  5477. const llvm::fltSemantics &Tgt) {
  5478. if (value.isFloat())
  5479. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  5480. if (value.isVector()) {
  5481. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  5482. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  5483. return false;
  5484. return true;
  5485. }
  5486. assert(value.isComplexFloat());
  5487. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  5488. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  5489. }
  5490. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  5491. static bool IsZero(Sema &S, Expr *E) {
  5492. // Suppress cases where we are comparing against an enum constant.
  5493. if (const DeclRefExpr *DR =
  5494. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  5495. if (isa<EnumConstantDecl>(DR->getDecl()))
  5496. return false;
  5497. // Suppress cases where the '0' value is expanded from a macro.
  5498. if (E->getLocStart().isMacroID())
  5499. return false;
  5500. llvm::APSInt Value;
  5501. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  5502. }
  5503. static bool HasEnumType(Expr *E) {
  5504. // Strip off implicit integral promotions.
  5505. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  5506. if (ICE->getCastKind() != CK_IntegralCast &&
  5507. ICE->getCastKind() != CK_NoOp)
  5508. break;
  5509. E = ICE->getSubExpr();
  5510. }
  5511. return E->getType()->isEnumeralType();
  5512. }
  5513. static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  5514. // Disable warning in template instantiations.
  5515. if (!S.ActiveTemplateInstantiations.empty())
  5516. return;
  5517. BinaryOperatorKind op = E->getOpcode();
  5518. if (E->isValueDependent())
  5519. return;
  5520. if (op == BO_LT && IsZero(S, E->getRHS())) {
  5521. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  5522. << "< 0" << "false" << HasEnumType(E->getLHS())
  5523. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5524. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  5525. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  5526. << ">= 0" << "true" << HasEnumType(E->getLHS())
  5527. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5528. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  5529. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  5530. << "0 >" << "false" << HasEnumType(E->getRHS())
  5531. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5532. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  5533. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  5534. << "0 <=" << "true" << HasEnumType(E->getRHS())
  5535. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5536. }
  5537. }
  5538. static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
  5539. Expr *Constant, Expr *Other,
  5540. llvm::APSInt Value,
  5541. bool RhsConstant) {
  5542. // Disable warning in template instantiations.
  5543. if (!S.ActiveTemplateInstantiations.empty())
  5544. return;
  5545. // TODO: Investigate using GetExprRange() to get tighter bounds
  5546. // on the bit ranges.
  5547. QualType OtherT = Other->getType();
  5548. if (const auto *AT = OtherT->getAs<AtomicType>())
  5549. OtherT = AT->getValueType();
  5550. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  5551. unsigned OtherWidth = OtherRange.Width;
  5552. bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
  5553. // 0 values are handled later by CheckTrivialUnsignedComparison().
  5554. if ((Value == 0) && (!OtherIsBooleanType))
  5555. return;
  5556. BinaryOperatorKind op = E->getOpcode();
  5557. bool IsTrue = true;
  5558. // Used for diagnostic printout.
  5559. enum {
  5560. LiteralConstant = 0,
  5561. CXXBoolLiteralTrue,
  5562. CXXBoolLiteralFalse
  5563. } LiteralOrBoolConstant = LiteralConstant;
  5564. if (!OtherIsBooleanType) {
  5565. QualType ConstantT = Constant->getType();
  5566. QualType CommonT = E->getLHS()->getType();
  5567. if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
  5568. return;
  5569. assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
  5570. "comparison with non-integer type");
  5571. bool ConstantSigned = ConstantT->isSignedIntegerType();
  5572. bool CommonSigned = CommonT->isSignedIntegerType();
  5573. bool EqualityOnly = false;
  5574. if (CommonSigned) {
  5575. // The common type is signed, therefore no signed to unsigned conversion.
  5576. if (!OtherRange.NonNegative) {
  5577. // Check that the constant is representable in type OtherT.
  5578. if (ConstantSigned) {
  5579. if (OtherWidth >= Value.getMinSignedBits())
  5580. return;
  5581. } else { // !ConstantSigned
  5582. if (OtherWidth >= Value.getActiveBits() + 1)
  5583. return;
  5584. }
  5585. } else { // !OtherSigned
  5586. // Check that the constant is representable in type OtherT.
  5587. // Negative values are out of range.
  5588. if (ConstantSigned) {
  5589. if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
  5590. return;
  5591. } else { // !ConstantSigned
  5592. if (OtherWidth >= Value.getActiveBits())
  5593. return;
  5594. }
  5595. }
  5596. } else { // !CommonSigned
  5597. if (OtherRange.NonNegative) {
  5598. if (OtherWidth >= Value.getActiveBits())
  5599. return;
  5600. } else { // OtherSigned
  5601. assert(!ConstantSigned &&
  5602. "Two signed types converted to unsigned types.");
  5603. // Check to see if the constant is representable in OtherT.
  5604. if (OtherWidth > Value.getActiveBits())
  5605. return;
  5606. // Check to see if the constant is equivalent to a negative value
  5607. // cast to CommonT.
  5608. if (S.Context.getIntWidth(ConstantT) ==
  5609. S.Context.getIntWidth(CommonT) &&
  5610. Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
  5611. return;
  5612. // The constant value rests between values that OtherT can represent
  5613. // after conversion. Relational comparison still works, but equality
  5614. // comparisons will be tautological.
  5615. EqualityOnly = true;
  5616. }
  5617. }
  5618. bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
  5619. if (op == BO_EQ || op == BO_NE) {
  5620. IsTrue = op == BO_NE;
  5621. } else if (EqualityOnly) {
  5622. return;
  5623. } else if (RhsConstant) {
  5624. if (op == BO_GT || op == BO_GE)
  5625. IsTrue = !PositiveConstant;
  5626. else // op == BO_LT || op == BO_LE
  5627. IsTrue = PositiveConstant;
  5628. } else {
  5629. if (op == BO_LT || op == BO_LE)
  5630. IsTrue = !PositiveConstant;
  5631. else // op == BO_GT || op == BO_GE
  5632. IsTrue = PositiveConstant;
  5633. }
  5634. } else {
  5635. // Other isKnownToHaveBooleanValue
  5636. enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
  5637. enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
  5638. enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
  5639. static const struct LinkedConditions {
  5640. CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
  5641. CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
  5642. CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
  5643. CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
  5644. CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
  5645. CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
  5646. } TruthTable = {
  5647. // Constant on LHS. | Constant on RHS. |
  5648. // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
  5649. { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
  5650. { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
  5651. { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
  5652. { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
  5653. { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
  5654. { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
  5655. };
  5656. bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
  5657. enum ConstantValue ConstVal = Zero;
  5658. if (Value.isUnsigned() || Value.isNonNegative()) {
  5659. if (Value == 0) {
  5660. LiteralOrBoolConstant =
  5661. ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
  5662. ConstVal = Zero;
  5663. } else if (Value == 1) {
  5664. LiteralOrBoolConstant =
  5665. ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
  5666. ConstVal = One;
  5667. } else {
  5668. LiteralOrBoolConstant = LiteralConstant;
  5669. ConstVal = GT_One;
  5670. }
  5671. } else {
  5672. ConstVal = LT_Zero;
  5673. }
  5674. CompareBoolWithConstantResult CmpRes;
  5675. switch (op) {
  5676. case BO_LT:
  5677. CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
  5678. break;
  5679. case BO_GT:
  5680. CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
  5681. break;
  5682. case BO_LE:
  5683. CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
  5684. break;
  5685. case BO_GE:
  5686. CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
  5687. break;
  5688. case BO_EQ:
  5689. CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
  5690. break;
  5691. case BO_NE:
  5692. CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
  5693. break;
  5694. default:
  5695. CmpRes = Unkwn;
  5696. break;
  5697. }
  5698. if (CmpRes == AFals) {
  5699. IsTrue = false;
  5700. } else if (CmpRes == ATrue) {
  5701. IsTrue = true;
  5702. } else {
  5703. return;
  5704. }
  5705. }
  5706. // If this is a comparison to an enum constant, include that
  5707. // constant in the diagnostic.
  5708. const EnumConstantDecl *ED = nullptr;
  5709. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  5710. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  5711. SmallString<64> PrettySourceValue;
  5712. llvm::raw_svector_ostream OS(PrettySourceValue);
  5713. if (ED)
  5714. OS << '\'' << *ED << "' (" << Value << ")";
  5715. else
  5716. OS << Value;
  5717. S.DiagRuntimeBehavior(
  5718. E->getOperatorLoc(), E,
  5719. S.PDiag(diag::warn_out_of_range_compare)
  5720. << OS.str() << LiteralOrBoolConstant
  5721. << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
  5722. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  5723. }
  5724. /// Analyze the operands of the given comparison. Implements the
  5725. /// fallback case from AnalyzeComparison.
  5726. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  5727. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  5728. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  5729. }
  5730. /// \brief Implements -Wsign-compare.
  5731. ///
  5732. /// \param E the binary operator to check for warnings
  5733. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  5734. // The type the comparison is being performed in.
  5735. QualType T = E->getLHS()->getType();
  5736. // Only analyze comparison operators where both sides have been converted to
  5737. // the same type.
  5738. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  5739. return AnalyzeImpConvsInComparison(S, E);
  5740. // Don't analyze value-dependent comparisons directly.
  5741. if (E->isValueDependent())
  5742. return AnalyzeImpConvsInComparison(S, E);
  5743. Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
  5744. Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
  5745. bool IsComparisonConstant = false;
  5746. // Check whether an integer constant comparison results in a value
  5747. // of 'true' or 'false'.
  5748. if (T->isIntegralType(S.Context)) {
  5749. llvm::APSInt RHSValue;
  5750. bool IsRHSIntegralLiteral =
  5751. RHS->isIntegerConstantExpr(RHSValue, S.Context);
  5752. llvm::APSInt LHSValue;
  5753. bool IsLHSIntegralLiteral =
  5754. LHS->isIntegerConstantExpr(LHSValue, S.Context);
  5755. if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
  5756. DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
  5757. else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  5758. DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
  5759. else
  5760. IsComparisonConstant =
  5761. (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
  5762. } else if (!T->hasUnsignedIntegerRepresentation())
  5763. IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
  5764. // We don't do anything special if this isn't an unsigned integral
  5765. // comparison: we're only interested in integral comparisons, and
  5766. // signed comparisons only happen in cases we don't care to warn about.
  5767. //
  5768. // We also don't care about value-dependent expressions or expressions
  5769. // whose result is a constant.
  5770. if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
  5771. return AnalyzeImpConvsInComparison(S, E);
  5772. // Check to see if one of the (unmodified) operands is of different
  5773. // signedness.
  5774. Expr *signedOperand, *unsignedOperand;
  5775. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  5776. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  5777. "unsigned comparison between two signed integer expressions?");
  5778. signedOperand = LHS;
  5779. unsignedOperand = RHS;
  5780. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  5781. signedOperand = RHS;
  5782. unsignedOperand = LHS;
  5783. } else {
  5784. CheckTrivialUnsignedComparison(S, E);
  5785. return AnalyzeImpConvsInComparison(S, E);
  5786. }
  5787. // Otherwise, calculate the effective range of the signed operand.
  5788. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  5789. // Go ahead and analyze implicit conversions in the operands. Note
  5790. // that we skip the implicit conversions on both sides.
  5791. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  5792. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  5793. // If the signed range is non-negative, -Wsign-compare won't fire,
  5794. // but we should still check for comparisons which are always true
  5795. // or false.
  5796. if (signedRange.NonNegative)
  5797. return CheckTrivialUnsignedComparison(S, E);
  5798. // For (in)equality comparisons, if the unsigned operand is a
  5799. // constant which cannot collide with a overflowed signed operand,
  5800. // then reinterpreting the signed operand as unsigned will not
  5801. // change the result of the comparison.
  5802. if (E->isEqualityOp()) {
  5803. unsigned comparisonWidth = S.Context.getIntWidth(T);
  5804. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  5805. // We should never be unable to prove that the unsigned operand is
  5806. // non-negative.
  5807. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  5808. if (unsignedRange.Width < comparisonWidth)
  5809. return;
  5810. }
  5811. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  5812. S.PDiag(diag::warn_mixed_sign_comparison)
  5813. << LHS->getType() << RHS->getType()
  5814. << LHS->getSourceRange() << RHS->getSourceRange());
  5815. }
  5816. /// Analyzes an attempt to assign the given value to a bitfield.
  5817. ///
  5818. /// Returns true if there was something fishy about the attempt.
  5819. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  5820. SourceLocation InitLoc) {
  5821. assert(Bitfield->isBitField());
  5822. if (Bitfield->isInvalidDecl())
  5823. return false;
  5824. // White-list bool bitfields.
  5825. if (Bitfield->getType()->isBooleanType())
  5826. return false;
  5827. // Ignore value- or type-dependent expressions.
  5828. if (Bitfield->getBitWidth()->isValueDependent() ||
  5829. Bitfield->getBitWidth()->isTypeDependent() ||
  5830. Init->isValueDependent() ||
  5831. Init->isTypeDependent())
  5832. return false;
  5833. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  5834. llvm::APSInt Value;
  5835. if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
  5836. return false;
  5837. unsigned OriginalWidth = Value.getBitWidth();
  5838. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  5839. if (OriginalWidth <= FieldWidth)
  5840. return false;
  5841. // Compute the value which the bitfield will contain.
  5842. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  5843. TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
  5844. // Check whether the stored value is equal to the original value.
  5845. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  5846. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  5847. return false;
  5848. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  5849. // therefore don't strictly fit into a signed bitfield of width 1.
  5850. if (FieldWidth == 1 && Value == 1)
  5851. return false;
  5852. std::string PrettyValue = Value.toString(10);
  5853. std::string PrettyTrunc = TruncatedValue.toString(10);
  5854. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  5855. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  5856. << Init->getSourceRange();
  5857. return true;
  5858. }
  5859. /// Analyze the given simple or compound assignment for warning-worthy
  5860. /// operations.
  5861. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  5862. // Just recurse on the LHS.
  5863. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  5864. // We want to recurse on the RHS as normal unless we're assigning to
  5865. // a bitfield.
  5866. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  5867. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  5868. E->getOperatorLoc())) {
  5869. // Recurse, ignoring any implicit conversions on the RHS.
  5870. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  5871. E->getOperatorLoc());
  5872. }
  5873. }
  5874. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  5875. }
  5876. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  5877. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  5878. SourceLocation CContext, unsigned diag,
  5879. bool pruneControlFlow = false) {
  5880. if (pruneControlFlow) {
  5881. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  5882. S.PDiag(diag)
  5883. << SourceType << T << E->getSourceRange()
  5884. << SourceRange(CContext));
  5885. return;
  5886. }
  5887. S.Diag(E->getExprLoc(), diag)
  5888. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  5889. }
  5890. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  5891. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  5892. SourceLocation CContext, unsigned diag,
  5893. bool pruneControlFlow = false) {
  5894. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  5895. }
  5896. /// Diagnose an implicit cast from a literal expression. Does not warn when the
  5897. /// cast wouldn't lose information.
  5898. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  5899. SourceLocation CContext) {
  5900. // Try to convert the literal exactly to an integer. If we can, don't warn.
  5901. bool isExact = false;
  5902. const llvm::APFloat &Value = FL->getValue();
  5903. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  5904. T->hasUnsignedIntegerRepresentation());
  5905. if (Value.convertToInteger(IntegerValue,
  5906. llvm::APFloat::rmTowardZero, &isExact)
  5907. == llvm::APFloat::opOK && isExact)
  5908. return;
  5909. // FIXME: Force the precision of the source value down so we don't print
  5910. // digits which are usually useless (we don't really care here if we
  5911. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  5912. // would automatically print the shortest representation, but it's a bit
  5913. // tricky to implement.
  5914. SmallString<16> PrettySourceValue;
  5915. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  5916. precision = (precision * 59 + 195) / 196;
  5917. Value.toString(PrettySourceValue, precision);
  5918. SmallString<16> PrettyTargetValue;
  5919. if (T->isSpecificBuiltinType(BuiltinType::Bool))
  5920. PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
  5921. else
  5922. IntegerValue.toString(PrettyTargetValue);
  5923. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  5924. << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
  5925. << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
  5926. }
  5927. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  5928. if (!Range.Width) return "0";
  5929. llvm::APSInt ValueInRange = Value;
  5930. ValueInRange.setIsSigned(!Range.NonNegative);
  5931. ValueInRange = ValueInRange.trunc(Range.Width);
  5932. return ValueInRange.toString(10);
  5933. }
  5934. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  5935. if (!isa<ImplicitCastExpr>(Ex))
  5936. return false;
  5937. Expr *InnerE = Ex->IgnoreParenImpCasts();
  5938. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  5939. const Type *Source =
  5940. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  5941. if (Target->isDependentType())
  5942. return false;
  5943. const BuiltinType *FloatCandidateBT =
  5944. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  5945. const Type *BoolCandidateType = ToBool ? Target : Source;
  5946. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  5947. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  5948. }
  5949. void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  5950. SourceLocation CC) {
  5951. unsigned NumArgs = TheCall->getNumArgs();
  5952. for (unsigned i = 0; i < NumArgs; ++i) {
  5953. Expr *CurrA = TheCall->getArg(i);
  5954. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  5955. continue;
  5956. bool IsSwapped = ((i > 0) &&
  5957. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  5958. IsSwapped |= ((i < (NumArgs - 1)) &&
  5959. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  5960. if (IsSwapped) {
  5961. // Warn on this floating-point to bool conversion.
  5962. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  5963. CurrA->getType(), CC,
  5964. diag::warn_impcast_floating_point_to_bool);
  5965. }
  5966. }
  5967. }
  5968. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  5969. SourceLocation CC) {
  5970. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  5971. E->getExprLoc()))
  5972. return;
  5973. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  5974. const Expr::NullPointerConstantKind NullKind =
  5975. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  5976. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  5977. return;
  5978. // Return if target type is a safe conversion.
  5979. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  5980. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  5981. return;
  5982. SourceLocation Loc = E->getSourceRange().getBegin();
  5983. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  5984. if (NullKind == Expr::NPCK_GNUNull) {
  5985. if (Loc.isMacroID())
  5986. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  5987. }
  5988. // Only warn if the null and context location are in the same macro expansion.
  5989. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  5990. return;
  5991. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  5992. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
  5993. << FixItHint::CreateReplacement(Loc,
  5994. S.getFixItZeroLiteralForType(T, Loc));
  5995. }
  5996. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  5997. ObjCArrayLiteral *ArrayLiteral);
  5998. static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  5999. ObjCDictionaryLiteral *DictionaryLiteral);
  6000. /// Check a single element within a collection literal against the
  6001. /// target element type.
  6002. static void checkObjCCollectionLiteralElement(Sema &S,
  6003. QualType TargetElementType,
  6004. Expr *Element,
  6005. unsigned ElementKind) {
  6006. // Skip a bitcast to 'id' or qualified 'id'.
  6007. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  6008. if (ICE->getCastKind() == CK_BitCast &&
  6009. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  6010. Element = ICE->getSubExpr();
  6011. }
  6012. QualType ElementType = Element->getType();
  6013. ExprResult ElementResult(Element);
  6014. if (ElementType->getAs<ObjCObjectPointerType>() &&
  6015. S.CheckSingleAssignmentConstraints(TargetElementType,
  6016. ElementResult,
  6017. false, false)
  6018. != Sema::Compatible) {
  6019. S.Diag(Element->getLocStart(),
  6020. diag::warn_objc_collection_literal_element)
  6021. << ElementType << ElementKind << TargetElementType
  6022. << Element->getSourceRange();
  6023. }
  6024. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  6025. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  6026. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  6027. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  6028. }
  6029. /// Check an Objective-C array literal being converted to the given
  6030. /// target type.
  6031. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  6032. ObjCArrayLiteral *ArrayLiteral) {
  6033. if (!S.NSArrayDecl)
  6034. return;
  6035. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  6036. if (!TargetObjCPtr)
  6037. return;
  6038. if (TargetObjCPtr->isUnspecialized() ||
  6039. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  6040. != S.NSArrayDecl->getCanonicalDecl())
  6041. return;
  6042. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  6043. if (TypeArgs.size() != 1)
  6044. return;
  6045. QualType TargetElementType = TypeArgs[0];
  6046. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  6047. checkObjCCollectionLiteralElement(S, TargetElementType,
  6048. ArrayLiteral->getElement(I),
  6049. 0);
  6050. }
  6051. }
  6052. /// Check an Objective-C dictionary literal being converted to the given
  6053. /// target type.
  6054. static void checkObjCDictionaryLiteral(
  6055. Sema &S, QualType TargetType,
  6056. ObjCDictionaryLiteral *DictionaryLiteral) {
  6057. if (!S.NSDictionaryDecl)
  6058. return;
  6059. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  6060. if (!TargetObjCPtr)
  6061. return;
  6062. if (TargetObjCPtr->isUnspecialized() ||
  6063. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  6064. != S.NSDictionaryDecl->getCanonicalDecl())
  6065. return;
  6066. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  6067. if (TypeArgs.size() != 2)
  6068. return;
  6069. QualType TargetKeyType = TypeArgs[0];
  6070. QualType TargetObjectType = TypeArgs[1];
  6071. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  6072. auto Element = DictionaryLiteral->getKeyValueElement(I);
  6073. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  6074. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  6075. }
  6076. }
  6077. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  6078. SourceLocation CC, bool *ICContext = nullptr) {
  6079. if (E->isTypeDependent() || E->isValueDependent()) return;
  6080. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  6081. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  6082. if (Source == Target) return;
  6083. if (Target->isDependentType()) return;
  6084. // If the conversion context location is invalid don't complain. We also
  6085. // don't want to emit a warning if the issue occurs from the expansion of
  6086. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  6087. // delay this check as long as possible. Once we detect we are in that
  6088. // scenario, we just return.
  6089. if (CC.isInvalid())
  6090. return;
  6091. // Diagnose implicit casts to bool.
  6092. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  6093. if (isa<StringLiteral>(E))
  6094. // Warn on string literal to bool. Checks for string literals in logical
  6095. // and expressions, for instance, assert(0 && "error here"), are
  6096. // prevented by a check in AnalyzeImplicitConversions().
  6097. return DiagnoseImpCast(S, E, T, CC,
  6098. diag::warn_impcast_string_literal_to_bool);
  6099. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  6100. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  6101. // This covers the literal expressions that evaluate to Objective-C
  6102. // objects.
  6103. return DiagnoseImpCast(S, E, T, CC,
  6104. diag::warn_impcast_objective_c_literal_to_bool);
  6105. }
  6106. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  6107. // Warn on pointer to bool conversion that is always true.
  6108. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  6109. SourceRange(CC));
  6110. }
  6111. }
  6112. // Check implicit casts from Objective-C collection literals to specialized
  6113. // collection types, e.g., NSArray<NSString *> *.
  6114. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  6115. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  6116. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  6117. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  6118. // Strip vector types.
  6119. if (isa<VectorType>(Source)) {
  6120. if (!isa<VectorType>(Target)) {
  6121. if (S.SourceMgr.isInSystemMacro(CC))
  6122. return;
  6123. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  6124. }
  6125. // If the vector cast is cast between two vectors of the same size, it is
  6126. // a bitcast, not a conversion.
  6127. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  6128. return;
  6129. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  6130. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  6131. }
  6132. if (auto VecTy = dyn_cast<VectorType>(Target))
  6133. Target = VecTy->getElementType().getTypePtr();
  6134. // Strip complex types.
  6135. if (isa<ComplexType>(Source)) {
  6136. if (!isa<ComplexType>(Target)) {
  6137. if (S.SourceMgr.isInSystemMacro(CC))
  6138. return;
  6139. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  6140. }
  6141. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  6142. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  6143. }
  6144. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  6145. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  6146. // If the source is floating point...
  6147. if (SourceBT && SourceBT->isFloatingPoint()) {
  6148. // ...and the target is floating point...
  6149. if (TargetBT && TargetBT->isFloatingPoint()) {
  6150. // ...then warn if we're dropping FP rank.
  6151. // Builtin FP kinds are ordered by increasing FP rank.
  6152. if (SourceBT->getKind() > TargetBT->getKind()) {
  6153. // Don't warn about float constants that are precisely
  6154. // representable in the target type.
  6155. Expr::EvalResult result;
  6156. if (E->EvaluateAsRValue(result, S.Context)) {
  6157. // Value might be a float, a float vector, or a float complex.
  6158. if (IsSameFloatAfterCast(result.Val,
  6159. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  6160. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  6161. return;
  6162. }
  6163. if (S.SourceMgr.isInSystemMacro(CC))
  6164. return;
  6165. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  6166. }
  6167. return;
  6168. }
  6169. // If the target is integral, always warn.
  6170. if (TargetBT && TargetBT->isInteger()) {
  6171. if (S.SourceMgr.isInSystemMacro(CC))
  6172. return;
  6173. Expr *InnerE = E->IgnoreParenImpCasts();
  6174. // We also want to warn on, e.g., "int i = -1.234"
  6175. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  6176. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  6177. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  6178. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  6179. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  6180. } else {
  6181. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  6182. }
  6183. }
  6184. // If the target is bool, warn if expr is a function or method call.
  6185. if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
  6186. isa<CallExpr>(E)) {
  6187. // Check last argument of function call to see if it is an
  6188. // implicit cast from a type matching the type the result
  6189. // is being cast to.
  6190. CallExpr *CEx = cast<CallExpr>(E);
  6191. unsigned NumArgs = CEx->getNumArgs();
  6192. if (NumArgs > 0) {
  6193. Expr *LastA = CEx->getArg(NumArgs - 1);
  6194. Expr *InnerE = LastA->IgnoreParenImpCasts();
  6195. const Type *InnerType =
  6196. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  6197. if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
  6198. // Warn on this floating-point to bool conversion
  6199. DiagnoseImpCast(S, E, T, CC,
  6200. diag::warn_impcast_floating_point_to_bool);
  6201. }
  6202. }
  6203. }
  6204. return;
  6205. }
  6206. DiagnoseNullConversion(S, E, T, CC);
  6207. if (!Source->isIntegerType() || !Target->isIntegerType())
  6208. return;
  6209. // TODO: remove this early return once the false positives for constant->bool
  6210. // in templates, macros, etc, are reduced or removed.
  6211. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  6212. return;
  6213. IntRange SourceRange = GetExprRange(S.Context, E);
  6214. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  6215. if (SourceRange.Width > TargetRange.Width) {
  6216. // If the source is a constant, use a default-on diagnostic.
  6217. // TODO: this should happen for bitfield stores, too.
  6218. llvm::APSInt Value(32);
  6219. if (E->isIntegerConstantExpr(Value, S.Context)) {
  6220. if (S.SourceMgr.isInSystemMacro(CC))
  6221. return;
  6222. std::string PrettySourceValue = Value.toString(10);
  6223. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  6224. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  6225. S.PDiag(diag::warn_impcast_integer_precision_constant)
  6226. << PrettySourceValue << PrettyTargetValue
  6227. << E->getType() << T << E->getSourceRange()
  6228. << clang::SourceRange(CC));
  6229. return;
  6230. }
  6231. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  6232. if (S.SourceMgr.isInSystemMacro(CC))
  6233. return;
  6234. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  6235. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  6236. /* pruneControlFlow */ true);
  6237. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  6238. }
  6239. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  6240. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  6241. SourceRange.Width == TargetRange.Width)) {
  6242. if (S.SourceMgr.isInSystemMacro(CC))
  6243. return;
  6244. unsigned DiagID = diag::warn_impcast_integer_sign;
  6245. // Traditionally, gcc has warned about this under -Wsign-compare.
  6246. // We also want to warn about it in -Wconversion.
  6247. // So if -Wconversion is off, use a completely identical diagnostic
  6248. // in the sign-compare group.
  6249. // The conditional-checking code will
  6250. if (ICContext) {
  6251. DiagID = diag::warn_impcast_integer_sign_conditional;
  6252. *ICContext = true;
  6253. }
  6254. return DiagnoseImpCast(S, E, T, CC, DiagID);
  6255. }
  6256. // Diagnose conversions between different enumeration types.
  6257. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  6258. // type, to give us better diagnostics.
  6259. QualType SourceType = E->getType();
  6260. if (!S.getLangOpts().CPlusPlus) {
  6261. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6262. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  6263. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  6264. SourceType = S.Context.getTypeDeclType(Enum);
  6265. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  6266. }
  6267. }
  6268. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  6269. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  6270. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  6271. TargetEnum->getDecl()->hasNameForLinkage() &&
  6272. SourceEnum != TargetEnum) {
  6273. if (S.SourceMgr.isInSystemMacro(CC))
  6274. return;
  6275. return DiagnoseImpCast(S, E, SourceType, T, CC,
  6276. diag::warn_impcast_different_enum_types);
  6277. }
  6278. return;
  6279. }
  6280. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  6281. SourceLocation CC, QualType T);
  6282. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  6283. SourceLocation CC, bool &ICContext) {
  6284. E = E->IgnoreParenImpCasts();
  6285. if (isa<ConditionalOperator>(E))
  6286. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  6287. AnalyzeImplicitConversions(S, E, CC);
  6288. if (E->getType() != T)
  6289. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  6290. return;
  6291. }
  6292. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  6293. SourceLocation CC, QualType T) {
  6294. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  6295. bool Suspicious = false;
  6296. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  6297. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  6298. // If -Wconversion would have warned about either of the candidates
  6299. // for a signedness conversion to the context type...
  6300. if (!Suspicious) return;
  6301. // ...but it's currently ignored...
  6302. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  6303. return;
  6304. // ...then check whether it would have warned about either of the
  6305. // candidates for a signedness conversion to the condition type.
  6306. if (E->getType() == T) return;
  6307. Suspicious = false;
  6308. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  6309. E->getType(), CC, &Suspicious);
  6310. if (!Suspicious)
  6311. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  6312. E->getType(), CC, &Suspicious);
  6313. }
  6314. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  6315. /// Input argument E is a logical expression.
  6316. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  6317. if (S.getLangOpts().Bool)
  6318. return;
  6319. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  6320. }
  6321. /// AnalyzeImplicitConversions - Find and report any interesting
  6322. /// implicit conversions in the given expression. There are a couple
  6323. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  6324. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  6325. QualType T = OrigE->getType();
  6326. Expr *E = OrigE->IgnoreParenImpCasts();
  6327. if (E->isTypeDependent() || E->isValueDependent())
  6328. return;
  6329. // For conditional operators, we analyze the arguments as if they
  6330. // were being fed directly into the output.
  6331. if (isa<ConditionalOperator>(E)) {
  6332. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  6333. CheckConditionalOperator(S, CO, CC, T);
  6334. return;
  6335. }
  6336. // Check implicit argument conversions for function calls.
  6337. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  6338. CheckImplicitArgumentConversions(S, Call, CC);
  6339. // Go ahead and check any implicit conversions we might have skipped.
  6340. // The non-canonical typecheck is just an optimization;
  6341. // CheckImplicitConversion will filter out dead implicit conversions.
  6342. if (E->getType() != T)
  6343. CheckImplicitConversion(S, E, T, CC);
  6344. // Now continue drilling into this expression.
  6345. if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
  6346. if (POE->getResultExpr())
  6347. E = POE->getResultExpr();
  6348. }
  6349. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  6350. if (OVE->getSourceExpr())
  6351. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  6352. return;
  6353. }
  6354. // Skip past explicit casts.
  6355. if (isa<ExplicitCastExpr>(E)) {
  6356. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  6357. return AnalyzeImplicitConversions(S, E, CC);
  6358. }
  6359. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  6360. // Do a somewhat different check with comparison operators.
  6361. if (BO->isComparisonOp())
  6362. return AnalyzeComparison(S, BO);
  6363. // And with simple assignments.
  6364. if (BO->getOpcode() == BO_Assign)
  6365. return AnalyzeAssignment(S, BO);
  6366. }
  6367. // These break the otherwise-useful invariant below. Fortunately,
  6368. // we don't really need to recurse into them, because any internal
  6369. // expressions should have been analyzed already when they were
  6370. // built into statements.
  6371. if (isa<StmtExpr>(E)) return;
  6372. // Don't descend into unevaluated contexts.
  6373. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  6374. // Now just recurse over the expression's children.
  6375. CC = E->getExprLoc();
  6376. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  6377. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  6378. for (Stmt *SubStmt : E->children()) {
  6379. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  6380. if (!ChildExpr)
  6381. continue;
  6382. if (IsLogicalAndOperator &&
  6383. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  6384. // Ignore checking string literals that are in logical and operators.
  6385. // This is a common pattern for asserts.
  6386. continue;
  6387. AnalyzeImplicitConversions(S, ChildExpr, CC);
  6388. }
  6389. if (BO && BO->isLogicalOp()) {
  6390. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  6391. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  6392. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  6393. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  6394. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  6395. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  6396. }
  6397. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
  6398. if (U->getOpcode() == UO_LNot)
  6399. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  6400. }
  6401. } // end anonymous namespace
  6402. enum {
  6403. AddressOf,
  6404. FunctionPointer,
  6405. ArrayPointer
  6406. };
  6407. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  6408. // Returns true when emitting a warning about taking the address of a reference.
  6409. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  6410. PartialDiagnostic PD) {
  6411. E = E->IgnoreParenImpCasts();
  6412. const FunctionDecl *FD = nullptr;
  6413. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  6414. if (!DRE->getDecl()->getType()->isReferenceType())
  6415. return false;
  6416. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  6417. if (!M->getMemberDecl()->getType()->isReferenceType())
  6418. return false;
  6419. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  6420. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  6421. return false;
  6422. FD = Call->getDirectCallee();
  6423. } else {
  6424. return false;
  6425. }
  6426. SemaRef.Diag(E->getExprLoc(), PD);
  6427. // If possible, point to location of function.
  6428. if (FD) {
  6429. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  6430. }
  6431. return true;
  6432. }
  6433. // Returns true if the SourceLocation is expanded from any macro body.
  6434. // Returns false if the SourceLocation is invalid, is from not in a macro
  6435. // expansion, or is from expanded from a top-level macro argument.
  6436. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  6437. if (Loc.isInvalid())
  6438. return false;
  6439. while (Loc.isMacroID()) {
  6440. if (SM.isMacroBodyExpansion(Loc))
  6441. return true;
  6442. Loc = SM.getImmediateMacroCallerLoc(Loc);
  6443. }
  6444. return false;
  6445. }
  6446. /// \brief Diagnose pointers that are always non-null.
  6447. /// \param E the expression containing the pointer
  6448. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  6449. /// compared to a null pointer
  6450. /// \param IsEqual True when the comparison is equal to a null pointer
  6451. /// \param Range Extra SourceRange to highlight in the diagnostic
  6452. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  6453. Expr::NullPointerConstantKind NullKind,
  6454. bool IsEqual, SourceRange Range) {
  6455. if (!E)
  6456. return;
  6457. // Don't warn inside macros.
  6458. if (E->getExprLoc().isMacroID()) {
  6459. const SourceManager &SM = getSourceManager();
  6460. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  6461. IsInAnyMacroBody(SM, Range.getBegin()))
  6462. return;
  6463. }
  6464. E = E->IgnoreImpCasts();
  6465. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  6466. if (isa<CXXThisExpr>(E)) {
  6467. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  6468. : diag::warn_this_bool_conversion;
  6469. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  6470. return;
  6471. }
  6472. bool IsAddressOf = false;
  6473. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  6474. if (UO->getOpcode() != UO_AddrOf)
  6475. return;
  6476. IsAddressOf = true;
  6477. E = UO->getSubExpr();
  6478. }
  6479. if (IsAddressOf) {
  6480. unsigned DiagID = IsCompare
  6481. ? diag::warn_address_of_reference_null_compare
  6482. : diag::warn_address_of_reference_bool_conversion;
  6483. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  6484. << IsEqual;
  6485. if (CheckForReference(*this, E, PD)) {
  6486. return;
  6487. }
  6488. }
  6489. // Expect to find a single Decl. Skip anything more complicated.
  6490. ValueDecl *D = nullptr;
  6491. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  6492. D = R->getDecl();
  6493. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  6494. D = M->getMemberDecl();
  6495. }
  6496. // Weak Decls can be null.
  6497. if (!D || D->isWeak())
  6498. return;
  6499. // Check for parameter decl with nonnull attribute
  6500. if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
  6501. if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
  6502. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  6503. unsigned NumArgs = FD->getNumParams();
  6504. llvm::SmallBitVector AttrNonNull(NumArgs);
  6505. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  6506. if (!NonNull->args_size()) {
  6507. AttrNonNull.set(0, NumArgs);
  6508. break;
  6509. }
  6510. for (unsigned Val : NonNull->args()) {
  6511. if (Val >= NumArgs)
  6512. continue;
  6513. AttrNonNull.set(Val);
  6514. }
  6515. }
  6516. if (!AttrNonNull.empty())
  6517. for (unsigned i = 0; i < NumArgs; ++i)
  6518. if (FD->getParamDecl(i) == PV &&
  6519. (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
  6520. std::string Str;
  6521. llvm::raw_string_ostream S(Str);
  6522. E->printPretty(S, nullptr, getPrintingPolicy());
  6523. unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
  6524. : diag::warn_cast_nonnull_to_bool;
  6525. Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
  6526. << Range << IsEqual;
  6527. return;
  6528. }
  6529. }
  6530. }
  6531. QualType T = D->getType();
  6532. const bool IsArray = T->isArrayType();
  6533. const bool IsFunction = T->isFunctionType();
  6534. // Address of function is used to silence the function warning.
  6535. if (IsAddressOf && IsFunction) {
  6536. return;
  6537. }
  6538. // Found nothing.
  6539. if (!IsAddressOf && !IsFunction && !IsArray)
  6540. return;
  6541. // Pretty print the expression for the diagnostic.
  6542. std::string Str;
  6543. llvm::raw_string_ostream S(Str);
  6544. E->printPretty(S, nullptr, getPrintingPolicy());
  6545. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  6546. : diag::warn_impcast_pointer_to_bool;
  6547. unsigned DiagType;
  6548. if (IsAddressOf)
  6549. DiagType = AddressOf;
  6550. else if (IsFunction)
  6551. DiagType = FunctionPointer;
  6552. else if (IsArray)
  6553. DiagType = ArrayPointer;
  6554. else
  6555. llvm_unreachable("Could not determine diagnostic.");
  6556. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  6557. << Range << IsEqual;
  6558. if (!IsFunction)
  6559. return;
  6560. // Suggest '&' to silence the function warning.
  6561. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  6562. << FixItHint::CreateInsertion(E->getLocStart(), "&");
  6563. // Check to see if '()' fixit should be emitted.
  6564. QualType ReturnType;
  6565. UnresolvedSet<4> NonTemplateOverloads;
  6566. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  6567. if (ReturnType.isNull())
  6568. return;
  6569. if (IsCompare) {
  6570. // There are two cases here. If there is null constant, the only suggest
  6571. // for a pointer return type. If the null is 0, then suggest if the return
  6572. // type is a pointer or an integer type.
  6573. if (!ReturnType->isPointerType()) {
  6574. if (NullKind == Expr::NPCK_ZeroExpression ||
  6575. NullKind == Expr::NPCK_ZeroLiteral) {
  6576. if (!ReturnType->isIntegerType())
  6577. return;
  6578. } else {
  6579. return;
  6580. }
  6581. }
  6582. } else { // !IsCompare
  6583. // For function to bool, only suggest if the function pointer has bool
  6584. // return type.
  6585. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  6586. return;
  6587. }
  6588. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  6589. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
  6590. }
  6591. /// Diagnoses "dangerous" implicit conversions within the given
  6592. /// expression (which is a full expression). Implements -Wconversion
  6593. /// and -Wsign-compare.
  6594. ///
  6595. /// \param CC the "context" location of the implicit conversion, i.e.
  6596. /// the most location of the syntactic entity requiring the implicit
  6597. /// conversion
  6598. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  6599. // Don't diagnose in unevaluated contexts.
  6600. if (isUnevaluatedContext())
  6601. return;
  6602. // Don't diagnose for value- or type-dependent expressions.
  6603. if (E->isTypeDependent() || E->isValueDependent())
  6604. return;
  6605. // Check for array bounds violations in cases where the check isn't triggered
  6606. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  6607. // ArraySubscriptExpr is on the RHS of a variable initialization.
  6608. CheckArrayAccess(E);
  6609. // This is not the right CC for (e.g.) a variable initialization.
  6610. AnalyzeImplicitConversions(*this, E, CC);
  6611. }
  6612. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  6613. /// Input argument E is a logical expression.
  6614. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  6615. ::CheckBoolLikeConversion(*this, E, CC);
  6616. }
  6617. /// Diagnose when expression is an integer constant expression and its evaluation
  6618. /// results in integer overflow
  6619. void Sema::CheckForIntOverflow (Expr *E) {
  6620. if (isa<BinaryOperator>(E->IgnoreParenCasts()))
  6621. E->IgnoreParenCasts()->EvaluateForOverflow(Context);
  6622. }
  6623. namespace {
  6624. /// \brief Visitor for expressions which looks for unsequenced operations on the
  6625. /// same object.
  6626. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  6627. typedef EvaluatedExprVisitor<SequenceChecker> Base;
  6628. /// \brief A tree of sequenced regions within an expression. Two regions are
  6629. /// unsequenced if one is an ancestor or a descendent of the other. When we
  6630. /// finish processing an expression with sequencing, such as a comma
  6631. /// expression, we fold its tree nodes into its parent, since they are
  6632. /// unsequenced with respect to nodes we will visit later.
  6633. class SequenceTree {
  6634. struct Value {
  6635. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  6636. unsigned Parent : 31;
  6637. bool Merged : 1;
  6638. };
  6639. SmallVector<Value, 8> Values;
  6640. public:
  6641. /// \brief A region within an expression which may be sequenced with respect
  6642. /// to some other region.
  6643. class Seq {
  6644. explicit Seq(unsigned N) : Index(N) {}
  6645. unsigned Index;
  6646. friend class SequenceTree;
  6647. public:
  6648. Seq() : Index(0) {}
  6649. };
  6650. SequenceTree() { Values.push_back(Value(0)); }
  6651. Seq root() const { return Seq(0); }
  6652. /// \brief Create a new sequence of operations, which is an unsequenced
  6653. /// subset of \p Parent. This sequence of operations is sequenced with
  6654. /// respect to other children of \p Parent.
  6655. Seq allocate(Seq Parent) {
  6656. Values.push_back(Value(Parent.Index));
  6657. return Seq(Values.size() - 1);
  6658. }
  6659. /// \brief Merge a sequence of operations into its parent.
  6660. void merge(Seq S) {
  6661. Values[S.Index].Merged = true;
  6662. }
  6663. /// \brief Determine whether two operations are unsequenced. This operation
  6664. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  6665. /// should have been merged into its parent as appropriate.
  6666. bool isUnsequenced(Seq Cur, Seq Old) {
  6667. unsigned C = representative(Cur.Index);
  6668. unsigned Target = representative(Old.Index);
  6669. while (C >= Target) {
  6670. if (C == Target)
  6671. return true;
  6672. C = Values[C].Parent;
  6673. }
  6674. return false;
  6675. }
  6676. private:
  6677. /// \brief Pick a representative for a sequence.
  6678. unsigned representative(unsigned K) {
  6679. if (Values[K].Merged)
  6680. // Perform path compression as we go.
  6681. return Values[K].Parent = representative(Values[K].Parent);
  6682. return K;
  6683. }
  6684. };
  6685. /// An object for which we can track unsequenced uses.
  6686. typedef NamedDecl *Object;
  6687. /// Different flavors of object usage which we track. We only track the
  6688. /// least-sequenced usage of each kind.
  6689. enum UsageKind {
  6690. /// A read of an object. Multiple unsequenced reads are OK.
  6691. UK_Use,
  6692. /// A modification of an object which is sequenced before the value
  6693. /// computation of the expression, such as ++n in C++.
  6694. UK_ModAsValue,
  6695. /// A modification of an object which is not sequenced before the value
  6696. /// computation of the expression, such as n++.
  6697. UK_ModAsSideEffect,
  6698. UK_Count = UK_ModAsSideEffect + 1
  6699. };
  6700. struct Usage {
  6701. Usage() : Use(nullptr), Seq() {}
  6702. Expr *Use;
  6703. SequenceTree::Seq Seq;
  6704. };
  6705. struct UsageInfo {
  6706. UsageInfo() : Diagnosed(false) {}
  6707. Usage Uses[UK_Count];
  6708. /// Have we issued a diagnostic for this variable already?
  6709. bool Diagnosed;
  6710. };
  6711. typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
  6712. Sema &SemaRef;
  6713. /// Sequenced regions within the expression.
  6714. SequenceTree Tree;
  6715. /// Declaration modifications and references which we have seen.
  6716. UsageInfoMap UsageMap;
  6717. /// The region we are currently within.
  6718. SequenceTree::Seq Region;
  6719. /// Filled in with declarations which were modified as a side-effect
  6720. /// (that is, post-increment operations).
  6721. SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
  6722. /// Expressions to check later. We defer checking these to reduce
  6723. /// stack usage.
  6724. SmallVectorImpl<Expr *> &WorkList;
  6725. /// RAII object wrapping the visitation of a sequenced subexpression of an
  6726. /// expression. At the end of this process, the side-effects of the evaluation
  6727. /// become sequenced with respect to the value computation of the result, so
  6728. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  6729. /// UK_ModAsValue.
  6730. struct SequencedSubexpression {
  6731. SequencedSubexpression(SequenceChecker &Self)
  6732. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  6733. Self.ModAsSideEffect = &ModAsSideEffect;
  6734. }
  6735. ~SequencedSubexpression() {
  6736. for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
  6737. MI != ME; ++MI) {
  6738. UsageInfo &U = Self.UsageMap[MI->first];
  6739. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  6740. Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
  6741. SideEffectUsage = MI->second;
  6742. }
  6743. Self.ModAsSideEffect = OldModAsSideEffect;
  6744. }
  6745. SequenceChecker &Self;
  6746. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  6747. SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
  6748. };
  6749. /// RAII object wrapping the visitation of a subexpression which we might
  6750. /// choose to evaluate as a constant. If any subexpression is evaluated and
  6751. /// found to be non-constant, this allows us to suppress the evaluation of
  6752. /// the outer expression.
  6753. class EvaluationTracker {
  6754. public:
  6755. EvaluationTracker(SequenceChecker &Self)
  6756. : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
  6757. Self.EvalTracker = this;
  6758. }
  6759. ~EvaluationTracker() {
  6760. Self.EvalTracker = Prev;
  6761. if (Prev)
  6762. Prev->EvalOK &= EvalOK;
  6763. }
  6764. bool evaluate(const Expr *E, bool &Result) {
  6765. if (!EvalOK || E->isValueDependent())
  6766. return false;
  6767. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  6768. return EvalOK;
  6769. }
  6770. private:
  6771. SequenceChecker &Self;
  6772. EvaluationTracker *Prev;
  6773. bool EvalOK;
  6774. } *EvalTracker;
  6775. /// \brief Find the object which is produced by the specified expression,
  6776. /// if any.
  6777. Object getObject(Expr *E, bool Mod) const {
  6778. E = E->IgnoreParenCasts();
  6779. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  6780. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  6781. return getObject(UO->getSubExpr(), Mod);
  6782. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  6783. if (BO->getOpcode() == BO_Comma)
  6784. return getObject(BO->getRHS(), Mod);
  6785. if (Mod && BO->isAssignmentOp())
  6786. return getObject(BO->getLHS(), Mod);
  6787. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  6788. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  6789. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  6790. return ME->getMemberDecl();
  6791. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6792. // FIXME: If this is a reference, map through to its value.
  6793. return DRE->getDecl();
  6794. return nullptr;
  6795. }
  6796. /// \brief Note that an object was modified or used by an expression.
  6797. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  6798. Usage &U = UI.Uses[UK];
  6799. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  6800. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  6801. ModAsSideEffect->push_back(std::make_pair(O, U));
  6802. U.Use = Ref;
  6803. U.Seq = Region;
  6804. }
  6805. }
  6806. /// \brief Check whether a modification or use conflicts with a prior usage.
  6807. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  6808. bool IsModMod) {
  6809. if (UI.Diagnosed)
  6810. return;
  6811. const Usage &U = UI.Uses[OtherKind];
  6812. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  6813. return;
  6814. Expr *Mod = U.Use;
  6815. Expr *ModOrUse = Ref;
  6816. if (OtherKind == UK_Use)
  6817. std::swap(Mod, ModOrUse);
  6818. SemaRef.Diag(Mod->getExprLoc(),
  6819. IsModMod ? diag::warn_unsequenced_mod_mod
  6820. : diag::warn_unsequenced_mod_use)
  6821. << O << SourceRange(ModOrUse->getExprLoc());
  6822. UI.Diagnosed = true;
  6823. }
  6824. void notePreUse(Object O, Expr *Use) {
  6825. UsageInfo &U = UsageMap[O];
  6826. // Uses conflict with other modifications.
  6827. checkUsage(O, U, Use, UK_ModAsValue, false);
  6828. }
  6829. void notePostUse(Object O, Expr *Use) {
  6830. UsageInfo &U = UsageMap[O];
  6831. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  6832. addUsage(U, O, Use, UK_Use);
  6833. }
  6834. void notePreMod(Object O, Expr *Mod) {
  6835. UsageInfo &U = UsageMap[O];
  6836. // Modifications conflict with other modifications and with uses.
  6837. checkUsage(O, U, Mod, UK_ModAsValue, true);
  6838. checkUsage(O, U, Mod, UK_Use, false);
  6839. }
  6840. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  6841. UsageInfo &U = UsageMap[O];
  6842. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  6843. addUsage(U, O, Use, UK);
  6844. }
  6845. public:
  6846. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  6847. : Base(S.Context), SemaRef(S), Region(Tree.root()),
  6848. ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
  6849. Visit(E);
  6850. }
  6851. void VisitStmt(Stmt *S) {
  6852. // Skip all statements which aren't expressions for now.
  6853. }
  6854. void VisitExpr(Expr *E) {
  6855. // By default, just recurse to evaluated subexpressions.
  6856. Base::VisitStmt(E);
  6857. }
  6858. void VisitCastExpr(CastExpr *E) {
  6859. Object O = Object();
  6860. if (E->getCastKind() == CK_LValueToRValue)
  6861. O = getObject(E->getSubExpr(), false);
  6862. if (O)
  6863. notePreUse(O, E);
  6864. VisitExpr(E);
  6865. if (O)
  6866. notePostUse(O, E);
  6867. }
  6868. void VisitBinComma(BinaryOperator *BO) {
  6869. // C++11 [expr.comma]p1:
  6870. // Every value computation and side effect associated with the left
  6871. // expression is sequenced before every value computation and side
  6872. // effect associated with the right expression.
  6873. SequenceTree::Seq LHS = Tree.allocate(Region);
  6874. SequenceTree::Seq RHS = Tree.allocate(Region);
  6875. SequenceTree::Seq OldRegion = Region;
  6876. {
  6877. SequencedSubexpression SeqLHS(*this);
  6878. Region = LHS;
  6879. Visit(BO->getLHS());
  6880. }
  6881. Region = RHS;
  6882. Visit(BO->getRHS());
  6883. Region = OldRegion;
  6884. // Forget that LHS and RHS are sequenced. They are both unsequenced
  6885. // with respect to other stuff.
  6886. Tree.merge(LHS);
  6887. Tree.merge(RHS);
  6888. }
  6889. void VisitBinAssign(BinaryOperator *BO) {
  6890. // The modification is sequenced after the value computation of the LHS
  6891. // and RHS, so check it before inspecting the operands and update the
  6892. // map afterwards.
  6893. Object O = getObject(BO->getLHS(), true);
  6894. if (!O)
  6895. return VisitExpr(BO);
  6896. notePreMod(O, BO);
  6897. // C++11 [expr.ass]p7:
  6898. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  6899. // only once.
  6900. //
  6901. // Therefore, for a compound assignment operator, O is considered used
  6902. // everywhere except within the evaluation of E1 itself.
  6903. if (isa<CompoundAssignOperator>(BO))
  6904. notePreUse(O, BO);
  6905. Visit(BO->getLHS());
  6906. if (isa<CompoundAssignOperator>(BO))
  6907. notePostUse(O, BO);
  6908. Visit(BO->getRHS());
  6909. // C++11 [expr.ass]p1:
  6910. // the assignment is sequenced [...] before the value computation of the
  6911. // assignment expression.
  6912. // C11 6.5.16/3 has no such rule.
  6913. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  6914. : UK_ModAsSideEffect);
  6915. }
  6916. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  6917. VisitBinAssign(CAO);
  6918. }
  6919. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  6920. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  6921. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  6922. Object O = getObject(UO->getSubExpr(), true);
  6923. if (!O)
  6924. return VisitExpr(UO);
  6925. notePreMod(O, UO);
  6926. Visit(UO->getSubExpr());
  6927. // C++11 [expr.pre.incr]p1:
  6928. // the expression ++x is equivalent to x+=1
  6929. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  6930. : UK_ModAsSideEffect);
  6931. }
  6932. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  6933. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  6934. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  6935. Object O = getObject(UO->getSubExpr(), true);
  6936. if (!O)
  6937. return VisitExpr(UO);
  6938. notePreMod(O, UO);
  6939. Visit(UO->getSubExpr());
  6940. notePostMod(O, UO, UK_ModAsSideEffect);
  6941. }
  6942. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  6943. void VisitBinLOr(BinaryOperator *BO) {
  6944. // The side-effects of the LHS of an '&&' are sequenced before the
  6945. // value computation of the RHS, and hence before the value computation
  6946. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  6947. // as if they were unconditionally sequenced.
  6948. EvaluationTracker Eval(*this);
  6949. {
  6950. SequencedSubexpression Sequenced(*this);
  6951. Visit(BO->getLHS());
  6952. }
  6953. bool Result;
  6954. if (Eval.evaluate(BO->getLHS(), Result)) {
  6955. if (!Result)
  6956. Visit(BO->getRHS());
  6957. } else {
  6958. // Check for unsequenced operations in the RHS, treating it as an
  6959. // entirely separate evaluation.
  6960. //
  6961. // FIXME: If there are operations in the RHS which are unsequenced
  6962. // with respect to operations outside the RHS, and those operations
  6963. // are unconditionally evaluated, diagnose them.
  6964. WorkList.push_back(BO->getRHS());
  6965. }
  6966. }
  6967. void VisitBinLAnd(BinaryOperator *BO) {
  6968. EvaluationTracker Eval(*this);
  6969. {
  6970. SequencedSubexpression Sequenced(*this);
  6971. Visit(BO->getLHS());
  6972. }
  6973. bool Result;
  6974. if (Eval.evaluate(BO->getLHS(), Result)) {
  6975. if (Result)
  6976. Visit(BO->getRHS());
  6977. } else {
  6978. WorkList.push_back(BO->getRHS());
  6979. }
  6980. }
  6981. // Only visit the condition, unless we can be sure which subexpression will
  6982. // be chosen.
  6983. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  6984. EvaluationTracker Eval(*this);
  6985. {
  6986. SequencedSubexpression Sequenced(*this);
  6987. Visit(CO->getCond());
  6988. }
  6989. bool Result;
  6990. if (Eval.evaluate(CO->getCond(), Result))
  6991. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  6992. else {
  6993. WorkList.push_back(CO->getTrueExpr());
  6994. WorkList.push_back(CO->getFalseExpr());
  6995. }
  6996. }
  6997. void VisitCallExpr(CallExpr *CE) {
  6998. // C++11 [intro.execution]p15:
  6999. // When calling a function [...], every value computation and side effect
  7000. // associated with any argument expression, or with the postfix expression
  7001. // designating the called function, is sequenced before execution of every
  7002. // expression or statement in the body of the function [and thus before
  7003. // the value computation of its result].
  7004. SequencedSubexpression Sequenced(*this);
  7005. Base::VisitCallExpr(CE);
  7006. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  7007. }
  7008. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  7009. // This is a call, so all subexpressions are sequenced before the result.
  7010. SequencedSubexpression Sequenced(*this);
  7011. if (!CCE->isListInitialization())
  7012. return VisitExpr(CCE);
  7013. // In C++11, list initializations are sequenced.
  7014. SmallVector<SequenceTree::Seq, 32> Elts;
  7015. SequenceTree::Seq Parent = Region;
  7016. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  7017. E = CCE->arg_end();
  7018. I != E; ++I) {
  7019. Region = Tree.allocate(Parent);
  7020. Elts.push_back(Region);
  7021. Visit(*I);
  7022. }
  7023. // Forget that the initializers are sequenced.
  7024. Region = Parent;
  7025. for (unsigned I = 0; I < Elts.size(); ++I)
  7026. Tree.merge(Elts[I]);
  7027. }
  7028. void VisitInitListExpr(InitListExpr *ILE) {
  7029. if (!SemaRef.getLangOpts().CPlusPlus11)
  7030. return VisitExpr(ILE);
  7031. // In C++11, list initializations are sequenced.
  7032. SmallVector<SequenceTree::Seq, 32> Elts;
  7033. SequenceTree::Seq Parent = Region;
  7034. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  7035. Expr *E = ILE->getInit(I);
  7036. if (!E) continue;
  7037. Region = Tree.allocate(Parent);
  7038. Elts.push_back(Region);
  7039. Visit(E);
  7040. }
  7041. // Forget that the initializers are sequenced.
  7042. Region = Parent;
  7043. for (unsigned I = 0; I < Elts.size(); ++I)
  7044. Tree.merge(Elts[I]);
  7045. }
  7046. };
  7047. }
  7048. void Sema::CheckUnsequencedOperations(Expr *E) {
  7049. SmallVector<Expr *, 8> WorkList;
  7050. WorkList.push_back(E);
  7051. while (!WorkList.empty()) {
  7052. Expr *Item = WorkList.pop_back_val();
  7053. SequenceChecker(*this, Item, WorkList);
  7054. }
  7055. }
  7056. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  7057. bool IsConstexpr) {
  7058. CheckImplicitConversions(E, CheckLoc);
  7059. CheckUnsequencedOperations(E);
  7060. if (!IsConstexpr && !E->isValueDependent())
  7061. CheckForIntOverflow(E);
  7062. }
  7063. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  7064. FieldDecl *BitField,
  7065. Expr *Init) {
  7066. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  7067. }
  7068. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  7069. SourceLocation Loc) {
  7070. if (!PType->isVariablyModifiedType())
  7071. return;
  7072. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  7073. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  7074. return;
  7075. }
  7076. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  7077. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  7078. return;
  7079. }
  7080. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  7081. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  7082. return;
  7083. }
  7084. const ArrayType *AT = S.Context.getAsArrayType(PType);
  7085. if (!AT)
  7086. return;
  7087. if (AT->getSizeModifier() != ArrayType::Star) {
  7088. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  7089. return;
  7090. }
  7091. S.Diag(Loc, diag::err_array_star_in_function_definition);
  7092. }
  7093. /// CheckParmsForFunctionDef - Check that the parameters of the given
  7094. /// function are appropriate for the definition of a function. This
  7095. /// takes care of any checks that cannot be performed on the
  7096. /// declaration itself, e.g., that the types of each of the function
  7097. /// parameters are complete.
  7098. bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
  7099. ParmVarDecl *const *PEnd,
  7100. bool CheckParameterNames) {
  7101. bool HasInvalidParm = false;
  7102. for (; P != PEnd; ++P) {
  7103. ParmVarDecl *Param = *P;
  7104. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  7105. // function declarator that is part of a function definition of
  7106. // that function shall not have incomplete type.
  7107. //
  7108. // This is also C++ [dcl.fct]p6.
  7109. if (!Param->isInvalidDecl() &&
  7110. RequireCompleteType(Param->getLocation(), Param->getType(),
  7111. diag::err_typecheck_decl_incomplete_type)) {
  7112. Param->setInvalidDecl();
  7113. HasInvalidParm = true;
  7114. }
  7115. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  7116. // declaration of each parameter shall include an identifier.
  7117. if (CheckParameterNames &&
  7118. Param->getIdentifier() == nullptr &&
  7119. !Param->isImplicit() &&
  7120. !getLangOpts().CPlusPlus)
  7121. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  7122. // C99 6.7.5.3p12:
  7123. // If the function declarator is not part of a definition of that
  7124. // function, parameters may have incomplete type and may use the [*]
  7125. // notation in their sequences of declarator specifiers to specify
  7126. // variable length array types.
  7127. QualType PType = Param->getOriginalType();
  7128. // FIXME: This diagnostic should point the '[*]' if source-location
  7129. // information is added for it.
  7130. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  7131. // MSVC destroys objects passed by value in the callee. Therefore a
  7132. // function definition which takes such a parameter must be able to call the
  7133. // object's destructor. However, we don't perform any direct access check
  7134. // on the dtor.
  7135. if (getLangOpts().CPlusPlus && Context.getTargetInfo()
  7136. .getCXXABI()
  7137. .areArgsDestroyedLeftToRightInCallee()) {
  7138. if (!Param->isInvalidDecl()) {
  7139. if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
  7140. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  7141. if (!ClassDecl->isInvalidDecl() &&
  7142. !ClassDecl->hasIrrelevantDestructor() &&
  7143. !ClassDecl->isDependentContext()) {
  7144. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  7145. MarkFunctionReferenced(Param->getLocation(), Destructor);
  7146. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  7147. }
  7148. }
  7149. }
  7150. }
  7151. }
  7152. return HasInvalidParm;
  7153. }
  7154. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  7155. /// pointer cast increases the alignment requirements.
  7156. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  7157. // This is actually a lot of work to potentially be doing on every
  7158. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  7159. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  7160. return;
  7161. // Ignore dependent types.
  7162. if (T->isDependentType() || Op->getType()->isDependentType())
  7163. return;
  7164. // Require that the destination be a pointer type.
  7165. const PointerType *DestPtr = T->getAs<PointerType>();
  7166. if (!DestPtr) return;
  7167. // If the destination has alignment 1, we're done.
  7168. QualType DestPointee = DestPtr->getPointeeType();
  7169. if (DestPointee->isIncompleteType()) return;
  7170. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  7171. if (DestAlign.isOne()) return;
  7172. // Require that the source be a pointer type.
  7173. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  7174. if (!SrcPtr) return;
  7175. QualType SrcPointee = SrcPtr->getPointeeType();
  7176. // Whitelist casts from cv void*. We already implicitly
  7177. // whitelisted casts to cv void*, since they have alignment 1.
  7178. // Also whitelist casts involving incomplete types, which implicitly
  7179. // includes 'void'.
  7180. if (SrcPointee->isIncompleteType()) return;
  7181. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  7182. if (SrcAlign >= DestAlign) return;
  7183. Diag(TRange.getBegin(), diag::warn_cast_align)
  7184. << Op->getType() << T
  7185. << static_cast<unsigned>(SrcAlign.getQuantity())
  7186. << static_cast<unsigned>(DestAlign.getQuantity())
  7187. << TRange << Op->getSourceRange();
  7188. }
  7189. static const Type* getElementType(const Expr *BaseExpr) {
  7190. const Type* EltType = BaseExpr->getType().getTypePtr();
  7191. if (EltType->isAnyPointerType())
  7192. return EltType->getPointeeType().getTypePtr();
  7193. else if (EltType->isArrayType())
  7194. return EltType->getBaseElementTypeUnsafe();
  7195. return EltType;
  7196. }
  7197. /// \brief Check whether this array fits the idiom of a size-one tail padded
  7198. /// array member of a struct.
  7199. ///
  7200. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  7201. /// commonly used to emulate flexible arrays in C89 code.
  7202. static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
  7203. const NamedDecl *ND) {
  7204. if (Size != 1 || !ND) return false;
  7205. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  7206. if (!FD) return false;
  7207. // Don't consider sizes resulting from macro expansions or template argument
  7208. // substitution to form C89 tail-padded arrays.
  7209. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  7210. while (TInfo) {
  7211. TypeLoc TL = TInfo->getTypeLoc();
  7212. // Look through typedefs.
  7213. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  7214. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  7215. TInfo = TDL->getTypeSourceInfo();
  7216. continue;
  7217. }
  7218. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  7219. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  7220. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  7221. return false;
  7222. }
  7223. break;
  7224. }
  7225. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  7226. if (!RD) return false;
  7227. if (RD->isUnion()) return false;
  7228. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  7229. if (!CRD->isStandardLayout()) return false;
  7230. }
  7231. // See if this is the last field decl in the record.
  7232. const Decl *D = FD;
  7233. while ((D = D->getNextDeclInContext()))
  7234. if (isa<FieldDecl>(D))
  7235. return false;
  7236. return true;
  7237. }
  7238. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  7239. const ArraySubscriptExpr *ASE,
  7240. bool AllowOnePastEnd, bool IndexNegated) {
  7241. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  7242. if (IndexExpr->isValueDependent())
  7243. return;
  7244. const Type *EffectiveType = getElementType(BaseExpr);
  7245. BaseExpr = BaseExpr->IgnoreParenCasts();
  7246. const ConstantArrayType *ArrayTy =
  7247. Context.getAsConstantArrayType(BaseExpr->getType());
  7248. if (!ArrayTy)
  7249. return;
  7250. llvm::APSInt index;
  7251. if (!IndexExpr->EvaluateAsInt(index, Context))
  7252. return;
  7253. if (IndexNegated)
  7254. index = -index;
  7255. const NamedDecl *ND = nullptr;
  7256. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  7257. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  7258. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  7259. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  7260. if (index.isUnsigned() || !index.isNegative()) {
  7261. llvm::APInt size = ArrayTy->getSize();
  7262. if (!size.isStrictlyPositive())
  7263. return;
  7264. const Type* BaseType = getElementType(BaseExpr);
  7265. if (BaseType != EffectiveType) {
  7266. // Make sure we're comparing apples to apples when comparing index to size
  7267. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  7268. uint64_t array_typesize = Context.getTypeSize(BaseType);
  7269. // Handle ptrarith_typesize being zero, such as when casting to void*
  7270. if (!ptrarith_typesize) ptrarith_typesize = 1;
  7271. if (ptrarith_typesize != array_typesize) {
  7272. // There's a cast to a different size type involved
  7273. uint64_t ratio = array_typesize / ptrarith_typesize;
  7274. // TODO: Be smarter about handling cases where array_typesize is not a
  7275. // multiple of ptrarith_typesize
  7276. if (ptrarith_typesize * ratio == array_typesize)
  7277. size *= llvm::APInt(size.getBitWidth(), ratio);
  7278. }
  7279. }
  7280. if (size.getBitWidth() > index.getBitWidth())
  7281. index = index.zext(size.getBitWidth());
  7282. else if (size.getBitWidth() < index.getBitWidth())
  7283. size = size.zext(index.getBitWidth());
  7284. // For array subscripting the index must be less than size, but for pointer
  7285. // arithmetic also allow the index (offset) to be equal to size since
  7286. // computing the next address after the end of the array is legal and
  7287. // commonly done e.g. in C++ iterators and range-based for loops.
  7288. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  7289. return;
  7290. // Also don't warn for arrays of size 1 which are members of some
  7291. // structure. These are often used to approximate flexible arrays in C89
  7292. // code.
  7293. if (IsTailPaddedMemberArray(*this, size, ND))
  7294. return;
  7295. // Suppress the warning if the subscript expression (as identified by the
  7296. // ']' location) and the index expression are both from macro expansions
  7297. // within a system header.
  7298. if (ASE) {
  7299. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  7300. ASE->getRBracketLoc());
  7301. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  7302. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  7303. IndexExpr->getLocStart());
  7304. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  7305. return;
  7306. }
  7307. }
  7308. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  7309. if (ASE)
  7310. DiagID = diag::warn_array_index_exceeds_bounds;
  7311. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  7312. PDiag(DiagID) << index.toString(10, true)
  7313. << size.toString(10, true)
  7314. << (unsigned)size.getLimitedValue(~0U)
  7315. << IndexExpr->getSourceRange());
  7316. } else {
  7317. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  7318. if (!ASE) {
  7319. DiagID = diag::warn_ptr_arith_precedes_bounds;
  7320. if (index.isNegative()) index = -index;
  7321. }
  7322. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  7323. PDiag(DiagID) << index.toString(10, true)
  7324. << IndexExpr->getSourceRange());
  7325. }
  7326. if (!ND) {
  7327. // Try harder to find a NamedDecl to point at in the note.
  7328. while (const ArraySubscriptExpr *ASE =
  7329. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  7330. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  7331. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  7332. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  7333. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  7334. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  7335. }
  7336. if (ND)
  7337. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  7338. PDiag(diag::note_array_index_out_of_bounds)
  7339. << ND->getDeclName());
  7340. }
  7341. void Sema::CheckArrayAccess(const Expr *expr) {
  7342. int AllowOnePastEnd = 0;
  7343. while (expr) {
  7344. expr = expr->IgnoreParenImpCasts();
  7345. switch (expr->getStmtClass()) {
  7346. case Stmt::ArraySubscriptExprClass: {
  7347. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  7348. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  7349. AllowOnePastEnd > 0);
  7350. return;
  7351. }
  7352. case Stmt::UnaryOperatorClass: {
  7353. // Only unwrap the * and & unary operators
  7354. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  7355. expr = UO->getSubExpr();
  7356. switch (UO->getOpcode()) {
  7357. case UO_AddrOf:
  7358. AllowOnePastEnd++;
  7359. break;
  7360. case UO_Deref:
  7361. AllowOnePastEnd--;
  7362. break;
  7363. default:
  7364. return;
  7365. }
  7366. break;
  7367. }
  7368. case Stmt::ConditionalOperatorClass: {
  7369. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  7370. if (const Expr *lhs = cond->getLHS())
  7371. CheckArrayAccess(lhs);
  7372. if (const Expr *rhs = cond->getRHS())
  7373. CheckArrayAccess(rhs);
  7374. return;
  7375. }
  7376. default:
  7377. return;
  7378. }
  7379. }
  7380. }
  7381. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  7382. namespace {
  7383. struct RetainCycleOwner {
  7384. RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
  7385. VarDecl *Variable;
  7386. SourceRange Range;
  7387. SourceLocation Loc;
  7388. bool Indirect;
  7389. void setLocsFrom(Expr *e) {
  7390. Loc = e->getExprLoc();
  7391. Range = e->getSourceRange();
  7392. }
  7393. };
  7394. }
  7395. /// Consider whether capturing the given variable can possibly lead to
  7396. /// a retain cycle.
  7397. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  7398. // In ARC, it's captured strongly iff the variable has __strong
  7399. // lifetime. In MRR, it's captured strongly if the variable is
  7400. // __block and has an appropriate type.
  7401. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  7402. return false;
  7403. owner.Variable = var;
  7404. if (ref)
  7405. owner.setLocsFrom(ref);
  7406. return true;
  7407. }
  7408. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  7409. while (true) {
  7410. e = e->IgnoreParens();
  7411. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  7412. switch (cast->getCastKind()) {
  7413. case CK_BitCast:
  7414. case CK_LValueBitCast:
  7415. case CK_LValueToRValue:
  7416. case CK_ARCReclaimReturnedObject:
  7417. e = cast->getSubExpr();
  7418. continue;
  7419. default:
  7420. return false;
  7421. }
  7422. }
  7423. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  7424. ObjCIvarDecl *ivar = ref->getDecl();
  7425. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  7426. return false;
  7427. // Try to find a retain cycle in the base.
  7428. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  7429. return false;
  7430. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  7431. owner.Indirect = true;
  7432. return true;
  7433. }
  7434. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  7435. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  7436. if (!var) return false;
  7437. return considerVariable(var, ref, owner);
  7438. }
  7439. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  7440. if (member->isArrow()) return false;
  7441. // Don't count this as an indirect ownership.
  7442. e = member->getBase();
  7443. continue;
  7444. }
  7445. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  7446. // Only pay attention to pseudo-objects on property references.
  7447. ObjCPropertyRefExpr *pre
  7448. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  7449. ->IgnoreParens());
  7450. if (!pre) return false;
  7451. if (pre->isImplicitProperty()) return false;
  7452. ObjCPropertyDecl *property = pre->getExplicitProperty();
  7453. if (!property->isRetaining() &&
  7454. !(property->getPropertyIvarDecl() &&
  7455. property->getPropertyIvarDecl()->getType()
  7456. .getObjCLifetime() == Qualifiers::OCL_Strong))
  7457. return false;
  7458. owner.Indirect = true;
  7459. if (pre->isSuperReceiver()) {
  7460. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  7461. if (!owner.Variable)
  7462. return false;
  7463. owner.Loc = pre->getLocation();
  7464. owner.Range = pre->getSourceRange();
  7465. return true;
  7466. }
  7467. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  7468. ->getSourceExpr());
  7469. continue;
  7470. }
  7471. // Array ivars?
  7472. return false;
  7473. }
  7474. }
  7475. namespace {
  7476. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  7477. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  7478. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  7479. Context(Context), Variable(variable), Capturer(nullptr),
  7480. VarWillBeReased(false) {}
  7481. ASTContext &Context;
  7482. VarDecl *Variable;
  7483. Expr *Capturer;
  7484. bool VarWillBeReased;
  7485. void VisitDeclRefExpr(DeclRefExpr *ref) {
  7486. if (ref->getDecl() == Variable && !Capturer)
  7487. Capturer = ref;
  7488. }
  7489. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  7490. if (Capturer) return;
  7491. Visit(ref->getBase());
  7492. if (Capturer && ref->isFreeIvar())
  7493. Capturer = ref;
  7494. }
  7495. void VisitBlockExpr(BlockExpr *block) {
  7496. // Look inside nested blocks
  7497. if (block->getBlockDecl()->capturesVariable(Variable))
  7498. Visit(block->getBlockDecl()->getBody());
  7499. }
  7500. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  7501. if (Capturer) return;
  7502. if (OVE->getSourceExpr())
  7503. Visit(OVE->getSourceExpr());
  7504. }
  7505. void VisitBinaryOperator(BinaryOperator *BinOp) {
  7506. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  7507. return;
  7508. Expr *LHS = BinOp->getLHS();
  7509. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  7510. if (DRE->getDecl() != Variable)
  7511. return;
  7512. if (Expr *RHS = BinOp->getRHS()) {
  7513. RHS = RHS->IgnoreParenCasts();
  7514. llvm::APSInt Value;
  7515. VarWillBeReased =
  7516. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  7517. }
  7518. }
  7519. }
  7520. };
  7521. }
  7522. /// Check whether the given argument is a block which captures a
  7523. /// variable.
  7524. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  7525. assert(owner.Variable && owner.Loc.isValid());
  7526. e = e->IgnoreParenCasts();
  7527. // Look through [^{...} copy] and Block_copy(^{...}).
  7528. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  7529. Selector Cmd = ME->getSelector();
  7530. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  7531. e = ME->getInstanceReceiver();
  7532. if (!e)
  7533. return nullptr;
  7534. e = e->IgnoreParenCasts();
  7535. }
  7536. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  7537. if (CE->getNumArgs() == 1) {
  7538. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  7539. if (Fn) {
  7540. const IdentifierInfo *FnI = Fn->getIdentifier();
  7541. if (FnI && FnI->isStr("_Block_copy")) {
  7542. e = CE->getArg(0)->IgnoreParenCasts();
  7543. }
  7544. }
  7545. }
  7546. }
  7547. BlockExpr *block = dyn_cast<BlockExpr>(e);
  7548. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  7549. return nullptr;
  7550. FindCaptureVisitor visitor(S.Context, owner.Variable);
  7551. visitor.Visit(block->getBlockDecl()->getBody());
  7552. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  7553. }
  7554. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  7555. RetainCycleOwner &owner) {
  7556. assert(capturer);
  7557. assert(owner.Variable && owner.Loc.isValid());
  7558. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  7559. << owner.Variable << capturer->getSourceRange();
  7560. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  7561. << owner.Indirect << owner.Range;
  7562. }
  7563. /// Check for a keyword selector that starts with the word 'add' or
  7564. /// 'set'.
  7565. static bool isSetterLikeSelector(Selector sel) {
  7566. if (sel.isUnarySelector()) return false;
  7567. StringRef str = sel.getNameForSlot(0);
  7568. while (!str.empty() && str.front() == '_') str = str.substr(1);
  7569. if (str.startswith("set"))
  7570. str = str.substr(3);
  7571. else if (str.startswith("add")) {
  7572. // Specially whitelist 'addOperationWithBlock:'.
  7573. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  7574. return false;
  7575. str = str.substr(3);
  7576. }
  7577. else
  7578. return false;
  7579. if (str.empty()) return true;
  7580. return !isLowercase(str.front());
  7581. }
  7582. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  7583. ObjCMessageExpr *Message) {
  7584. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  7585. Message->getReceiverInterface(),
  7586. NSAPI::ClassId_NSMutableArray);
  7587. if (!IsMutableArray) {
  7588. return None;
  7589. }
  7590. Selector Sel = Message->getSelector();
  7591. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  7592. S.NSAPIObj->getNSArrayMethodKind(Sel);
  7593. if (!MKOpt) {
  7594. return None;
  7595. }
  7596. NSAPI::NSArrayMethodKind MK = *MKOpt;
  7597. switch (MK) {
  7598. case NSAPI::NSMutableArr_addObject:
  7599. case NSAPI::NSMutableArr_insertObjectAtIndex:
  7600. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  7601. return 0;
  7602. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  7603. return 1;
  7604. default:
  7605. return None;
  7606. }
  7607. return None;
  7608. }
  7609. static
  7610. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  7611. ObjCMessageExpr *Message) {
  7612. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  7613. Message->getReceiverInterface(),
  7614. NSAPI::ClassId_NSMutableDictionary);
  7615. if (!IsMutableDictionary) {
  7616. return None;
  7617. }
  7618. Selector Sel = Message->getSelector();
  7619. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  7620. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  7621. if (!MKOpt) {
  7622. return None;
  7623. }
  7624. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  7625. switch (MK) {
  7626. case NSAPI::NSMutableDict_setObjectForKey:
  7627. case NSAPI::NSMutableDict_setValueForKey:
  7628. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  7629. return 0;
  7630. default:
  7631. return None;
  7632. }
  7633. return None;
  7634. }
  7635. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  7636. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  7637. Message->getReceiverInterface(),
  7638. NSAPI::ClassId_NSMutableSet);
  7639. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  7640. Message->getReceiverInterface(),
  7641. NSAPI::ClassId_NSMutableOrderedSet);
  7642. if (!IsMutableSet && !IsMutableOrderedSet) {
  7643. return None;
  7644. }
  7645. Selector Sel = Message->getSelector();
  7646. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  7647. if (!MKOpt) {
  7648. return None;
  7649. }
  7650. NSAPI::NSSetMethodKind MK = *MKOpt;
  7651. switch (MK) {
  7652. case NSAPI::NSMutableSet_addObject:
  7653. case NSAPI::NSOrderedSet_setObjectAtIndex:
  7654. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  7655. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  7656. return 0;
  7657. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  7658. return 1;
  7659. }
  7660. return None;
  7661. }
  7662. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  7663. if (!Message->isInstanceMessage()) {
  7664. return;
  7665. }
  7666. Optional<int> ArgOpt;
  7667. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  7668. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  7669. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  7670. return;
  7671. }
  7672. int ArgIndex = *ArgOpt;
  7673. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  7674. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  7675. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  7676. }
  7677. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  7678. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  7679. if (ArgRE->isObjCSelfExpr()) {
  7680. Diag(Message->getSourceRange().getBegin(),
  7681. diag::warn_objc_circular_container)
  7682. << ArgRE->getDecl()->getName() << StringRef("super");
  7683. }
  7684. }
  7685. } else {
  7686. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  7687. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  7688. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  7689. }
  7690. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  7691. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  7692. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  7693. ValueDecl *Decl = ReceiverRE->getDecl();
  7694. Diag(Message->getSourceRange().getBegin(),
  7695. diag::warn_objc_circular_container)
  7696. << Decl->getName() << Decl->getName();
  7697. if (!ArgRE->isObjCSelfExpr()) {
  7698. Diag(Decl->getLocation(),
  7699. diag::note_objc_circular_container_declared_here)
  7700. << Decl->getName();
  7701. }
  7702. }
  7703. }
  7704. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  7705. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  7706. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  7707. ObjCIvarDecl *Decl = IvarRE->getDecl();
  7708. Diag(Message->getSourceRange().getBegin(),
  7709. diag::warn_objc_circular_container)
  7710. << Decl->getName() << Decl->getName();
  7711. Diag(Decl->getLocation(),
  7712. diag::note_objc_circular_container_declared_here)
  7713. << Decl->getName();
  7714. }
  7715. }
  7716. }
  7717. }
  7718. }
  7719. /// Check a message send to see if it's likely to cause a retain cycle.
  7720. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  7721. // Only check instance methods whose selector looks like a setter.
  7722. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  7723. return;
  7724. // Try to find a variable that the receiver is strongly owned by.
  7725. RetainCycleOwner owner;
  7726. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  7727. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  7728. return;
  7729. } else {
  7730. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  7731. owner.Variable = getCurMethodDecl()->getSelfDecl();
  7732. owner.Loc = msg->getSuperLoc();
  7733. owner.Range = msg->getSuperLoc();
  7734. }
  7735. // Check whether the receiver is captured by any of the arguments.
  7736. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  7737. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  7738. return diagnoseRetainCycle(*this, capturer, owner);
  7739. }
  7740. /// Check a property assign to see if it's likely to cause a retain cycle.
  7741. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  7742. RetainCycleOwner owner;
  7743. if (!findRetainCycleOwner(*this, receiver, owner))
  7744. return;
  7745. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  7746. diagnoseRetainCycle(*this, capturer, owner);
  7747. }
  7748. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  7749. RetainCycleOwner Owner;
  7750. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  7751. return;
  7752. // Because we don't have an expression for the variable, we have to set the
  7753. // location explicitly here.
  7754. Owner.Loc = Var->getLocation();
  7755. Owner.Range = Var->getSourceRange();
  7756. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  7757. diagnoseRetainCycle(*this, Capturer, Owner);
  7758. }
  7759. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  7760. Expr *RHS, bool isProperty) {
  7761. // Check if RHS is an Objective-C object literal, which also can get
  7762. // immediately zapped in a weak reference. Note that we explicitly
  7763. // allow ObjCStringLiterals, since those are designed to never really die.
  7764. RHS = RHS->IgnoreParenImpCasts();
  7765. // This enum needs to match with the 'select' in
  7766. // warn_objc_arc_literal_assign (off-by-1).
  7767. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  7768. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  7769. return false;
  7770. S.Diag(Loc, diag::warn_arc_literal_assign)
  7771. << (unsigned) Kind
  7772. << (isProperty ? 0 : 1)
  7773. << RHS->getSourceRange();
  7774. return true;
  7775. }
  7776. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  7777. Qualifiers::ObjCLifetime LT,
  7778. Expr *RHS, bool isProperty) {
  7779. // Strip off any implicit cast added to get to the one ARC-specific.
  7780. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  7781. if (cast->getCastKind() == CK_ARCConsumeObject) {
  7782. S.Diag(Loc, diag::warn_arc_retained_assign)
  7783. << (LT == Qualifiers::OCL_ExplicitNone)
  7784. << (isProperty ? 0 : 1)
  7785. << RHS->getSourceRange();
  7786. return true;
  7787. }
  7788. RHS = cast->getSubExpr();
  7789. }
  7790. if (LT == Qualifiers::OCL_Weak &&
  7791. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  7792. return true;
  7793. return false;
  7794. }
  7795. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  7796. QualType LHS, Expr *RHS) {
  7797. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  7798. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  7799. return false;
  7800. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  7801. return true;
  7802. return false;
  7803. }
  7804. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  7805. Expr *LHS, Expr *RHS) {
  7806. QualType LHSType;
  7807. // PropertyRef on LHS type need be directly obtained from
  7808. // its declaration as it has a PseudoType.
  7809. ObjCPropertyRefExpr *PRE
  7810. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  7811. if (PRE && !PRE->isImplicitProperty()) {
  7812. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  7813. if (PD)
  7814. LHSType = PD->getType();
  7815. }
  7816. if (LHSType.isNull())
  7817. LHSType = LHS->getType();
  7818. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  7819. if (LT == Qualifiers::OCL_Weak) {
  7820. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  7821. getCurFunction()->markSafeWeakUse(LHS);
  7822. }
  7823. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  7824. return;
  7825. // FIXME. Check for other life times.
  7826. if (LT != Qualifiers::OCL_None)
  7827. return;
  7828. if (PRE) {
  7829. if (PRE->isImplicitProperty())
  7830. return;
  7831. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  7832. if (!PD)
  7833. return;
  7834. unsigned Attributes = PD->getPropertyAttributes();
  7835. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  7836. // when 'assign' attribute was not explicitly specified
  7837. // by user, ignore it and rely on property type itself
  7838. // for lifetime info.
  7839. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  7840. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  7841. LHSType->isObjCRetainableType())
  7842. return;
  7843. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  7844. if (cast->getCastKind() == CK_ARCConsumeObject) {
  7845. Diag(Loc, diag::warn_arc_retained_property_assign)
  7846. << RHS->getSourceRange();
  7847. return;
  7848. }
  7849. RHS = cast->getSubExpr();
  7850. }
  7851. }
  7852. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  7853. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  7854. return;
  7855. }
  7856. }
  7857. }
  7858. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  7859. namespace {
  7860. bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  7861. SourceLocation StmtLoc,
  7862. const NullStmt *Body) {
  7863. // Do not warn if the body is a macro that expands to nothing, e.g:
  7864. //
  7865. // #define CALL(x)
  7866. // if (condition)
  7867. // CALL(0);
  7868. //
  7869. if (Body->hasLeadingEmptyMacro())
  7870. return false;
  7871. // Get line numbers of statement and body.
  7872. bool StmtLineInvalid;
  7873. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  7874. &StmtLineInvalid);
  7875. if (StmtLineInvalid)
  7876. return false;
  7877. bool BodyLineInvalid;
  7878. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  7879. &BodyLineInvalid);
  7880. if (BodyLineInvalid)
  7881. return false;
  7882. // Warn if null statement and body are on the same line.
  7883. if (StmtLine != BodyLine)
  7884. return false;
  7885. return true;
  7886. }
  7887. } // Unnamed namespace
  7888. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  7889. const Stmt *Body,
  7890. unsigned DiagID) {
  7891. // Since this is a syntactic check, don't emit diagnostic for template
  7892. // instantiations, this just adds noise.
  7893. if (CurrentInstantiationScope)
  7894. return;
  7895. // The body should be a null statement.
  7896. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  7897. if (!NBody)
  7898. return;
  7899. // Do the usual checks.
  7900. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  7901. return;
  7902. Diag(NBody->getSemiLoc(), DiagID);
  7903. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  7904. }
  7905. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  7906. const Stmt *PossibleBody) {
  7907. assert(!CurrentInstantiationScope); // Ensured by caller
  7908. SourceLocation StmtLoc;
  7909. const Stmt *Body;
  7910. unsigned DiagID;
  7911. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  7912. StmtLoc = FS->getRParenLoc();
  7913. Body = FS->getBody();
  7914. DiagID = diag::warn_empty_for_body;
  7915. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  7916. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  7917. Body = WS->getBody();
  7918. DiagID = diag::warn_empty_while_body;
  7919. } else
  7920. return; // Neither `for' nor `while'.
  7921. // The body should be a null statement.
  7922. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  7923. if (!NBody)
  7924. return;
  7925. // Skip expensive checks if diagnostic is disabled.
  7926. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  7927. return;
  7928. // Do the usual checks.
  7929. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  7930. return;
  7931. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  7932. // noise level low, emit diagnostics only if for/while is followed by a
  7933. // CompoundStmt, e.g.:
  7934. // for (int i = 0; i < n; i++);
  7935. // {
  7936. // a(i);
  7937. // }
  7938. // or if for/while is followed by a statement with more indentation
  7939. // than for/while itself:
  7940. // for (int i = 0; i < n; i++);
  7941. // a(i);
  7942. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  7943. if (!ProbableTypo) {
  7944. bool BodyColInvalid;
  7945. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  7946. PossibleBody->getLocStart(),
  7947. &BodyColInvalid);
  7948. if (BodyColInvalid)
  7949. return;
  7950. bool StmtColInvalid;
  7951. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  7952. S->getLocStart(),
  7953. &StmtColInvalid);
  7954. if (StmtColInvalid)
  7955. return;
  7956. if (BodyCol > StmtCol)
  7957. ProbableTypo = true;
  7958. }
  7959. if (ProbableTypo) {
  7960. Diag(NBody->getSemiLoc(), DiagID);
  7961. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  7962. }
  7963. }
  7964. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  7965. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  7966. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  7967. SourceLocation OpLoc) {
  7968. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  7969. return;
  7970. if (!ActiveTemplateInstantiations.empty())
  7971. return;
  7972. // Strip parens and casts away.
  7973. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  7974. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  7975. // Check for a call expression
  7976. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  7977. if (!CE || CE->getNumArgs() != 1)
  7978. return;
  7979. // Check for a call to std::move
  7980. const FunctionDecl *FD = CE->getDirectCallee();
  7981. if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
  7982. !FD->getIdentifier()->isStr("move"))
  7983. return;
  7984. // Get argument from std::move
  7985. RHSExpr = CE->getArg(0);
  7986. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  7987. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  7988. // Two DeclRefExpr's, check that the decls are the same.
  7989. if (LHSDeclRef && RHSDeclRef) {
  7990. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  7991. return;
  7992. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  7993. RHSDeclRef->getDecl()->getCanonicalDecl())
  7994. return;
  7995. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  7996. << LHSExpr->getSourceRange()
  7997. << RHSExpr->getSourceRange();
  7998. return;
  7999. }
  8000. // Member variables require a different approach to check for self moves.
  8001. // MemberExpr's are the same if every nested MemberExpr refers to the same
  8002. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  8003. // the base Expr's are CXXThisExpr's.
  8004. const Expr *LHSBase = LHSExpr;
  8005. const Expr *RHSBase = RHSExpr;
  8006. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  8007. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  8008. if (!LHSME || !RHSME)
  8009. return;
  8010. while (LHSME && RHSME) {
  8011. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  8012. RHSME->getMemberDecl()->getCanonicalDecl())
  8013. return;
  8014. LHSBase = LHSME->getBase();
  8015. RHSBase = RHSME->getBase();
  8016. LHSME = dyn_cast<MemberExpr>(LHSBase);
  8017. RHSME = dyn_cast<MemberExpr>(RHSBase);
  8018. }
  8019. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  8020. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  8021. if (LHSDeclRef && RHSDeclRef) {
  8022. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  8023. return;
  8024. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  8025. RHSDeclRef->getDecl()->getCanonicalDecl())
  8026. return;
  8027. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  8028. << LHSExpr->getSourceRange()
  8029. << RHSExpr->getSourceRange();
  8030. return;
  8031. }
  8032. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  8033. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  8034. << LHSExpr->getSourceRange()
  8035. << RHSExpr->getSourceRange();
  8036. }
  8037. //===--- Layout compatibility ----------------------------------------------//
  8038. namespace {
  8039. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  8040. /// \brief Check if two enumeration types are layout-compatible.
  8041. bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  8042. // C++11 [dcl.enum] p8:
  8043. // Two enumeration types are layout-compatible if they have the same
  8044. // underlying type.
  8045. return ED1->isComplete() && ED2->isComplete() &&
  8046. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  8047. }
  8048. /// \brief Check if two fields are layout-compatible.
  8049. bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
  8050. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  8051. return false;
  8052. if (Field1->isBitField() != Field2->isBitField())
  8053. return false;
  8054. if (Field1->isBitField()) {
  8055. // Make sure that the bit-fields are the same length.
  8056. unsigned Bits1 = Field1->getBitWidthValue(C);
  8057. unsigned Bits2 = Field2->getBitWidthValue(C);
  8058. if (Bits1 != Bits2)
  8059. return false;
  8060. }
  8061. return true;
  8062. }
  8063. /// \brief Check if two standard-layout structs are layout-compatible.
  8064. /// (C++11 [class.mem] p17)
  8065. bool isLayoutCompatibleStruct(ASTContext &C,
  8066. RecordDecl *RD1,
  8067. RecordDecl *RD2) {
  8068. // If both records are C++ classes, check that base classes match.
  8069. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  8070. // If one of records is a CXXRecordDecl we are in C++ mode,
  8071. // thus the other one is a CXXRecordDecl, too.
  8072. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  8073. // Check number of base classes.
  8074. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  8075. return false;
  8076. // Check the base classes.
  8077. for (CXXRecordDecl::base_class_const_iterator
  8078. Base1 = D1CXX->bases_begin(),
  8079. BaseEnd1 = D1CXX->bases_end(),
  8080. Base2 = D2CXX->bases_begin();
  8081. Base1 != BaseEnd1;
  8082. ++Base1, ++Base2) {
  8083. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  8084. return false;
  8085. }
  8086. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  8087. // If only RD2 is a C++ class, it should have zero base classes.
  8088. if (D2CXX->getNumBases() > 0)
  8089. return false;
  8090. }
  8091. // Check the fields.
  8092. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  8093. Field2End = RD2->field_end(),
  8094. Field1 = RD1->field_begin(),
  8095. Field1End = RD1->field_end();
  8096. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  8097. if (!isLayoutCompatible(C, *Field1, *Field2))
  8098. return false;
  8099. }
  8100. if (Field1 != Field1End || Field2 != Field2End)
  8101. return false;
  8102. return true;
  8103. }
  8104. /// \brief Check if two standard-layout unions are layout-compatible.
  8105. /// (C++11 [class.mem] p18)
  8106. bool isLayoutCompatibleUnion(ASTContext &C,
  8107. RecordDecl *RD1,
  8108. RecordDecl *RD2) {
  8109. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  8110. for (auto *Field2 : RD2->fields())
  8111. UnmatchedFields.insert(Field2);
  8112. for (auto *Field1 : RD1->fields()) {
  8113. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  8114. I = UnmatchedFields.begin(),
  8115. E = UnmatchedFields.end();
  8116. for ( ; I != E; ++I) {
  8117. if (isLayoutCompatible(C, Field1, *I)) {
  8118. bool Result = UnmatchedFields.erase(*I);
  8119. (void) Result;
  8120. assert(Result);
  8121. break;
  8122. }
  8123. }
  8124. if (I == E)
  8125. return false;
  8126. }
  8127. return UnmatchedFields.empty();
  8128. }
  8129. bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
  8130. if (RD1->isUnion() != RD2->isUnion())
  8131. return false;
  8132. if (RD1->isUnion())
  8133. return isLayoutCompatibleUnion(C, RD1, RD2);
  8134. else
  8135. return isLayoutCompatibleStruct(C, RD1, RD2);
  8136. }
  8137. /// \brief Check if two types are layout-compatible in C++11 sense.
  8138. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  8139. if (T1.isNull() || T2.isNull())
  8140. return false;
  8141. // C++11 [basic.types] p11:
  8142. // If two types T1 and T2 are the same type, then T1 and T2 are
  8143. // layout-compatible types.
  8144. if (C.hasSameType(T1, T2))
  8145. return true;
  8146. T1 = T1.getCanonicalType().getUnqualifiedType();
  8147. T2 = T2.getCanonicalType().getUnqualifiedType();
  8148. const Type::TypeClass TC1 = T1->getTypeClass();
  8149. const Type::TypeClass TC2 = T2->getTypeClass();
  8150. if (TC1 != TC2)
  8151. return false;
  8152. if (TC1 == Type::Enum) {
  8153. return isLayoutCompatible(C,
  8154. cast<EnumType>(T1)->getDecl(),
  8155. cast<EnumType>(T2)->getDecl());
  8156. } else if (TC1 == Type::Record) {
  8157. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  8158. return false;
  8159. return isLayoutCompatible(C,
  8160. cast<RecordType>(T1)->getDecl(),
  8161. cast<RecordType>(T2)->getDecl());
  8162. }
  8163. return false;
  8164. }
  8165. }
  8166. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  8167. namespace {
  8168. /// \brief Given a type tag expression find the type tag itself.
  8169. ///
  8170. /// \param TypeExpr Type tag expression, as it appears in user's code.
  8171. ///
  8172. /// \param VD Declaration of an identifier that appears in a type tag.
  8173. ///
  8174. /// \param MagicValue Type tag magic value.
  8175. bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  8176. const ValueDecl **VD, uint64_t *MagicValue) {
  8177. while(true) {
  8178. if (!TypeExpr)
  8179. return false;
  8180. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  8181. switch (TypeExpr->getStmtClass()) {
  8182. case Stmt::UnaryOperatorClass: {
  8183. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  8184. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  8185. TypeExpr = UO->getSubExpr();
  8186. continue;
  8187. }
  8188. return false;
  8189. }
  8190. case Stmt::DeclRefExprClass: {
  8191. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  8192. *VD = DRE->getDecl();
  8193. return true;
  8194. }
  8195. case Stmt::IntegerLiteralClass: {
  8196. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  8197. llvm::APInt MagicValueAPInt = IL->getValue();
  8198. if (MagicValueAPInt.getActiveBits() <= 64) {
  8199. *MagicValue = MagicValueAPInt.getZExtValue();
  8200. return true;
  8201. } else
  8202. return false;
  8203. }
  8204. case Stmt::BinaryConditionalOperatorClass:
  8205. case Stmt::ConditionalOperatorClass: {
  8206. const AbstractConditionalOperator *ACO =
  8207. cast<AbstractConditionalOperator>(TypeExpr);
  8208. bool Result;
  8209. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  8210. if (Result)
  8211. TypeExpr = ACO->getTrueExpr();
  8212. else
  8213. TypeExpr = ACO->getFalseExpr();
  8214. continue;
  8215. }
  8216. return false;
  8217. }
  8218. case Stmt::BinaryOperatorClass: {
  8219. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  8220. if (BO->getOpcode() == BO_Comma) {
  8221. TypeExpr = BO->getRHS();
  8222. continue;
  8223. }
  8224. return false;
  8225. }
  8226. default:
  8227. return false;
  8228. }
  8229. }
  8230. }
  8231. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  8232. ///
  8233. /// \param TypeExpr Expression that specifies a type tag.
  8234. ///
  8235. /// \param MagicValues Registered magic values.
  8236. ///
  8237. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  8238. /// kind.
  8239. ///
  8240. /// \param TypeInfo Information about the corresponding C type.
  8241. ///
  8242. /// \returns true if the corresponding C type was found.
  8243. bool GetMatchingCType(
  8244. const IdentifierInfo *ArgumentKind,
  8245. const Expr *TypeExpr, const ASTContext &Ctx,
  8246. const llvm::DenseMap<Sema::TypeTagMagicValue,
  8247. Sema::TypeTagData> *MagicValues,
  8248. bool &FoundWrongKind,
  8249. Sema::TypeTagData &TypeInfo) {
  8250. FoundWrongKind = false;
  8251. // Variable declaration that has type_tag_for_datatype attribute.
  8252. const ValueDecl *VD = nullptr;
  8253. uint64_t MagicValue;
  8254. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  8255. return false;
  8256. if (VD) {
  8257. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  8258. if (I->getArgumentKind() != ArgumentKind) {
  8259. FoundWrongKind = true;
  8260. return false;
  8261. }
  8262. TypeInfo.Type = I->getMatchingCType();
  8263. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  8264. TypeInfo.MustBeNull = I->getMustBeNull();
  8265. return true;
  8266. }
  8267. return false;
  8268. }
  8269. if (!MagicValues)
  8270. return false;
  8271. llvm::DenseMap<Sema::TypeTagMagicValue,
  8272. Sema::TypeTagData>::const_iterator I =
  8273. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  8274. if (I == MagicValues->end())
  8275. return false;
  8276. TypeInfo = I->second;
  8277. return true;
  8278. }
  8279. } // unnamed namespace
  8280. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  8281. uint64_t MagicValue, QualType Type,
  8282. bool LayoutCompatible,
  8283. bool MustBeNull) {
  8284. if (!TypeTagForDatatypeMagicValues)
  8285. TypeTagForDatatypeMagicValues.reset(
  8286. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  8287. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  8288. (*TypeTagForDatatypeMagicValues)[Magic] =
  8289. TypeTagData(Type, LayoutCompatible, MustBeNull);
  8290. }
  8291. namespace {
  8292. bool IsSameCharType(QualType T1, QualType T2) {
  8293. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  8294. if (!BT1)
  8295. return false;
  8296. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  8297. if (!BT2)
  8298. return false;
  8299. BuiltinType::Kind T1Kind = BT1->getKind();
  8300. BuiltinType::Kind T2Kind = BT2->getKind();
  8301. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  8302. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  8303. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  8304. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  8305. }
  8306. } // unnamed namespace
  8307. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  8308. const Expr * const *ExprArgs) {
  8309. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  8310. bool IsPointerAttr = Attr->getIsPointer();
  8311. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  8312. bool FoundWrongKind;
  8313. TypeTagData TypeInfo;
  8314. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  8315. TypeTagForDatatypeMagicValues.get(),
  8316. FoundWrongKind, TypeInfo)) {
  8317. if (FoundWrongKind)
  8318. Diag(TypeTagExpr->getExprLoc(),
  8319. diag::warn_type_tag_for_datatype_wrong_kind)
  8320. << TypeTagExpr->getSourceRange();
  8321. return;
  8322. }
  8323. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  8324. if (IsPointerAttr) {
  8325. // Skip implicit cast of pointer to `void *' (as a function argument).
  8326. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  8327. if (ICE->getType()->isVoidPointerType() &&
  8328. ICE->getCastKind() == CK_BitCast)
  8329. ArgumentExpr = ICE->getSubExpr();
  8330. }
  8331. QualType ArgumentType = ArgumentExpr->getType();
  8332. // Passing a `void*' pointer shouldn't trigger a warning.
  8333. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  8334. return;
  8335. if (TypeInfo.MustBeNull) {
  8336. // Type tag with matching void type requires a null pointer.
  8337. if (!ArgumentExpr->isNullPointerConstant(Context,
  8338. Expr::NPC_ValueDependentIsNotNull)) {
  8339. Diag(ArgumentExpr->getExprLoc(),
  8340. diag::warn_type_safety_null_pointer_required)
  8341. << ArgumentKind->getName()
  8342. << ArgumentExpr->getSourceRange()
  8343. << TypeTagExpr->getSourceRange();
  8344. }
  8345. return;
  8346. }
  8347. QualType RequiredType = TypeInfo.Type;
  8348. if (IsPointerAttr)
  8349. RequiredType = Context.getPointerType(RequiredType);
  8350. bool mismatch = false;
  8351. if (!TypeInfo.LayoutCompatible) {
  8352. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  8353. // C++11 [basic.fundamental] p1:
  8354. // Plain char, signed char, and unsigned char are three distinct types.
  8355. //
  8356. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  8357. // char' depending on the current char signedness mode.
  8358. if (mismatch)
  8359. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  8360. RequiredType->getPointeeType())) ||
  8361. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  8362. mismatch = false;
  8363. } else
  8364. if (IsPointerAttr)
  8365. mismatch = !isLayoutCompatible(Context,
  8366. ArgumentType->getPointeeType(),
  8367. RequiredType->getPointeeType());
  8368. else
  8369. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  8370. if (mismatch)
  8371. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  8372. << ArgumentType << ArgumentKind
  8373. << TypeInfo.LayoutCompatible << RequiredType
  8374. << ArgumentExpr->getSourceRange()
  8375. << TypeTagExpr->getSourceRange();
  8376. }