CFG.cpp 198 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006
  1. //===- CFG.cpp - Classes for representing and building CFGs ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the CFG and CFGBuilder classes for representing and
  10. // building Control-Flow Graphs (CFGs) from ASTs.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Analysis/CFG.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/DeclBase.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclGroup.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/OperationKinds.h"
  23. #include "clang/AST/PrettyPrinter.h"
  24. #include "clang/AST/Stmt.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/AST/StmtObjC.h"
  27. #include "clang/AST/StmtVisitor.h"
  28. #include "clang/AST/Type.h"
  29. #include "clang/Analysis/ConstructionContext.h"
  30. #include "clang/Analysis/Support/BumpVector.h"
  31. #include "clang/Basic/Builtins.h"
  32. #include "clang/Basic/ExceptionSpecificationType.h"
  33. #include "clang/Basic/JsonSupport.h"
  34. #include "clang/Basic/LLVM.h"
  35. #include "clang/Basic/LangOptions.h"
  36. #include "clang/Basic/SourceLocation.h"
  37. #include "clang/Basic/Specifiers.h"
  38. #include "llvm/ADT/APInt.h"
  39. #include "llvm/ADT/APSInt.h"
  40. #include "llvm/ADT/ArrayRef.h"
  41. #include "llvm/ADT/DenseMap.h"
  42. #include "llvm/ADT/Optional.h"
  43. #include "llvm/ADT/STLExtras.h"
  44. #include "llvm/ADT/SetVector.h"
  45. #include "llvm/ADT/SmallPtrSet.h"
  46. #include "llvm/ADT/SmallVector.h"
  47. #include "llvm/Support/Allocator.h"
  48. #include "llvm/Support/Casting.h"
  49. #include "llvm/Support/Compiler.h"
  50. #include "llvm/Support/DOTGraphTraits.h"
  51. #include "llvm/Support/ErrorHandling.h"
  52. #include "llvm/Support/Format.h"
  53. #include "llvm/Support/GraphWriter.h"
  54. #include "llvm/Support/SaveAndRestore.h"
  55. #include "llvm/Support/raw_ostream.h"
  56. #include <cassert>
  57. #include <memory>
  58. #include <string>
  59. #include <tuple>
  60. #include <utility>
  61. #include <vector>
  62. using namespace clang;
  63. static SourceLocation GetEndLoc(Decl *D) {
  64. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  65. if (Expr *Ex = VD->getInit())
  66. return Ex->getSourceRange().getEnd();
  67. return D->getLocation();
  68. }
  69. /// Returns true on constant values based around a single IntegerLiteral.
  70. /// Allow for use of parentheses, integer casts, and negative signs.
  71. static bool IsIntegerLiteralConstantExpr(const Expr *E) {
  72. // Allow parentheses
  73. E = E->IgnoreParens();
  74. // Allow conversions to different integer kind.
  75. if (const auto *CE = dyn_cast<CastExpr>(E)) {
  76. if (CE->getCastKind() != CK_IntegralCast)
  77. return false;
  78. E = CE->getSubExpr();
  79. }
  80. // Allow negative numbers.
  81. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  82. if (UO->getOpcode() != UO_Minus)
  83. return false;
  84. E = UO->getSubExpr();
  85. }
  86. return isa<IntegerLiteral>(E);
  87. }
  88. /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
  89. /// constant expression or EnumConstantDecl from the given Expr. If it fails,
  90. /// returns nullptr.
  91. static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
  92. E = E->IgnoreParens();
  93. if (IsIntegerLiteralConstantExpr(E))
  94. return E;
  95. if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  96. return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
  97. return nullptr;
  98. }
  99. /// Tries to interpret a binary operator into `Expr Op NumExpr` form, if
  100. /// NumExpr is an integer literal or an enum constant.
  101. ///
  102. /// If this fails, at least one of the returned DeclRefExpr or Expr will be
  103. /// null.
  104. static std::tuple<const Expr *, BinaryOperatorKind, const Expr *>
  105. tryNormalizeBinaryOperator(const BinaryOperator *B) {
  106. BinaryOperatorKind Op = B->getOpcode();
  107. const Expr *MaybeDecl = B->getLHS();
  108. const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
  109. // Expr looked like `0 == Foo` instead of `Foo == 0`
  110. if (Constant == nullptr) {
  111. // Flip the operator
  112. if (Op == BO_GT)
  113. Op = BO_LT;
  114. else if (Op == BO_GE)
  115. Op = BO_LE;
  116. else if (Op == BO_LT)
  117. Op = BO_GT;
  118. else if (Op == BO_LE)
  119. Op = BO_GE;
  120. MaybeDecl = B->getRHS();
  121. Constant = tryTransformToIntOrEnumConstant(B->getLHS());
  122. }
  123. return std::make_tuple(MaybeDecl, Op, Constant);
  124. }
  125. /// For an expression `x == Foo && x == Bar`, this determines whether the
  126. /// `Foo` and `Bar` are either of the same enumeration type, or both integer
  127. /// literals.
  128. ///
  129. /// It's an error to pass this arguments that are not either IntegerLiterals
  130. /// or DeclRefExprs (that have decls of type EnumConstantDecl)
  131. static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
  132. // User intent isn't clear if they're mixing int literals with enum
  133. // constants.
  134. if (isa<DeclRefExpr>(E1) != isa<DeclRefExpr>(E2))
  135. return false;
  136. // Integer literal comparisons, regardless of literal type, are acceptable.
  137. if (!isa<DeclRefExpr>(E1))
  138. return true;
  139. // IntegerLiterals are handled above and only EnumConstantDecls are expected
  140. // beyond this point
  141. assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
  142. auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
  143. auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
  144. assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
  145. const DeclContext *DC1 = Decl1->getDeclContext();
  146. const DeclContext *DC2 = Decl2->getDeclContext();
  147. assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
  148. return DC1 == DC2;
  149. }
  150. namespace {
  151. class CFGBuilder;
  152. /// The CFG builder uses a recursive algorithm to build the CFG. When
  153. /// we process an expression, sometimes we know that we must add the
  154. /// subexpressions as block-level expressions. For example:
  155. ///
  156. /// exp1 || exp2
  157. ///
  158. /// When processing the '||' expression, we know that exp1 and exp2
  159. /// need to be added as block-level expressions, even though they
  160. /// might not normally need to be. AddStmtChoice records this
  161. /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
  162. /// the builder has an option not to add a subexpression as a
  163. /// block-level expression.
  164. class AddStmtChoice {
  165. public:
  166. enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
  167. AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
  168. bool alwaysAdd(CFGBuilder &builder,
  169. const Stmt *stmt) const;
  170. /// Return a copy of this object, except with the 'always-add' bit
  171. /// set as specified.
  172. AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
  173. return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
  174. }
  175. private:
  176. Kind kind;
  177. };
  178. /// LocalScope - Node in tree of local scopes created for C++ implicit
  179. /// destructor calls generation. It contains list of automatic variables
  180. /// declared in the scope and link to position in previous scope this scope
  181. /// began in.
  182. ///
  183. /// The process of creating local scopes is as follows:
  184. /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
  185. /// - Before processing statements in scope (e.g. CompoundStmt) create
  186. /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
  187. /// and set CFGBuilder::ScopePos to the end of new scope,
  188. /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
  189. /// at this VarDecl,
  190. /// - For every normal (without jump) end of scope add to CFGBlock destructors
  191. /// for objects in the current scope,
  192. /// - For every jump add to CFGBlock destructors for objects
  193. /// between CFGBuilder::ScopePos and local scope position saved for jump
  194. /// target. Thanks to C++ restrictions on goto jumps we can be sure that
  195. /// jump target position will be on the path to root from CFGBuilder::ScopePos
  196. /// (adding any variable that doesn't need constructor to be called to
  197. /// LocalScope can break this assumption),
  198. ///
  199. class LocalScope {
  200. public:
  201. friend class const_iterator;
  202. using AutomaticVarsTy = BumpVector<VarDecl *>;
  203. /// const_iterator - Iterates local scope backwards and jumps to previous
  204. /// scope on reaching the beginning of currently iterated scope.
  205. class const_iterator {
  206. const LocalScope* Scope = nullptr;
  207. /// VarIter is guaranteed to be greater then 0 for every valid iterator.
  208. /// Invalid iterator (with null Scope) has VarIter equal to 0.
  209. unsigned VarIter = 0;
  210. public:
  211. /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
  212. /// Incrementing invalid iterator is allowed and will result in invalid
  213. /// iterator.
  214. const_iterator() = default;
  215. /// Create valid iterator. In case when S.Prev is an invalid iterator and
  216. /// I is equal to 0, this will create invalid iterator.
  217. const_iterator(const LocalScope& S, unsigned I)
  218. : Scope(&S), VarIter(I) {
  219. // Iterator to "end" of scope is not allowed. Handle it by going up
  220. // in scopes tree possibly up to invalid iterator in the root.
  221. if (VarIter == 0 && Scope)
  222. *this = Scope->Prev;
  223. }
  224. VarDecl *const* operator->() const {
  225. assert(Scope && "Dereferencing invalid iterator is not allowed");
  226. assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
  227. return &Scope->Vars[VarIter - 1];
  228. }
  229. const VarDecl *getFirstVarInScope() const {
  230. assert(Scope && "Dereferencing invalid iterator is not allowed");
  231. assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
  232. return Scope->Vars[0];
  233. }
  234. VarDecl *operator*() const {
  235. return *this->operator->();
  236. }
  237. const_iterator &operator++() {
  238. if (!Scope)
  239. return *this;
  240. assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
  241. --VarIter;
  242. if (VarIter == 0)
  243. *this = Scope->Prev;
  244. return *this;
  245. }
  246. const_iterator operator++(int) {
  247. const_iterator P = *this;
  248. ++*this;
  249. return P;
  250. }
  251. bool operator==(const const_iterator &rhs) const {
  252. return Scope == rhs.Scope && VarIter == rhs.VarIter;
  253. }
  254. bool operator!=(const const_iterator &rhs) const {
  255. return !(*this == rhs);
  256. }
  257. explicit operator bool() const {
  258. return *this != const_iterator();
  259. }
  260. int distance(const_iterator L);
  261. const_iterator shared_parent(const_iterator L);
  262. bool pointsToFirstDeclaredVar() { return VarIter == 1; }
  263. };
  264. private:
  265. BumpVectorContext ctx;
  266. /// Automatic variables in order of declaration.
  267. AutomaticVarsTy Vars;
  268. /// Iterator to variable in previous scope that was declared just before
  269. /// begin of this scope.
  270. const_iterator Prev;
  271. public:
  272. /// Constructs empty scope linked to previous scope in specified place.
  273. LocalScope(BumpVectorContext ctx, const_iterator P)
  274. : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
  275. /// Begin of scope in direction of CFG building (backwards).
  276. const_iterator begin() const { return const_iterator(*this, Vars.size()); }
  277. void addVar(VarDecl *VD) {
  278. Vars.push_back(VD, ctx);
  279. }
  280. };
  281. } // namespace
  282. /// distance - Calculates distance from this to L. L must be reachable from this
  283. /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
  284. /// number of scopes between this and L.
  285. int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
  286. int D = 0;
  287. const_iterator F = *this;
  288. while (F.Scope != L.Scope) {
  289. assert(F != const_iterator() &&
  290. "L iterator is not reachable from F iterator.");
  291. D += F.VarIter;
  292. F = F.Scope->Prev;
  293. }
  294. D += F.VarIter - L.VarIter;
  295. return D;
  296. }
  297. /// Calculates the closest parent of this iterator
  298. /// that is in a scope reachable through the parents of L.
  299. /// I.e. when using 'goto' from this to L, the lifetime of all variables
  300. /// between this and shared_parent(L) end.
  301. LocalScope::const_iterator
  302. LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
  303. llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
  304. while (true) {
  305. ScopesOfL.insert(L.Scope);
  306. if (L == const_iterator())
  307. break;
  308. L = L.Scope->Prev;
  309. }
  310. const_iterator F = *this;
  311. while (true) {
  312. if (ScopesOfL.count(F.Scope))
  313. return F;
  314. assert(F != const_iterator() &&
  315. "L iterator is not reachable from F iterator.");
  316. F = F.Scope->Prev;
  317. }
  318. }
  319. namespace {
  320. /// Structure for specifying position in CFG during its build process. It
  321. /// consists of CFGBlock that specifies position in CFG and
  322. /// LocalScope::const_iterator that specifies position in LocalScope graph.
  323. struct BlockScopePosPair {
  324. CFGBlock *block = nullptr;
  325. LocalScope::const_iterator scopePosition;
  326. BlockScopePosPair() = default;
  327. BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
  328. : block(b), scopePosition(scopePos) {}
  329. };
  330. /// TryResult - a class representing a variant over the values
  331. /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
  332. /// and is used by the CFGBuilder to decide if a branch condition
  333. /// can be decided up front during CFG construction.
  334. class TryResult {
  335. int X = -1;
  336. public:
  337. TryResult() = default;
  338. TryResult(bool b) : X(b ? 1 : 0) {}
  339. bool isTrue() const { return X == 1; }
  340. bool isFalse() const { return X == 0; }
  341. bool isKnown() const { return X >= 0; }
  342. void negate() {
  343. assert(isKnown());
  344. X ^= 0x1;
  345. }
  346. };
  347. } // namespace
  348. static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
  349. if (!R1.isKnown() || !R2.isKnown())
  350. return TryResult();
  351. return TryResult(R1.isTrue() && R2.isTrue());
  352. }
  353. namespace {
  354. class reverse_children {
  355. llvm::SmallVector<Stmt *, 12> childrenBuf;
  356. ArrayRef<Stmt *> children;
  357. public:
  358. reverse_children(Stmt *S);
  359. using iterator = ArrayRef<Stmt *>::reverse_iterator;
  360. iterator begin() const { return children.rbegin(); }
  361. iterator end() const { return children.rend(); }
  362. };
  363. } // namespace
  364. reverse_children::reverse_children(Stmt *S) {
  365. if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  366. children = CE->getRawSubExprs();
  367. return;
  368. }
  369. switch (S->getStmtClass()) {
  370. // Note: Fill in this switch with more cases we want to optimize.
  371. case Stmt::InitListExprClass: {
  372. InitListExpr *IE = cast<InitListExpr>(S);
  373. children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
  374. IE->getNumInits());
  375. return;
  376. }
  377. default:
  378. break;
  379. }
  380. // Default case for all other statements.
  381. for (Stmt *SubStmt : S->children())
  382. childrenBuf.push_back(SubStmt);
  383. // This needs to be done *after* childrenBuf has been populated.
  384. children = childrenBuf;
  385. }
  386. namespace {
  387. /// CFGBuilder - This class implements CFG construction from an AST.
  388. /// The builder is stateful: an instance of the builder should be used to only
  389. /// construct a single CFG.
  390. ///
  391. /// Example usage:
  392. ///
  393. /// CFGBuilder builder;
  394. /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
  395. ///
  396. /// CFG construction is done via a recursive walk of an AST. We actually parse
  397. /// the AST in reverse order so that the successor of a basic block is
  398. /// constructed prior to its predecessor. This allows us to nicely capture
  399. /// implicit fall-throughs without extra basic blocks.
  400. class CFGBuilder {
  401. using JumpTarget = BlockScopePosPair;
  402. using JumpSource = BlockScopePosPair;
  403. ASTContext *Context;
  404. std::unique_ptr<CFG> cfg;
  405. // Current block.
  406. CFGBlock *Block = nullptr;
  407. // Block after the current block.
  408. CFGBlock *Succ = nullptr;
  409. JumpTarget ContinueJumpTarget;
  410. JumpTarget BreakJumpTarget;
  411. JumpTarget SEHLeaveJumpTarget;
  412. CFGBlock *SwitchTerminatedBlock = nullptr;
  413. CFGBlock *DefaultCaseBlock = nullptr;
  414. // This can point either to a try or a __try block. The frontend forbids
  415. // mixing both kinds in one function, so having one for both is enough.
  416. CFGBlock *TryTerminatedBlock = nullptr;
  417. // Current position in local scope.
  418. LocalScope::const_iterator ScopePos;
  419. // LabelMap records the mapping from Label expressions to their jump targets.
  420. using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
  421. LabelMapTy LabelMap;
  422. // A list of blocks that end with a "goto" that must be backpatched to their
  423. // resolved targets upon completion of CFG construction.
  424. using BackpatchBlocksTy = std::vector<JumpSource>;
  425. BackpatchBlocksTy BackpatchBlocks;
  426. // A list of labels whose address has been taken (for indirect gotos).
  427. using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
  428. LabelSetTy AddressTakenLabels;
  429. // Information about the currently visited C++ object construction site.
  430. // This is set in the construction trigger and read when the constructor
  431. // or a function that returns an object by value is being visited.
  432. llvm::DenseMap<Expr *, const ConstructionContextLayer *>
  433. ConstructionContextMap;
  434. using DeclsWithEndedScopeSetTy = llvm::SmallSetVector<VarDecl *, 16>;
  435. DeclsWithEndedScopeSetTy DeclsWithEndedScope;
  436. bool badCFG = false;
  437. const CFG::BuildOptions &BuildOpts;
  438. // State to track for building switch statements.
  439. bool switchExclusivelyCovered = false;
  440. Expr::EvalResult *switchCond = nullptr;
  441. CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
  442. const Stmt *lastLookup = nullptr;
  443. // Caches boolean evaluations of expressions to avoid multiple re-evaluations
  444. // during construction of branches for chained logical operators.
  445. using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
  446. CachedBoolEvalsTy CachedBoolEvals;
  447. public:
  448. explicit CFGBuilder(ASTContext *astContext,
  449. const CFG::BuildOptions &buildOpts)
  450. : Context(astContext), cfg(new CFG()), // crew a new CFG
  451. ConstructionContextMap(), BuildOpts(buildOpts) {}
  452. // buildCFG - Used by external clients to construct the CFG.
  453. std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
  454. bool alwaysAdd(const Stmt *stmt);
  455. private:
  456. // Visitors to walk an AST and construct the CFG.
  457. CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
  458. CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
  459. CFGBlock *VisitBreakStmt(BreakStmt *B);
  460. CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
  461. CFGBlock *VisitCaseStmt(CaseStmt *C);
  462. CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
  463. CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed);
  464. CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
  465. AddStmtChoice asc);
  466. CFGBlock *VisitContinueStmt(ContinueStmt *C);
  467. CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
  468. AddStmtChoice asc);
  469. CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
  470. CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
  471. CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
  472. CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
  473. CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
  474. CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
  475. AddStmtChoice asc);
  476. CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
  477. AddStmtChoice asc);
  478. CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
  479. CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
  480. CFGBlock *VisitDeclStmt(DeclStmt *DS);
  481. CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
  482. CFGBlock *VisitDefaultStmt(DefaultStmt *D);
  483. CFGBlock *VisitDoStmt(DoStmt *D);
  484. CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
  485. AddStmtChoice asc, bool ExternallyDestructed);
  486. CFGBlock *VisitForStmt(ForStmt *F);
  487. CFGBlock *VisitGotoStmt(GotoStmt *G);
  488. CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
  489. CFGBlock *VisitIfStmt(IfStmt *I);
  490. CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
  491. CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
  492. CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
  493. CFGBlock *VisitLabelStmt(LabelStmt *L);
  494. CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
  495. CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
  496. CFGBlock *VisitLogicalOperator(BinaryOperator *B);
  497. std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
  498. Stmt *Term,
  499. CFGBlock *TrueBlock,
  500. CFGBlock *FalseBlock);
  501. CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
  502. AddStmtChoice asc);
  503. CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
  504. CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
  505. CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
  506. CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
  507. CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
  508. CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
  509. CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
  510. CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
  511. CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
  512. CFGBlock *VisitReturnStmt(Stmt *S);
  513. CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
  514. CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
  515. CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
  516. CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
  517. CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
  518. CFGBlock *VisitSwitchStmt(SwitchStmt *S);
  519. CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
  520. AddStmtChoice asc);
  521. CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
  522. CFGBlock *VisitWhileStmt(WhileStmt *W);
  523. CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
  524. bool ExternallyDestructed = false);
  525. CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
  526. CFGBlock *VisitChildren(Stmt *S);
  527. CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
  528. CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D,
  529. AddStmtChoice asc);
  530. void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
  531. const Stmt *S) {
  532. if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
  533. appendScopeBegin(B, VD, S);
  534. }
  535. /// When creating the CFG for temporary destructors, we want to mirror the
  536. /// branch structure of the corresponding constructor calls.
  537. /// Thus, while visiting a statement for temporary destructors, we keep a
  538. /// context to keep track of the following information:
  539. /// - whether a subexpression is executed unconditionally
  540. /// - if a subexpression is executed conditionally, the first
  541. /// CXXBindTemporaryExpr we encounter in that subexpression (which
  542. /// corresponds to the last temporary destructor we have to call for this
  543. /// subexpression) and the CFG block at that point (which will become the
  544. /// successor block when inserting the decision point).
  545. ///
  546. /// That way, we can build the branch structure for temporary destructors as
  547. /// follows:
  548. /// 1. If a subexpression is executed unconditionally, we add the temporary
  549. /// destructor calls to the current block.
  550. /// 2. If a subexpression is executed conditionally, when we encounter a
  551. /// CXXBindTemporaryExpr:
  552. /// a) If it is the first temporary destructor call in the subexpression,
  553. /// we remember the CXXBindTemporaryExpr and the current block in the
  554. /// TempDtorContext; we start a new block, and insert the temporary
  555. /// destructor call.
  556. /// b) Otherwise, add the temporary destructor call to the current block.
  557. /// 3. When we finished visiting a conditionally executed subexpression,
  558. /// and we found at least one temporary constructor during the visitation
  559. /// (2.a has executed), we insert a decision block that uses the
  560. /// CXXBindTemporaryExpr as terminator, and branches to the current block
  561. /// if the CXXBindTemporaryExpr was marked executed, and otherwise
  562. /// branches to the stored successor.
  563. struct TempDtorContext {
  564. TempDtorContext() = default;
  565. TempDtorContext(TryResult KnownExecuted)
  566. : IsConditional(true), KnownExecuted(KnownExecuted) {}
  567. /// Returns whether we need to start a new branch for a temporary destructor
  568. /// call. This is the case when the temporary destructor is
  569. /// conditionally executed, and it is the first one we encounter while
  570. /// visiting a subexpression - other temporary destructors at the same level
  571. /// will be added to the same block and are executed under the same
  572. /// condition.
  573. bool needsTempDtorBranch() const {
  574. return IsConditional && !TerminatorExpr;
  575. }
  576. /// Remember the successor S of a temporary destructor decision branch for
  577. /// the corresponding CXXBindTemporaryExpr E.
  578. void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
  579. Succ = S;
  580. TerminatorExpr = E;
  581. }
  582. const bool IsConditional = false;
  583. const TryResult KnownExecuted = true;
  584. CFGBlock *Succ = nullptr;
  585. CXXBindTemporaryExpr *TerminatorExpr = nullptr;
  586. };
  587. // Visitors to walk an AST and generate destructors of temporaries in
  588. // full expression.
  589. CFGBlock *VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
  590. TempDtorContext &Context);
  591. CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
  592. TempDtorContext &Context);
  593. CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
  594. bool ExternallyDestructed,
  595. TempDtorContext &Context);
  596. CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
  597. CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context);
  598. CFGBlock *VisitConditionalOperatorForTemporaryDtors(
  599. AbstractConditionalOperator *E, bool ExternallyDestructed,
  600. TempDtorContext &Context);
  601. void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
  602. CFGBlock *FalseSucc = nullptr);
  603. // NYS == Not Yet Supported
  604. CFGBlock *NYS() {
  605. badCFG = true;
  606. return Block;
  607. }
  608. // Remember to apply the construction context based on the current \p Layer
  609. // when constructing the CFG element for \p CE.
  610. void consumeConstructionContext(const ConstructionContextLayer *Layer,
  611. Expr *E);
  612. // Scan \p Child statement to find constructors in it, while keeping in mind
  613. // that its parent statement is providing a partial construction context
  614. // described by \p Layer. If a constructor is found, it would be assigned
  615. // the context based on the layer. If an additional construction context layer
  616. // is found, the function recurses into that.
  617. void findConstructionContexts(const ConstructionContextLayer *Layer,
  618. Stmt *Child);
  619. // Scan all arguments of a call expression for a construction context.
  620. // These sorts of call expressions don't have a common superclass,
  621. // hence strict duck-typing.
  622. template <typename CallLikeExpr,
  623. typename = typename std::enable_if<
  624. std::is_same<CallLikeExpr, CallExpr>::value ||
  625. std::is_same<CallLikeExpr, CXXConstructExpr>::value ||
  626. std::is_same<CallLikeExpr, ObjCMessageExpr>::value>>
  627. void findConstructionContextsForArguments(CallLikeExpr *E) {
  628. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  629. Expr *Arg = E->getArg(i);
  630. if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
  631. findConstructionContexts(
  632. ConstructionContextLayer::create(cfg->getBumpVectorContext(),
  633. ConstructionContextItem(E, i)),
  634. Arg);
  635. }
  636. }
  637. // Unset the construction context after consuming it. This is done immediately
  638. // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
  639. // there's no need to do this manually in every Visit... function.
  640. void cleanupConstructionContext(Expr *E);
  641. void autoCreateBlock() { if (!Block) Block = createBlock(); }
  642. CFGBlock *createBlock(bool add_successor = true);
  643. CFGBlock *createNoReturnBlock();
  644. CFGBlock *addStmt(Stmt *S) {
  645. return Visit(S, AddStmtChoice::AlwaysAdd);
  646. }
  647. CFGBlock *addInitializer(CXXCtorInitializer *I);
  648. void addLoopExit(const Stmt *LoopStmt);
  649. void addAutomaticObjDtors(LocalScope::const_iterator B,
  650. LocalScope::const_iterator E, Stmt *S);
  651. void addLifetimeEnds(LocalScope::const_iterator B,
  652. LocalScope::const_iterator E, Stmt *S);
  653. void addAutomaticObjHandling(LocalScope::const_iterator B,
  654. LocalScope::const_iterator E, Stmt *S);
  655. void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
  656. void addScopesEnd(LocalScope::const_iterator B, LocalScope::const_iterator E,
  657. Stmt *S);
  658. void getDeclsWithEndedScope(LocalScope::const_iterator B,
  659. LocalScope::const_iterator E, Stmt *S);
  660. // Local scopes creation.
  661. LocalScope* createOrReuseLocalScope(LocalScope* Scope);
  662. void addLocalScopeForStmt(Stmt *S);
  663. LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
  664. LocalScope* Scope = nullptr);
  665. LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
  666. void addLocalScopeAndDtors(Stmt *S);
  667. const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
  668. if (!BuildOpts.AddRichCXXConstructors)
  669. return nullptr;
  670. const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
  671. if (!Layer)
  672. return nullptr;
  673. cleanupConstructionContext(E);
  674. return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
  675. Layer);
  676. }
  677. // Interface to CFGBlock - adding CFGElements.
  678. void appendStmt(CFGBlock *B, const Stmt *S) {
  679. if (alwaysAdd(S) && cachedEntry)
  680. cachedEntry->second = B;
  681. // All block-level expressions should have already been IgnoreParens()ed.
  682. assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
  683. B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
  684. }
  685. void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
  686. if (const ConstructionContext *CC =
  687. retrieveAndCleanupConstructionContext(CE)) {
  688. B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
  689. return;
  690. }
  691. // No valid construction context found. Fall back to statement.
  692. B->appendStmt(CE, cfg->getBumpVectorContext());
  693. }
  694. void appendCall(CFGBlock *B, CallExpr *CE) {
  695. if (alwaysAdd(CE) && cachedEntry)
  696. cachedEntry->second = B;
  697. if (const ConstructionContext *CC =
  698. retrieveAndCleanupConstructionContext(CE)) {
  699. B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
  700. return;
  701. }
  702. // No valid construction context found. Fall back to statement.
  703. B->appendStmt(CE, cfg->getBumpVectorContext());
  704. }
  705. void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
  706. B->appendInitializer(I, cfg->getBumpVectorContext());
  707. }
  708. void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
  709. B->appendNewAllocator(NE, cfg->getBumpVectorContext());
  710. }
  711. void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
  712. B->appendBaseDtor(BS, cfg->getBumpVectorContext());
  713. }
  714. void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
  715. B->appendMemberDtor(FD, cfg->getBumpVectorContext());
  716. }
  717. void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
  718. if (alwaysAdd(ME) && cachedEntry)
  719. cachedEntry->second = B;
  720. if (const ConstructionContext *CC =
  721. retrieveAndCleanupConstructionContext(ME)) {
  722. B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
  723. return;
  724. }
  725. B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
  726. cfg->getBumpVectorContext());
  727. }
  728. void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
  729. B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
  730. }
  731. void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
  732. B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
  733. }
  734. void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
  735. B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
  736. }
  737. void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
  738. B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
  739. }
  740. void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
  741. B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
  742. }
  743. void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
  744. LocalScope::const_iterator B, LocalScope::const_iterator E);
  745. void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
  746. LocalScope::const_iterator B,
  747. LocalScope::const_iterator E);
  748. const VarDecl *
  749. prependAutomaticObjScopeEndWithTerminator(CFGBlock *Blk,
  750. LocalScope::const_iterator B,
  751. LocalScope::const_iterator E);
  752. void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
  753. B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
  754. cfg->getBumpVectorContext());
  755. }
  756. /// Add a reachable successor to a block, with the alternate variant that is
  757. /// unreachable.
  758. void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
  759. B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
  760. cfg->getBumpVectorContext());
  761. }
  762. void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
  763. if (BuildOpts.AddScopes)
  764. B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
  765. }
  766. void prependScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
  767. if (BuildOpts.AddScopes)
  768. B->prependScopeBegin(VD, S, cfg->getBumpVectorContext());
  769. }
  770. void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
  771. if (BuildOpts.AddScopes)
  772. B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
  773. }
  774. void prependScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
  775. if (BuildOpts.AddScopes)
  776. B->prependScopeEnd(VD, S, cfg->getBumpVectorContext());
  777. }
  778. /// Find a relational comparison with an expression evaluating to a
  779. /// boolean and a constant other than 0 and 1.
  780. /// e.g. if ((x < y) == 10)
  781. TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
  782. const Expr *LHSExpr = B->getLHS()->IgnoreParens();
  783. const Expr *RHSExpr = B->getRHS()->IgnoreParens();
  784. const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
  785. const Expr *BoolExpr = RHSExpr;
  786. bool IntFirst = true;
  787. if (!IntLiteral) {
  788. IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
  789. BoolExpr = LHSExpr;
  790. IntFirst = false;
  791. }
  792. if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
  793. return TryResult();
  794. llvm::APInt IntValue = IntLiteral->getValue();
  795. if ((IntValue == 1) || (IntValue == 0))
  796. return TryResult();
  797. bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
  798. !IntValue.isNegative();
  799. BinaryOperatorKind Bok = B->getOpcode();
  800. if (Bok == BO_GT || Bok == BO_GE) {
  801. // Always true for 10 > bool and bool > -1
  802. // Always false for -1 > bool and bool > 10
  803. return TryResult(IntFirst == IntLarger);
  804. } else {
  805. // Always true for -1 < bool and bool < 10
  806. // Always false for 10 < bool and bool < -1
  807. return TryResult(IntFirst != IntLarger);
  808. }
  809. }
  810. /// Find an incorrect equality comparison. Either with an expression
  811. /// evaluating to a boolean and a constant other than 0 and 1.
  812. /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
  813. /// true/false e.q. (x & 8) == 4.
  814. TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
  815. const Expr *LHSExpr = B->getLHS()->IgnoreParens();
  816. const Expr *RHSExpr = B->getRHS()->IgnoreParens();
  817. const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
  818. const Expr *BoolExpr = RHSExpr;
  819. if (!IntLiteral) {
  820. IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
  821. BoolExpr = LHSExpr;
  822. }
  823. if (!IntLiteral)
  824. return TryResult();
  825. const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
  826. if (BitOp && (BitOp->getOpcode() == BO_And ||
  827. BitOp->getOpcode() == BO_Or)) {
  828. const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
  829. const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
  830. const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
  831. if (!IntLiteral2)
  832. IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
  833. if (!IntLiteral2)
  834. return TryResult();
  835. llvm::APInt L1 = IntLiteral->getValue();
  836. llvm::APInt L2 = IntLiteral2->getValue();
  837. if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
  838. (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
  839. if (BuildOpts.Observer)
  840. BuildOpts.Observer->compareBitwiseEquality(B,
  841. B->getOpcode() != BO_EQ);
  842. TryResult(B->getOpcode() != BO_EQ);
  843. }
  844. } else if (BoolExpr->isKnownToHaveBooleanValue()) {
  845. llvm::APInt IntValue = IntLiteral->getValue();
  846. if ((IntValue == 1) || (IntValue == 0)) {
  847. return TryResult();
  848. }
  849. return TryResult(B->getOpcode() != BO_EQ);
  850. }
  851. return TryResult();
  852. }
  853. TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
  854. const llvm::APSInt &Value1,
  855. const llvm::APSInt &Value2) {
  856. assert(Value1.isSigned() == Value2.isSigned());
  857. switch (Relation) {
  858. default:
  859. return TryResult();
  860. case BO_EQ:
  861. return TryResult(Value1 == Value2);
  862. case BO_NE:
  863. return TryResult(Value1 != Value2);
  864. case BO_LT:
  865. return TryResult(Value1 < Value2);
  866. case BO_LE:
  867. return TryResult(Value1 <= Value2);
  868. case BO_GT:
  869. return TryResult(Value1 > Value2);
  870. case BO_GE:
  871. return TryResult(Value1 >= Value2);
  872. }
  873. }
  874. /// Find a pair of comparison expressions with or without parentheses
  875. /// with a shared variable and constants and a logical operator between them
  876. /// that always evaluates to either true or false.
  877. /// e.g. if (x != 3 || x != 4)
  878. TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
  879. assert(B->isLogicalOp());
  880. const BinaryOperator *LHS =
  881. dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
  882. const BinaryOperator *RHS =
  883. dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
  884. if (!LHS || !RHS)
  885. return {};
  886. if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
  887. return {};
  888. const Expr *DeclExpr1;
  889. const Expr *NumExpr1;
  890. BinaryOperatorKind BO1;
  891. std::tie(DeclExpr1, BO1, NumExpr1) = tryNormalizeBinaryOperator(LHS);
  892. if (!DeclExpr1 || !NumExpr1)
  893. return {};
  894. const Expr *DeclExpr2;
  895. const Expr *NumExpr2;
  896. BinaryOperatorKind BO2;
  897. std::tie(DeclExpr2, BO2, NumExpr2) = tryNormalizeBinaryOperator(RHS);
  898. if (!DeclExpr2 || !NumExpr2)
  899. return {};
  900. // Check that it is the same variable on both sides.
  901. if (!Expr::isSameComparisonOperand(DeclExpr1, DeclExpr2))
  902. return {};
  903. // Make sure the user's intent is clear (e.g. they're comparing against two
  904. // int literals, or two things from the same enum)
  905. if (!areExprTypesCompatible(NumExpr1, NumExpr2))
  906. return {};
  907. Expr::EvalResult L1Result, L2Result;
  908. if (!NumExpr1->EvaluateAsInt(L1Result, *Context) ||
  909. !NumExpr2->EvaluateAsInt(L2Result, *Context))
  910. return {};
  911. llvm::APSInt L1 = L1Result.Val.getInt();
  912. llvm::APSInt L2 = L2Result.Val.getInt();
  913. // Can't compare signed with unsigned or with different bit width.
  914. if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
  915. return {};
  916. // Values that will be used to determine if result of logical
  917. // operator is always true/false
  918. const llvm::APSInt Values[] = {
  919. // Value less than both Value1 and Value2
  920. llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
  921. // L1
  922. L1,
  923. // Value between Value1 and Value2
  924. ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
  925. L1.isUnsigned()),
  926. // L2
  927. L2,
  928. // Value greater than both Value1 and Value2
  929. llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
  930. };
  931. // Check whether expression is always true/false by evaluating the following
  932. // * variable x is less than the smallest literal.
  933. // * variable x is equal to the smallest literal.
  934. // * Variable x is between smallest and largest literal.
  935. // * Variable x is equal to the largest literal.
  936. // * Variable x is greater than largest literal.
  937. bool AlwaysTrue = true, AlwaysFalse = true;
  938. // Track value of both subexpressions. If either side is always
  939. // true/false, another warning should have already been emitted.
  940. bool LHSAlwaysTrue = true, LHSAlwaysFalse = true;
  941. bool RHSAlwaysTrue = true, RHSAlwaysFalse = true;
  942. for (const llvm::APSInt &Value : Values) {
  943. TryResult Res1, Res2;
  944. Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
  945. Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
  946. if (!Res1.isKnown() || !Res2.isKnown())
  947. return {};
  948. if (B->getOpcode() == BO_LAnd) {
  949. AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
  950. AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
  951. } else {
  952. AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
  953. AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
  954. }
  955. LHSAlwaysTrue &= Res1.isTrue();
  956. LHSAlwaysFalse &= Res1.isFalse();
  957. RHSAlwaysTrue &= Res2.isTrue();
  958. RHSAlwaysFalse &= Res2.isFalse();
  959. }
  960. if (AlwaysTrue || AlwaysFalse) {
  961. if (!LHSAlwaysTrue && !LHSAlwaysFalse && !RHSAlwaysTrue &&
  962. !RHSAlwaysFalse && BuildOpts.Observer)
  963. BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
  964. return TryResult(AlwaysTrue);
  965. }
  966. return {};
  967. }
  968. /// A bitwise-or with a non-zero constant always evaluates to true.
  969. TryResult checkIncorrectBitwiseOrOperator(const BinaryOperator *B) {
  970. const Expr *LHSConstant =
  971. tryTransformToIntOrEnumConstant(B->getLHS()->IgnoreParenImpCasts());
  972. const Expr *RHSConstant =
  973. tryTransformToIntOrEnumConstant(B->getRHS()->IgnoreParenImpCasts());
  974. if ((LHSConstant && RHSConstant) || (!LHSConstant && !RHSConstant))
  975. return {};
  976. const Expr *Constant = LHSConstant ? LHSConstant : RHSConstant;
  977. Expr::EvalResult Result;
  978. if (!Constant->EvaluateAsInt(Result, *Context))
  979. return {};
  980. if (Result.Val.getInt() == 0)
  981. return {};
  982. if (BuildOpts.Observer)
  983. BuildOpts.Observer->compareBitwiseOr(B);
  984. return TryResult(true);
  985. }
  986. /// Try and evaluate an expression to an integer constant.
  987. bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
  988. if (!BuildOpts.PruneTriviallyFalseEdges)
  989. return false;
  990. return !S->isTypeDependent() &&
  991. !S->isValueDependent() &&
  992. S->EvaluateAsRValue(outResult, *Context);
  993. }
  994. /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
  995. /// if we can evaluate to a known value, otherwise return -1.
  996. TryResult tryEvaluateBool(Expr *S) {
  997. if (!BuildOpts.PruneTriviallyFalseEdges ||
  998. S->isTypeDependent() || S->isValueDependent())
  999. return {};
  1000. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
  1001. if (Bop->isLogicalOp() || Bop->isEqualityOp()) {
  1002. // Check the cache first.
  1003. CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
  1004. if (I != CachedBoolEvals.end())
  1005. return I->second; // already in map;
  1006. // Retrieve result at first, or the map might be updated.
  1007. TryResult Result = evaluateAsBooleanConditionNoCache(S);
  1008. CachedBoolEvals[S] = Result; // update or insert
  1009. return Result;
  1010. }
  1011. else {
  1012. switch (Bop->getOpcode()) {
  1013. default: break;
  1014. // For 'x & 0' and 'x * 0', we can determine that
  1015. // the value is always false.
  1016. case BO_Mul:
  1017. case BO_And: {
  1018. // If either operand is zero, we know the value
  1019. // must be false.
  1020. Expr::EvalResult LHSResult;
  1021. if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) {
  1022. llvm::APSInt IntVal = LHSResult.Val.getInt();
  1023. if (!IntVal.getBoolValue()) {
  1024. return TryResult(false);
  1025. }
  1026. }
  1027. Expr::EvalResult RHSResult;
  1028. if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) {
  1029. llvm::APSInt IntVal = RHSResult.Val.getInt();
  1030. if (!IntVal.getBoolValue()) {
  1031. return TryResult(false);
  1032. }
  1033. }
  1034. }
  1035. break;
  1036. }
  1037. }
  1038. }
  1039. return evaluateAsBooleanConditionNoCache(S);
  1040. }
  1041. /// Evaluate as boolean \param E without using the cache.
  1042. TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
  1043. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
  1044. if (Bop->isLogicalOp()) {
  1045. TryResult LHS = tryEvaluateBool(Bop->getLHS());
  1046. if (LHS.isKnown()) {
  1047. // We were able to evaluate the LHS, see if we can get away with not
  1048. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  1049. if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
  1050. return LHS.isTrue();
  1051. TryResult RHS = tryEvaluateBool(Bop->getRHS());
  1052. if (RHS.isKnown()) {
  1053. if (Bop->getOpcode() == BO_LOr)
  1054. return LHS.isTrue() || RHS.isTrue();
  1055. else
  1056. return LHS.isTrue() && RHS.isTrue();
  1057. }
  1058. } else {
  1059. TryResult RHS = tryEvaluateBool(Bop->getRHS());
  1060. if (RHS.isKnown()) {
  1061. // We can't evaluate the LHS; however, sometimes the result
  1062. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  1063. if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
  1064. return RHS.isTrue();
  1065. } else {
  1066. TryResult BopRes = checkIncorrectLogicOperator(Bop);
  1067. if (BopRes.isKnown())
  1068. return BopRes.isTrue();
  1069. }
  1070. }
  1071. return {};
  1072. } else if (Bop->isEqualityOp()) {
  1073. TryResult BopRes = checkIncorrectEqualityOperator(Bop);
  1074. if (BopRes.isKnown())
  1075. return BopRes.isTrue();
  1076. } else if (Bop->isRelationalOp()) {
  1077. TryResult BopRes = checkIncorrectRelationalOperator(Bop);
  1078. if (BopRes.isKnown())
  1079. return BopRes.isTrue();
  1080. } else if (Bop->getOpcode() == BO_Or) {
  1081. TryResult BopRes = checkIncorrectBitwiseOrOperator(Bop);
  1082. if (BopRes.isKnown())
  1083. return BopRes.isTrue();
  1084. }
  1085. }
  1086. bool Result;
  1087. if (E->EvaluateAsBooleanCondition(Result, *Context))
  1088. return Result;
  1089. return {};
  1090. }
  1091. bool hasTrivialDestructor(VarDecl *VD);
  1092. };
  1093. } // namespace
  1094. inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
  1095. const Stmt *stmt) const {
  1096. return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
  1097. }
  1098. bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
  1099. bool shouldAdd = BuildOpts.alwaysAdd(stmt);
  1100. if (!BuildOpts.forcedBlkExprs)
  1101. return shouldAdd;
  1102. if (lastLookup == stmt) {
  1103. if (cachedEntry) {
  1104. assert(cachedEntry->first == stmt);
  1105. return true;
  1106. }
  1107. return shouldAdd;
  1108. }
  1109. lastLookup = stmt;
  1110. // Perform the lookup!
  1111. CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
  1112. if (!fb) {
  1113. // No need to update 'cachedEntry', since it will always be null.
  1114. assert(!cachedEntry);
  1115. return shouldAdd;
  1116. }
  1117. CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
  1118. if (itr == fb->end()) {
  1119. cachedEntry = nullptr;
  1120. return shouldAdd;
  1121. }
  1122. cachedEntry = &*itr;
  1123. return true;
  1124. }
  1125. // FIXME: Add support for dependent-sized array types in C++?
  1126. // Does it even make sense to build a CFG for an uninstantiated template?
  1127. static const VariableArrayType *FindVA(const Type *t) {
  1128. while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
  1129. if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
  1130. if (vat->getSizeExpr())
  1131. return vat;
  1132. t = vt->getElementType().getTypePtr();
  1133. }
  1134. return nullptr;
  1135. }
  1136. void CFGBuilder::consumeConstructionContext(
  1137. const ConstructionContextLayer *Layer, Expr *E) {
  1138. assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
  1139. isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
  1140. if (const ConstructionContextLayer *PreviouslyStoredLayer =
  1141. ConstructionContextMap.lookup(E)) {
  1142. (void)PreviouslyStoredLayer;
  1143. // We might have visited this child when we were finding construction
  1144. // contexts within its parents.
  1145. assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
  1146. "Already within a different construction context!");
  1147. } else {
  1148. ConstructionContextMap[E] = Layer;
  1149. }
  1150. }
  1151. void CFGBuilder::findConstructionContexts(
  1152. const ConstructionContextLayer *Layer, Stmt *Child) {
  1153. if (!BuildOpts.AddRichCXXConstructors)
  1154. return;
  1155. if (!Child)
  1156. return;
  1157. auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
  1158. return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item,
  1159. Layer);
  1160. };
  1161. switch(Child->getStmtClass()) {
  1162. case Stmt::CXXConstructExprClass:
  1163. case Stmt::CXXTemporaryObjectExprClass: {
  1164. // Support pre-C++17 copy elision AST.
  1165. auto *CE = cast<CXXConstructExpr>(Child);
  1166. if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
  1167. findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
  1168. }
  1169. consumeConstructionContext(Layer, CE);
  1170. break;
  1171. }
  1172. // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
  1173. // FIXME: An isa<> would look much better but this whole switch is a
  1174. // workaround for an internal compiler error in MSVC 2015 (see r326021).
  1175. case Stmt::CallExprClass:
  1176. case Stmt::CXXMemberCallExprClass:
  1177. case Stmt::CXXOperatorCallExprClass:
  1178. case Stmt::UserDefinedLiteralClass:
  1179. case Stmt::ObjCMessageExprClass: {
  1180. auto *E = cast<Expr>(Child);
  1181. if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
  1182. consumeConstructionContext(Layer, E);
  1183. break;
  1184. }
  1185. case Stmt::ExprWithCleanupsClass: {
  1186. auto *Cleanups = cast<ExprWithCleanups>(Child);
  1187. findConstructionContexts(Layer, Cleanups->getSubExpr());
  1188. break;
  1189. }
  1190. case Stmt::CXXFunctionalCastExprClass: {
  1191. auto *Cast = cast<CXXFunctionalCastExpr>(Child);
  1192. findConstructionContexts(Layer, Cast->getSubExpr());
  1193. break;
  1194. }
  1195. case Stmt::ImplicitCastExprClass: {
  1196. auto *Cast = cast<ImplicitCastExpr>(Child);
  1197. // Should we support other implicit cast kinds?
  1198. switch (Cast->getCastKind()) {
  1199. case CK_NoOp:
  1200. case CK_ConstructorConversion:
  1201. findConstructionContexts(Layer, Cast->getSubExpr());
  1202. break;
  1203. default:
  1204. break;
  1205. }
  1206. break;
  1207. }
  1208. case Stmt::CXXBindTemporaryExprClass: {
  1209. auto *BTE = cast<CXXBindTemporaryExpr>(Child);
  1210. findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
  1211. break;
  1212. }
  1213. case Stmt::MaterializeTemporaryExprClass: {
  1214. // Normally we don't want to search in MaterializeTemporaryExpr because
  1215. // it indicates the beginning of a temporary object construction context,
  1216. // so it shouldn't be found in the middle. However, if it is the beginning
  1217. // of an elidable copy or move construction context, we need to include it.
  1218. if (Layer->getItem().getKind() ==
  1219. ConstructionContextItem::ElidableConstructorKind) {
  1220. auto *MTE = cast<MaterializeTemporaryExpr>(Child);
  1221. findConstructionContexts(withExtraLayer(MTE), MTE->GetTemporaryExpr());
  1222. }
  1223. break;
  1224. }
  1225. case Stmt::ConditionalOperatorClass: {
  1226. auto *CO = cast<ConditionalOperator>(Child);
  1227. if (Layer->getItem().getKind() !=
  1228. ConstructionContextItem::MaterializationKind) {
  1229. // If the object returned by the conditional operator is not going to be a
  1230. // temporary object that needs to be immediately materialized, then
  1231. // it must be C++17 with its mandatory copy elision. Do not yet promise
  1232. // to support this case.
  1233. assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
  1234. Context->getLangOpts().CPlusPlus17);
  1235. break;
  1236. }
  1237. findConstructionContexts(Layer, CO->getLHS());
  1238. findConstructionContexts(Layer, CO->getRHS());
  1239. break;
  1240. }
  1241. case Stmt::InitListExprClass: {
  1242. auto *ILE = cast<InitListExpr>(Child);
  1243. if (ILE->isTransparent()) {
  1244. findConstructionContexts(Layer, ILE->getInit(0));
  1245. break;
  1246. }
  1247. // TODO: Handle other cases. For now, fail to find construction contexts.
  1248. break;
  1249. }
  1250. default:
  1251. break;
  1252. }
  1253. }
  1254. void CFGBuilder::cleanupConstructionContext(Expr *E) {
  1255. assert(BuildOpts.AddRichCXXConstructors &&
  1256. "We should not be managing construction contexts!");
  1257. assert(ConstructionContextMap.count(E) &&
  1258. "Cannot exit construction context without the context!");
  1259. ConstructionContextMap.erase(E);
  1260. }
  1261. /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
  1262. /// arbitrary statement. Examples include a single expression or a function
  1263. /// body (compound statement). The ownership of the returned CFG is
  1264. /// transferred to the caller. If CFG construction fails, this method returns
  1265. /// NULL.
  1266. std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
  1267. assert(cfg.get());
  1268. if (!Statement)
  1269. return nullptr;
  1270. // Create an empty block that will serve as the exit block for the CFG. Since
  1271. // this is the first block added to the CFG, it will be implicitly registered
  1272. // as the exit block.
  1273. Succ = createBlock();
  1274. assert(Succ == &cfg->getExit());
  1275. Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
  1276. assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
  1277. "AddImplicitDtors and AddLifetime cannot be used at the same time");
  1278. if (BuildOpts.AddImplicitDtors)
  1279. if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
  1280. addImplicitDtorsForDestructor(DD);
  1281. // Visit the statements and create the CFG.
  1282. CFGBlock *B = addStmt(Statement);
  1283. if (badCFG)
  1284. return nullptr;
  1285. // For C++ constructor add initializers to CFG. Constructors of virtual bases
  1286. // are ignored unless the object is of the most derived class.
  1287. // class VBase { VBase() = default; VBase(int) {} };
  1288. // class A : virtual public VBase { A() : VBase(0) {} };
  1289. // class B : public A {};
  1290. // B b; // Constructor calls in order: VBase(), A(), B().
  1291. // // VBase(0) is ignored because A isn't the most derived class.
  1292. // This may result in the virtual base(s) being already initialized at this
  1293. // point, in which case we should jump right onto non-virtual bases and
  1294. // fields. To handle this, make a CFG branch. We only need to add one such
  1295. // branch per constructor, since the Standard states that all virtual bases
  1296. // shall be initialized before non-virtual bases and direct data members.
  1297. if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
  1298. CFGBlock *VBaseSucc = nullptr;
  1299. for (auto *I : llvm::reverse(CD->inits())) {
  1300. if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
  1301. I->isBaseInitializer() && I->isBaseVirtual()) {
  1302. // We've reached the first virtual base init while iterating in reverse
  1303. // order. Make a new block for virtual base initializers so that we
  1304. // could skip them.
  1305. VBaseSucc = Succ = B ? B : &cfg->getExit();
  1306. Block = createBlock();
  1307. }
  1308. B = addInitializer(I);
  1309. if (badCFG)
  1310. return nullptr;
  1311. }
  1312. if (VBaseSucc) {
  1313. // Make a branch block for potentially skipping virtual base initializers.
  1314. Succ = VBaseSucc;
  1315. B = createBlock();
  1316. B->setTerminator(
  1317. CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
  1318. addSuccessor(B, Block, true);
  1319. }
  1320. }
  1321. if (B)
  1322. Succ = B;
  1323. // Backpatch the gotos whose label -> block mappings we didn't know when we
  1324. // encountered them.
  1325. for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
  1326. E = BackpatchBlocks.end(); I != E; ++I ) {
  1327. CFGBlock *B = I->block;
  1328. if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) {
  1329. LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
  1330. // If there is no target for the goto, then we are looking at an
  1331. // incomplete AST. Handle this by not registering a successor.
  1332. if (LI == LabelMap.end())
  1333. continue;
  1334. JumpTarget JT = LI->second;
  1335. prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
  1336. JT.scopePosition);
  1337. prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
  1338. JT.scopePosition);
  1339. const VarDecl *VD = prependAutomaticObjScopeEndWithTerminator(
  1340. B, I->scopePosition, JT.scopePosition);
  1341. appendScopeBegin(JT.block, VD, G);
  1342. addSuccessor(B, JT.block);
  1343. };
  1344. if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) {
  1345. CFGBlock *Successor = (I+1)->block;
  1346. for (auto *L : G->labels()) {
  1347. LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
  1348. // If there is no target for the goto, then we are looking at an
  1349. // incomplete AST. Handle this by not registering a successor.
  1350. if (LI == LabelMap.end())
  1351. continue;
  1352. JumpTarget JT = LI->second;
  1353. // Successor has been added, so skip it.
  1354. if (JT.block == Successor)
  1355. continue;
  1356. addSuccessor(B, JT.block);
  1357. }
  1358. I++;
  1359. }
  1360. }
  1361. // Add successors to the Indirect Goto Dispatch block (if we have one).
  1362. if (CFGBlock *B = cfg->getIndirectGotoBlock())
  1363. for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
  1364. E = AddressTakenLabels.end(); I != E; ++I ) {
  1365. // Lookup the target block.
  1366. LabelMapTy::iterator LI = LabelMap.find(*I);
  1367. // If there is no target block that contains label, then we are looking
  1368. // at an incomplete AST. Handle this by not registering a successor.
  1369. if (LI == LabelMap.end()) continue;
  1370. addSuccessor(B, LI->second.block);
  1371. }
  1372. // Create an empty entry block that has no predecessors.
  1373. cfg->setEntry(createBlock());
  1374. if (BuildOpts.AddRichCXXConstructors)
  1375. assert(ConstructionContextMap.empty() &&
  1376. "Not all construction contexts were cleaned up!");
  1377. return std::move(cfg);
  1378. }
  1379. /// createBlock - Used to lazily create blocks that are connected
  1380. /// to the current (global) succcessor.
  1381. CFGBlock *CFGBuilder::createBlock(bool add_successor) {
  1382. CFGBlock *B = cfg->createBlock();
  1383. if (add_successor && Succ)
  1384. addSuccessor(B, Succ);
  1385. return B;
  1386. }
  1387. /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
  1388. /// CFG. It is *not* connected to the current (global) successor, and instead
  1389. /// directly tied to the exit block in order to be reachable.
  1390. CFGBlock *CFGBuilder::createNoReturnBlock() {
  1391. CFGBlock *B = createBlock(false);
  1392. B->setHasNoReturnElement();
  1393. addSuccessor(B, &cfg->getExit(), Succ);
  1394. return B;
  1395. }
  1396. /// addInitializer - Add C++ base or member initializer element to CFG.
  1397. CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
  1398. if (!BuildOpts.AddInitializers)
  1399. return Block;
  1400. bool HasTemporaries = false;
  1401. // Destructors of temporaries in initialization expression should be called
  1402. // after initialization finishes.
  1403. Expr *Init = I->getInit();
  1404. if (Init) {
  1405. HasTemporaries = isa<ExprWithCleanups>(Init);
  1406. if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
  1407. // Generate destructors for temporaries in initialization expression.
  1408. TempDtorContext Context;
  1409. VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
  1410. /*ExternallyDestructed=*/false, Context);
  1411. }
  1412. }
  1413. autoCreateBlock();
  1414. appendInitializer(Block, I);
  1415. if (Init) {
  1416. findConstructionContexts(
  1417. ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
  1418. Init);
  1419. if (HasTemporaries) {
  1420. // For expression with temporaries go directly to subexpression to omit
  1421. // generating destructors for the second time.
  1422. return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
  1423. }
  1424. if (BuildOpts.AddCXXDefaultInitExprInCtors) {
  1425. if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
  1426. // In general, appending the expression wrapped by a CXXDefaultInitExpr
  1427. // may cause the same Expr to appear more than once in the CFG. Doing it
  1428. // here is safe because there's only one initializer per field.
  1429. autoCreateBlock();
  1430. appendStmt(Block, Default);
  1431. if (Stmt *Child = Default->getExpr())
  1432. if (CFGBlock *R = Visit(Child))
  1433. Block = R;
  1434. return Block;
  1435. }
  1436. }
  1437. return Visit(Init);
  1438. }
  1439. return Block;
  1440. }
  1441. /// Retrieve the type of the temporary object whose lifetime was
  1442. /// extended by a local reference with the given initializer.
  1443. static QualType getReferenceInitTemporaryType(const Expr *Init,
  1444. bool *FoundMTE = nullptr) {
  1445. while (true) {
  1446. // Skip parentheses.
  1447. Init = Init->IgnoreParens();
  1448. // Skip through cleanups.
  1449. if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
  1450. Init = EWC->getSubExpr();
  1451. continue;
  1452. }
  1453. // Skip through the temporary-materialization expression.
  1454. if (const MaterializeTemporaryExpr *MTE
  1455. = dyn_cast<MaterializeTemporaryExpr>(Init)) {
  1456. Init = MTE->GetTemporaryExpr();
  1457. if (FoundMTE)
  1458. *FoundMTE = true;
  1459. continue;
  1460. }
  1461. // Skip sub-object accesses into rvalues.
  1462. SmallVector<const Expr *, 2> CommaLHSs;
  1463. SmallVector<SubobjectAdjustment, 2> Adjustments;
  1464. const Expr *SkippedInit =
  1465. Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  1466. if (SkippedInit != Init) {
  1467. Init = SkippedInit;
  1468. continue;
  1469. }
  1470. break;
  1471. }
  1472. return Init->getType();
  1473. }
  1474. // TODO: Support adding LoopExit element to the CFG in case where the loop is
  1475. // ended by ReturnStmt, GotoStmt or ThrowExpr.
  1476. void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
  1477. if(!BuildOpts.AddLoopExit)
  1478. return;
  1479. autoCreateBlock();
  1480. appendLoopExit(Block, LoopStmt);
  1481. }
  1482. void CFGBuilder::getDeclsWithEndedScope(LocalScope::const_iterator B,
  1483. LocalScope::const_iterator E, Stmt *S) {
  1484. if (!BuildOpts.AddScopes)
  1485. return;
  1486. if (B == E)
  1487. return;
  1488. // To go from B to E, one first goes up the scopes from B to P
  1489. // then sideways in one scope from P to P' and then down
  1490. // the scopes from P' to E.
  1491. // The lifetime of all objects between B and P end.
  1492. LocalScope::const_iterator P = B.shared_parent(E);
  1493. int Dist = B.distance(P);
  1494. if (Dist <= 0)
  1495. return;
  1496. for (LocalScope::const_iterator I = B; I != P; ++I)
  1497. if (I.pointsToFirstDeclaredVar())
  1498. DeclsWithEndedScope.insert(*I);
  1499. }
  1500. void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
  1501. LocalScope::const_iterator E,
  1502. Stmt *S) {
  1503. getDeclsWithEndedScope(B, E, S);
  1504. if (BuildOpts.AddScopes)
  1505. addScopesEnd(B, E, S);
  1506. if (BuildOpts.AddImplicitDtors)
  1507. addAutomaticObjDtors(B, E, S);
  1508. if (BuildOpts.AddLifetime)
  1509. addLifetimeEnds(B, E, S);
  1510. }
  1511. /// Add to current block automatic objects that leave the scope.
  1512. void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
  1513. LocalScope::const_iterator E, Stmt *S) {
  1514. if (!BuildOpts.AddLifetime)
  1515. return;
  1516. if (B == E)
  1517. return;
  1518. // To go from B to E, one first goes up the scopes from B to P
  1519. // then sideways in one scope from P to P' and then down
  1520. // the scopes from P' to E.
  1521. // The lifetime of all objects between B and P end.
  1522. LocalScope::const_iterator P = B.shared_parent(E);
  1523. int dist = B.distance(P);
  1524. if (dist <= 0)
  1525. return;
  1526. // We need to perform the scope leaving in reverse order
  1527. SmallVector<VarDecl *, 10> DeclsTrivial;
  1528. SmallVector<VarDecl *, 10> DeclsNonTrivial;
  1529. DeclsTrivial.reserve(dist);
  1530. DeclsNonTrivial.reserve(dist);
  1531. for (LocalScope::const_iterator I = B; I != P; ++I)
  1532. if (hasTrivialDestructor(*I))
  1533. DeclsTrivial.push_back(*I);
  1534. else
  1535. DeclsNonTrivial.push_back(*I);
  1536. autoCreateBlock();
  1537. // object with trivial destructor end their lifetime last (when storage
  1538. // duration ends)
  1539. for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
  1540. E = DeclsTrivial.rend();
  1541. I != E; ++I)
  1542. appendLifetimeEnds(Block, *I, S);
  1543. for (SmallVectorImpl<VarDecl *>::reverse_iterator
  1544. I = DeclsNonTrivial.rbegin(),
  1545. E = DeclsNonTrivial.rend();
  1546. I != E; ++I)
  1547. appendLifetimeEnds(Block, *I, S);
  1548. }
  1549. /// Add to current block markers for ending scopes.
  1550. void CFGBuilder::addScopesEnd(LocalScope::const_iterator B,
  1551. LocalScope::const_iterator E, Stmt *S) {
  1552. // If implicit destructors are enabled, we'll add scope ends in
  1553. // addAutomaticObjDtors.
  1554. if (BuildOpts.AddImplicitDtors)
  1555. return;
  1556. autoCreateBlock();
  1557. for (auto I = DeclsWithEndedScope.rbegin(), E = DeclsWithEndedScope.rend();
  1558. I != E; ++I)
  1559. appendScopeEnd(Block, *I, S);
  1560. return;
  1561. }
  1562. /// addAutomaticObjDtors - Add to current block automatic objects destructors
  1563. /// for objects in range of local scope positions. Use S as trigger statement
  1564. /// for destructors.
  1565. void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
  1566. LocalScope::const_iterator E, Stmt *S) {
  1567. if (!BuildOpts.AddImplicitDtors)
  1568. return;
  1569. if (B == E)
  1570. return;
  1571. // We need to append the destructors in reverse order, but any one of them
  1572. // may be a no-return destructor which changes the CFG. As a result, buffer
  1573. // this sequence up and replay them in reverse order when appending onto the
  1574. // CFGBlock(s).
  1575. SmallVector<VarDecl*, 10> Decls;
  1576. Decls.reserve(B.distance(E));
  1577. for (LocalScope::const_iterator I = B; I != E; ++I)
  1578. Decls.push_back(*I);
  1579. for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
  1580. E = Decls.rend();
  1581. I != E; ++I) {
  1582. if (hasTrivialDestructor(*I)) {
  1583. // If AddScopes is enabled and *I is a first variable in a scope, add a
  1584. // ScopeEnd marker in a Block.
  1585. if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I)) {
  1586. autoCreateBlock();
  1587. appendScopeEnd(Block, *I, S);
  1588. }
  1589. continue;
  1590. }
  1591. // If this destructor is marked as a no-return destructor, we need to
  1592. // create a new block for the destructor which does not have as a successor
  1593. // anything built thus far: control won't flow out of this block.
  1594. QualType Ty = (*I)->getType();
  1595. if (Ty->isReferenceType()) {
  1596. Ty = getReferenceInitTemporaryType((*I)->getInit());
  1597. }
  1598. Ty = Context->getBaseElementType(Ty);
  1599. if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
  1600. Block = createNoReturnBlock();
  1601. else
  1602. autoCreateBlock();
  1603. // Add ScopeEnd just after automatic obj destructor.
  1604. if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I))
  1605. appendScopeEnd(Block, *I, S);
  1606. appendAutomaticObjDtor(Block, *I, S);
  1607. }
  1608. }
  1609. /// addImplicitDtorsForDestructor - Add implicit destructors generated for
  1610. /// base and member objects in destructor.
  1611. void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
  1612. assert(BuildOpts.AddImplicitDtors &&
  1613. "Can be called only when dtors should be added");
  1614. const CXXRecordDecl *RD = DD->getParent();
  1615. // At the end destroy virtual base objects.
  1616. for (const auto &VI : RD->vbases()) {
  1617. // TODO: Add a VirtualBaseBranch to see if the most derived class
  1618. // (which is different from the current class) is responsible for
  1619. // destroying them.
  1620. const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
  1621. if (!CD->hasTrivialDestructor()) {
  1622. autoCreateBlock();
  1623. appendBaseDtor(Block, &VI);
  1624. }
  1625. }
  1626. // Before virtual bases destroy direct base objects.
  1627. for (const auto &BI : RD->bases()) {
  1628. if (!BI.isVirtual()) {
  1629. const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
  1630. if (!CD->hasTrivialDestructor()) {
  1631. autoCreateBlock();
  1632. appendBaseDtor(Block, &BI);
  1633. }
  1634. }
  1635. }
  1636. // First destroy member objects.
  1637. for (auto *FI : RD->fields()) {
  1638. // Check for constant size array. Set type to array element type.
  1639. QualType QT = FI->getType();
  1640. if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
  1641. if (AT->getSize() == 0)
  1642. continue;
  1643. QT = AT->getElementType();
  1644. }
  1645. if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
  1646. if (!CD->hasTrivialDestructor()) {
  1647. autoCreateBlock();
  1648. appendMemberDtor(Block, FI);
  1649. }
  1650. }
  1651. }
  1652. /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
  1653. /// way return valid LocalScope object.
  1654. LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
  1655. if (Scope)
  1656. return Scope;
  1657. llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
  1658. return new (alloc.Allocate<LocalScope>())
  1659. LocalScope(BumpVectorContext(alloc), ScopePos);
  1660. }
  1661. /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
  1662. /// that should create implicit scope (e.g. if/else substatements).
  1663. void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
  1664. if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
  1665. !BuildOpts.AddScopes)
  1666. return;
  1667. LocalScope *Scope = nullptr;
  1668. // For compound statement we will be creating explicit scope.
  1669. if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
  1670. for (auto *BI : CS->body()) {
  1671. Stmt *SI = BI->stripLabelLikeStatements();
  1672. if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
  1673. Scope = addLocalScopeForDeclStmt(DS, Scope);
  1674. }
  1675. return;
  1676. }
  1677. // For any other statement scope will be implicit and as such will be
  1678. // interesting only for DeclStmt.
  1679. if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
  1680. addLocalScopeForDeclStmt(DS);
  1681. }
  1682. /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
  1683. /// reuse Scope if not NULL.
  1684. LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
  1685. LocalScope* Scope) {
  1686. if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
  1687. !BuildOpts.AddScopes)
  1688. return Scope;
  1689. for (auto *DI : DS->decls())
  1690. if (VarDecl *VD = dyn_cast<VarDecl>(DI))
  1691. Scope = addLocalScopeForVarDecl(VD, Scope);
  1692. return Scope;
  1693. }
  1694. bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
  1695. // Check for const references bound to temporary. Set type to pointee.
  1696. QualType QT = VD->getType();
  1697. if (QT->isReferenceType()) {
  1698. // Attempt to determine whether this declaration lifetime-extends a
  1699. // temporary.
  1700. //
  1701. // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
  1702. // temporaries, and a single declaration can extend multiple temporaries.
  1703. // We should look at the storage duration on each nested
  1704. // MaterializeTemporaryExpr instead.
  1705. const Expr *Init = VD->getInit();
  1706. if (!Init) {
  1707. // Probably an exception catch-by-reference variable.
  1708. // FIXME: It doesn't really mean that the object has a trivial destructor.
  1709. // Also are there other cases?
  1710. return true;
  1711. }
  1712. // Lifetime-extending a temporary?
  1713. bool FoundMTE = false;
  1714. QT = getReferenceInitTemporaryType(Init, &FoundMTE);
  1715. if (!FoundMTE)
  1716. return true;
  1717. }
  1718. // Check for constant size array. Set type to array element type.
  1719. while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
  1720. if (AT->getSize() == 0)
  1721. return true;
  1722. QT = AT->getElementType();
  1723. }
  1724. // Check if type is a C++ class with non-trivial destructor.
  1725. if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
  1726. return !CD->hasDefinition() || CD->hasTrivialDestructor();
  1727. return true;
  1728. }
  1729. /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
  1730. /// create add scope for automatic objects and temporary objects bound to
  1731. /// const reference. Will reuse Scope if not NULL.
  1732. LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
  1733. LocalScope* Scope) {
  1734. assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
  1735. "AddImplicitDtors and AddLifetime cannot be used at the same time");
  1736. if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
  1737. !BuildOpts.AddScopes)
  1738. return Scope;
  1739. // Check if variable is local.
  1740. switch (VD->getStorageClass()) {
  1741. case SC_None:
  1742. case SC_Auto:
  1743. case SC_Register:
  1744. break;
  1745. default: return Scope;
  1746. }
  1747. if (BuildOpts.AddImplicitDtors) {
  1748. if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
  1749. // Add the variable to scope
  1750. Scope = createOrReuseLocalScope(Scope);
  1751. Scope->addVar(VD);
  1752. ScopePos = Scope->begin();
  1753. }
  1754. return Scope;
  1755. }
  1756. assert(BuildOpts.AddLifetime);
  1757. // Add the variable to scope
  1758. Scope = createOrReuseLocalScope(Scope);
  1759. Scope->addVar(VD);
  1760. ScopePos = Scope->begin();
  1761. return Scope;
  1762. }
  1763. /// addLocalScopeAndDtors - For given statement add local scope for it and
  1764. /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
  1765. void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
  1766. LocalScope::const_iterator scopeBeginPos = ScopePos;
  1767. addLocalScopeForStmt(S);
  1768. addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
  1769. }
  1770. /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
  1771. /// variables with automatic storage duration to CFGBlock's elements vector.
  1772. /// Elements will be prepended to physical beginning of the vector which
  1773. /// happens to be logical end. Use blocks terminator as statement that specifies
  1774. /// destructors call site.
  1775. /// FIXME: This mechanism for adding automatic destructors doesn't handle
  1776. /// no-return destructors properly.
  1777. void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
  1778. LocalScope::const_iterator B, LocalScope::const_iterator E) {
  1779. if (!BuildOpts.AddImplicitDtors)
  1780. return;
  1781. BumpVectorContext &C = cfg->getBumpVectorContext();
  1782. CFGBlock::iterator InsertPos
  1783. = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
  1784. for (LocalScope::const_iterator I = B; I != E; ++I)
  1785. InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
  1786. Blk->getTerminatorStmt());
  1787. }
  1788. /// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
  1789. /// variables with automatic storage duration to CFGBlock's elements vector.
  1790. /// Elements will be prepended to physical beginning of the vector which
  1791. /// happens to be logical end. Use blocks terminator as statement that specifies
  1792. /// where lifetime ends.
  1793. void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
  1794. CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
  1795. if (!BuildOpts.AddLifetime)
  1796. return;
  1797. BumpVectorContext &C = cfg->getBumpVectorContext();
  1798. CFGBlock::iterator InsertPos =
  1799. Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
  1800. for (LocalScope::const_iterator I = B; I != E; ++I) {
  1801. InsertPos =
  1802. Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminatorStmt());
  1803. }
  1804. }
  1805. /// prependAutomaticObjScopeEndWithTerminator - Prepend scope end CFGElements for
  1806. /// variables with automatic storage duration to CFGBlock's elements vector.
  1807. /// Elements will be prepended to physical beginning of the vector which
  1808. /// happens to be logical end. Use blocks terminator as statement that specifies
  1809. /// where scope ends.
  1810. const VarDecl *
  1811. CFGBuilder::prependAutomaticObjScopeEndWithTerminator(
  1812. CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
  1813. if (!BuildOpts.AddScopes)
  1814. return nullptr;
  1815. BumpVectorContext &C = cfg->getBumpVectorContext();
  1816. CFGBlock::iterator InsertPos =
  1817. Blk->beginScopeEndInsert(Blk->end(), 1, C);
  1818. LocalScope::const_iterator PlaceToInsert = B;
  1819. for (LocalScope::const_iterator I = B; I != E; ++I)
  1820. PlaceToInsert = I;
  1821. Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminatorStmt());
  1822. return *PlaceToInsert;
  1823. }
  1824. /// Visit - Walk the subtree of a statement and add extra
  1825. /// blocks for ternary operators, &&, and ||. We also process "," and
  1826. /// DeclStmts (which may contain nested control-flow).
  1827. CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
  1828. bool ExternallyDestructed) {
  1829. if (!S) {
  1830. badCFG = true;
  1831. return nullptr;
  1832. }
  1833. if (Expr *E = dyn_cast<Expr>(S))
  1834. S = E->IgnoreParens();
  1835. if (Context->getLangOpts().OpenMP)
  1836. if (auto *D = dyn_cast<OMPExecutableDirective>(S))
  1837. return VisitOMPExecutableDirective(D, asc);
  1838. switch (S->getStmtClass()) {
  1839. default:
  1840. return VisitStmt(S, asc);
  1841. case Stmt::AddrLabelExprClass:
  1842. return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
  1843. case Stmt::BinaryConditionalOperatorClass:
  1844. return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
  1845. case Stmt::BinaryOperatorClass:
  1846. return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
  1847. case Stmt::BlockExprClass:
  1848. return VisitBlockExpr(cast<BlockExpr>(S), asc);
  1849. case Stmt::BreakStmtClass:
  1850. return VisitBreakStmt(cast<BreakStmt>(S));
  1851. case Stmt::CallExprClass:
  1852. case Stmt::CXXOperatorCallExprClass:
  1853. case Stmt::CXXMemberCallExprClass:
  1854. case Stmt::UserDefinedLiteralClass:
  1855. return VisitCallExpr(cast<CallExpr>(S), asc);
  1856. case Stmt::CaseStmtClass:
  1857. return VisitCaseStmt(cast<CaseStmt>(S));
  1858. case Stmt::ChooseExprClass:
  1859. return VisitChooseExpr(cast<ChooseExpr>(S), asc);
  1860. case Stmt::CompoundStmtClass:
  1861. return VisitCompoundStmt(cast<CompoundStmt>(S), ExternallyDestructed);
  1862. case Stmt::ConditionalOperatorClass:
  1863. return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
  1864. case Stmt::ContinueStmtClass:
  1865. return VisitContinueStmt(cast<ContinueStmt>(S));
  1866. case Stmt::CXXCatchStmtClass:
  1867. return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
  1868. case Stmt::ExprWithCleanupsClass:
  1869. return VisitExprWithCleanups(cast<ExprWithCleanups>(S),
  1870. asc, ExternallyDestructed);
  1871. case Stmt::CXXDefaultArgExprClass:
  1872. case Stmt::CXXDefaultInitExprClass:
  1873. // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
  1874. // called function's declaration, not by the caller. If we simply add
  1875. // this expression to the CFG, we could end up with the same Expr
  1876. // appearing multiple times.
  1877. // PR13385 / <rdar://problem/12156507>
  1878. //
  1879. // It's likewise possible for multiple CXXDefaultInitExprs for the same
  1880. // expression to be used in the same function (through aggregate
  1881. // initialization).
  1882. return VisitStmt(S, asc);
  1883. case Stmt::CXXBindTemporaryExprClass:
  1884. return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
  1885. case Stmt::CXXConstructExprClass:
  1886. return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
  1887. case Stmt::CXXNewExprClass:
  1888. return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
  1889. case Stmt::CXXDeleteExprClass:
  1890. return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
  1891. case Stmt::CXXFunctionalCastExprClass:
  1892. return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
  1893. case Stmt::CXXTemporaryObjectExprClass:
  1894. return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
  1895. case Stmt::CXXThrowExprClass:
  1896. return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
  1897. case Stmt::CXXTryStmtClass:
  1898. return VisitCXXTryStmt(cast<CXXTryStmt>(S));
  1899. case Stmt::CXXForRangeStmtClass:
  1900. return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
  1901. case Stmt::DeclStmtClass:
  1902. return VisitDeclStmt(cast<DeclStmt>(S));
  1903. case Stmt::DefaultStmtClass:
  1904. return VisitDefaultStmt(cast<DefaultStmt>(S));
  1905. case Stmt::DoStmtClass:
  1906. return VisitDoStmt(cast<DoStmt>(S));
  1907. case Stmt::ForStmtClass:
  1908. return VisitForStmt(cast<ForStmt>(S));
  1909. case Stmt::GotoStmtClass:
  1910. return VisitGotoStmt(cast<GotoStmt>(S));
  1911. case Stmt::GCCAsmStmtClass:
  1912. return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc);
  1913. case Stmt::IfStmtClass:
  1914. return VisitIfStmt(cast<IfStmt>(S));
  1915. case Stmt::ImplicitCastExprClass:
  1916. return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
  1917. case Stmt::ConstantExprClass:
  1918. return VisitConstantExpr(cast<ConstantExpr>(S), asc);
  1919. case Stmt::IndirectGotoStmtClass:
  1920. return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
  1921. case Stmt::LabelStmtClass:
  1922. return VisitLabelStmt(cast<LabelStmt>(S));
  1923. case Stmt::LambdaExprClass:
  1924. return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
  1925. case Stmt::MaterializeTemporaryExprClass:
  1926. return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
  1927. asc);
  1928. case Stmt::MemberExprClass:
  1929. return VisitMemberExpr(cast<MemberExpr>(S), asc);
  1930. case Stmt::NullStmtClass:
  1931. return Block;
  1932. case Stmt::ObjCAtCatchStmtClass:
  1933. return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
  1934. case Stmt::ObjCAutoreleasePoolStmtClass:
  1935. return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
  1936. case Stmt::ObjCAtSynchronizedStmtClass:
  1937. return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
  1938. case Stmt::ObjCAtThrowStmtClass:
  1939. return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
  1940. case Stmt::ObjCAtTryStmtClass:
  1941. return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
  1942. case Stmt::ObjCForCollectionStmtClass:
  1943. return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
  1944. case Stmt::ObjCMessageExprClass:
  1945. return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
  1946. case Stmt::OpaqueValueExprClass:
  1947. return Block;
  1948. case Stmt::PseudoObjectExprClass:
  1949. return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
  1950. case Stmt::ReturnStmtClass:
  1951. case Stmt::CoreturnStmtClass:
  1952. return VisitReturnStmt(S);
  1953. case Stmt::SEHExceptStmtClass:
  1954. return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
  1955. case Stmt::SEHFinallyStmtClass:
  1956. return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
  1957. case Stmt::SEHLeaveStmtClass:
  1958. return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
  1959. case Stmt::SEHTryStmtClass:
  1960. return VisitSEHTryStmt(cast<SEHTryStmt>(S));
  1961. case Stmt::UnaryExprOrTypeTraitExprClass:
  1962. return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  1963. asc);
  1964. case Stmt::StmtExprClass:
  1965. return VisitStmtExpr(cast<StmtExpr>(S), asc);
  1966. case Stmt::SwitchStmtClass:
  1967. return VisitSwitchStmt(cast<SwitchStmt>(S));
  1968. case Stmt::UnaryOperatorClass:
  1969. return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
  1970. case Stmt::WhileStmtClass:
  1971. return VisitWhileStmt(cast<WhileStmt>(S));
  1972. }
  1973. }
  1974. CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
  1975. if (asc.alwaysAdd(*this, S)) {
  1976. autoCreateBlock();
  1977. appendStmt(Block, S);
  1978. }
  1979. return VisitChildren(S);
  1980. }
  1981. /// VisitChildren - Visit the children of a Stmt.
  1982. CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
  1983. CFGBlock *B = Block;
  1984. // Visit the children in their reverse order so that they appear in
  1985. // left-to-right (natural) order in the CFG.
  1986. reverse_children RChildren(S);
  1987. for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
  1988. I != E; ++I) {
  1989. if (Stmt *Child = *I)
  1990. if (CFGBlock *R = Visit(Child))
  1991. B = R;
  1992. }
  1993. return B;
  1994. }
  1995. CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
  1996. AddStmtChoice asc) {
  1997. AddressTakenLabels.insert(A->getLabel());
  1998. if (asc.alwaysAdd(*this, A)) {
  1999. autoCreateBlock();
  2000. appendStmt(Block, A);
  2001. }
  2002. return Block;
  2003. }
  2004. CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
  2005. AddStmtChoice asc) {
  2006. if (asc.alwaysAdd(*this, U)) {
  2007. autoCreateBlock();
  2008. appendStmt(Block, U);
  2009. }
  2010. if (U->getOpcode() == UO_LNot)
  2011. tryEvaluateBool(U->getSubExpr()->IgnoreParens());
  2012. return Visit(U->getSubExpr(), AddStmtChoice());
  2013. }
  2014. CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
  2015. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  2016. appendStmt(ConfluenceBlock, B);
  2017. if (badCFG)
  2018. return nullptr;
  2019. return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
  2020. ConfluenceBlock).first;
  2021. }
  2022. std::pair<CFGBlock*, CFGBlock*>
  2023. CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
  2024. Stmt *Term,
  2025. CFGBlock *TrueBlock,
  2026. CFGBlock *FalseBlock) {
  2027. // Introspect the RHS. If it is a nested logical operation, we recursively
  2028. // build the CFG using this function. Otherwise, resort to default
  2029. // CFG construction behavior.
  2030. Expr *RHS = B->getRHS()->IgnoreParens();
  2031. CFGBlock *RHSBlock, *ExitBlock;
  2032. do {
  2033. if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
  2034. if (B_RHS->isLogicalOp()) {
  2035. std::tie(RHSBlock, ExitBlock) =
  2036. VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
  2037. break;
  2038. }
  2039. // The RHS is not a nested logical operation. Don't push the terminator
  2040. // down further, but instead visit RHS and construct the respective
  2041. // pieces of the CFG, and link up the RHSBlock with the terminator
  2042. // we have been provided.
  2043. ExitBlock = RHSBlock = createBlock(false);
  2044. // Even though KnownVal is only used in the else branch of the next
  2045. // conditional, tryEvaluateBool performs additional checking on the
  2046. // Expr, so it should be called unconditionally.
  2047. TryResult KnownVal = tryEvaluateBool(RHS);
  2048. if (!KnownVal.isKnown())
  2049. KnownVal = tryEvaluateBool(B);
  2050. if (!Term) {
  2051. assert(TrueBlock == FalseBlock);
  2052. addSuccessor(RHSBlock, TrueBlock);
  2053. }
  2054. else {
  2055. RHSBlock->setTerminator(Term);
  2056. addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
  2057. addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
  2058. }
  2059. Block = RHSBlock;
  2060. RHSBlock = addStmt(RHS);
  2061. }
  2062. while (false);
  2063. if (badCFG)
  2064. return std::make_pair(nullptr, nullptr);
  2065. // Generate the blocks for evaluating the LHS.
  2066. Expr *LHS = B->getLHS()->IgnoreParens();
  2067. if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
  2068. if (B_LHS->isLogicalOp()) {
  2069. if (B->getOpcode() == BO_LOr)
  2070. FalseBlock = RHSBlock;
  2071. else
  2072. TrueBlock = RHSBlock;
  2073. // For the LHS, treat 'B' as the terminator that we want to sink
  2074. // into the nested branch. The RHS always gets the top-most
  2075. // terminator.
  2076. return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
  2077. }
  2078. // Create the block evaluating the LHS.
  2079. // This contains the '&&' or '||' as the terminator.
  2080. CFGBlock *LHSBlock = createBlock(false);
  2081. LHSBlock->setTerminator(B);
  2082. Block = LHSBlock;
  2083. CFGBlock *EntryLHSBlock = addStmt(LHS);
  2084. if (badCFG)
  2085. return std::make_pair(nullptr, nullptr);
  2086. // See if this is a known constant.
  2087. TryResult KnownVal = tryEvaluateBool(LHS);
  2088. // Now link the LHSBlock with RHSBlock.
  2089. if (B->getOpcode() == BO_LOr) {
  2090. addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
  2091. addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
  2092. } else {
  2093. assert(B->getOpcode() == BO_LAnd);
  2094. addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
  2095. addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
  2096. }
  2097. return std::make_pair(EntryLHSBlock, ExitBlock);
  2098. }
  2099. CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
  2100. AddStmtChoice asc) {
  2101. // && or ||
  2102. if (B->isLogicalOp())
  2103. return VisitLogicalOperator(B);
  2104. if (B->getOpcode() == BO_Comma) { // ,
  2105. autoCreateBlock();
  2106. appendStmt(Block, B);
  2107. addStmt(B->getRHS());
  2108. return addStmt(B->getLHS());
  2109. }
  2110. if (B->isAssignmentOp()) {
  2111. if (asc.alwaysAdd(*this, B)) {
  2112. autoCreateBlock();
  2113. appendStmt(Block, B);
  2114. }
  2115. Visit(B->getLHS());
  2116. return Visit(B->getRHS());
  2117. }
  2118. if (asc.alwaysAdd(*this, B)) {
  2119. autoCreateBlock();
  2120. appendStmt(Block, B);
  2121. }
  2122. if (B->isEqualityOp() || B->isRelationalOp())
  2123. tryEvaluateBool(B);
  2124. CFGBlock *RBlock = Visit(B->getRHS());
  2125. CFGBlock *LBlock = Visit(B->getLHS());
  2126. // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
  2127. // containing a DoStmt, and the LHS doesn't create a new block, then we should
  2128. // return RBlock. Otherwise we'll incorrectly return NULL.
  2129. return (LBlock ? LBlock : RBlock);
  2130. }
  2131. CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
  2132. if (asc.alwaysAdd(*this, E)) {
  2133. autoCreateBlock();
  2134. appendStmt(Block, E);
  2135. }
  2136. return Block;
  2137. }
  2138. CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
  2139. // "break" is a control-flow statement. Thus we stop processing the current
  2140. // block.
  2141. if (badCFG)
  2142. return nullptr;
  2143. // Now create a new block that ends with the break statement.
  2144. Block = createBlock(false);
  2145. Block->setTerminator(B);
  2146. // If there is no target for the break, then we are looking at an incomplete
  2147. // AST. This means that the CFG cannot be constructed.
  2148. if (BreakJumpTarget.block) {
  2149. addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
  2150. addSuccessor(Block, BreakJumpTarget.block);
  2151. } else
  2152. badCFG = true;
  2153. return Block;
  2154. }
  2155. static bool CanThrow(Expr *E, ASTContext &Ctx) {
  2156. QualType Ty = E->getType();
  2157. if (Ty->isFunctionPointerType() || Ty->isBlockPointerType())
  2158. Ty = Ty->getPointeeType();
  2159. const FunctionType *FT = Ty->getAs<FunctionType>();
  2160. if (FT) {
  2161. if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
  2162. if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
  2163. Proto->isNothrow())
  2164. return false;
  2165. }
  2166. return true;
  2167. }
  2168. CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
  2169. // Compute the callee type.
  2170. QualType calleeType = C->getCallee()->getType();
  2171. if (calleeType == Context->BoundMemberTy) {
  2172. QualType boundType = Expr::findBoundMemberType(C->getCallee());
  2173. // We should only get a null bound type if processing a dependent
  2174. // CFG. Recover by assuming nothing.
  2175. if (!boundType.isNull()) calleeType = boundType;
  2176. }
  2177. // If this is a call to a no-return function, this stops the block here.
  2178. bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
  2179. bool AddEHEdge = false;
  2180. // Languages without exceptions are assumed to not throw.
  2181. if (Context->getLangOpts().Exceptions) {
  2182. if (BuildOpts.AddEHEdges)
  2183. AddEHEdge = true;
  2184. }
  2185. // If this is a call to a builtin function, it might not actually evaluate
  2186. // its arguments. Don't add them to the CFG if this is the case.
  2187. bool OmitArguments = false;
  2188. if (FunctionDecl *FD = C->getDirectCallee()) {
  2189. // TODO: Support construction contexts for variadic function arguments.
  2190. // These are a bit problematic and not very useful because passing
  2191. // C++ objects as C-style variadic arguments doesn't work in general
  2192. // (see [expr.call]).
  2193. if (!FD->isVariadic())
  2194. findConstructionContextsForArguments(C);
  2195. if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
  2196. NoReturn = true;
  2197. if (FD->hasAttr<NoThrowAttr>())
  2198. AddEHEdge = false;
  2199. if (FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
  2200. FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
  2201. OmitArguments = true;
  2202. }
  2203. if (!CanThrow(C->getCallee(), *Context))
  2204. AddEHEdge = false;
  2205. if (OmitArguments) {
  2206. assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
  2207. assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
  2208. autoCreateBlock();
  2209. appendStmt(Block, C);
  2210. return Visit(C->getCallee());
  2211. }
  2212. if (!NoReturn && !AddEHEdge) {
  2213. autoCreateBlock();
  2214. appendCall(Block, C);
  2215. return VisitChildren(C);
  2216. }
  2217. if (Block) {
  2218. Succ = Block;
  2219. if (badCFG)
  2220. return nullptr;
  2221. }
  2222. if (NoReturn)
  2223. Block = createNoReturnBlock();
  2224. else
  2225. Block = createBlock();
  2226. appendCall(Block, C);
  2227. if (AddEHEdge) {
  2228. // Add exceptional edges.
  2229. if (TryTerminatedBlock)
  2230. addSuccessor(Block, TryTerminatedBlock);
  2231. else
  2232. addSuccessor(Block, &cfg->getExit());
  2233. }
  2234. return VisitChildren(C);
  2235. }
  2236. CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
  2237. AddStmtChoice asc) {
  2238. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  2239. appendStmt(ConfluenceBlock, C);
  2240. if (badCFG)
  2241. return nullptr;
  2242. AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
  2243. Succ = ConfluenceBlock;
  2244. Block = nullptr;
  2245. CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
  2246. if (badCFG)
  2247. return nullptr;
  2248. Succ = ConfluenceBlock;
  2249. Block = nullptr;
  2250. CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
  2251. if (badCFG)
  2252. return nullptr;
  2253. Block = createBlock(false);
  2254. // See if this is a known constant.
  2255. const TryResult& KnownVal = tryEvaluateBool(C->getCond());
  2256. addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
  2257. addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
  2258. Block->setTerminator(C);
  2259. return addStmt(C->getCond());
  2260. }
  2261. CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed) {
  2262. LocalScope::const_iterator scopeBeginPos = ScopePos;
  2263. addLocalScopeForStmt(C);
  2264. if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
  2265. // If the body ends with a ReturnStmt, the dtors will be added in
  2266. // VisitReturnStmt.
  2267. addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
  2268. }
  2269. CFGBlock *LastBlock = Block;
  2270. for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
  2271. I != E; ++I ) {
  2272. // If we hit a segment of code just containing ';' (NullStmts), we can
  2273. // get a null block back. In such cases, just use the LastBlock
  2274. CFGBlock *newBlock = Visit(*I, AddStmtChoice::AlwaysAdd,
  2275. ExternallyDestructed);
  2276. if (newBlock)
  2277. LastBlock = newBlock;
  2278. if (badCFG)
  2279. return nullptr;
  2280. ExternallyDestructed = false;
  2281. }
  2282. return LastBlock;
  2283. }
  2284. CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
  2285. AddStmtChoice asc) {
  2286. const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
  2287. const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
  2288. // Create the confluence block that will "merge" the results of the ternary
  2289. // expression.
  2290. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  2291. appendStmt(ConfluenceBlock, C);
  2292. if (badCFG)
  2293. return nullptr;
  2294. AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
  2295. // Create a block for the LHS expression if there is an LHS expression. A
  2296. // GCC extension allows LHS to be NULL, causing the condition to be the
  2297. // value that is returned instead.
  2298. // e.g: x ?: y is shorthand for: x ? x : y;
  2299. Succ = ConfluenceBlock;
  2300. Block = nullptr;
  2301. CFGBlock *LHSBlock = nullptr;
  2302. const Expr *trueExpr = C->getTrueExpr();
  2303. if (trueExpr != opaqueValue) {
  2304. LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
  2305. if (badCFG)
  2306. return nullptr;
  2307. Block = nullptr;
  2308. }
  2309. else
  2310. LHSBlock = ConfluenceBlock;
  2311. // Create the block for the RHS expression.
  2312. Succ = ConfluenceBlock;
  2313. CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
  2314. if (badCFG)
  2315. return nullptr;
  2316. // If the condition is a logical '&&' or '||', build a more accurate CFG.
  2317. if (BinaryOperator *Cond =
  2318. dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
  2319. if (Cond->isLogicalOp())
  2320. return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
  2321. // Create the block that will contain the condition.
  2322. Block = createBlock(false);
  2323. // See if this is a known constant.
  2324. const TryResult& KnownVal = tryEvaluateBool(C->getCond());
  2325. addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
  2326. addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
  2327. Block->setTerminator(C);
  2328. Expr *condExpr = C->getCond();
  2329. if (opaqueValue) {
  2330. // Run the condition expression if it's not trivially expressed in
  2331. // terms of the opaque value (or if there is no opaque value).
  2332. if (condExpr != opaqueValue)
  2333. addStmt(condExpr);
  2334. // Before that, run the common subexpression if there was one.
  2335. // At least one of this or the above will be run.
  2336. return addStmt(BCO->getCommon());
  2337. }
  2338. return addStmt(condExpr);
  2339. }
  2340. CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
  2341. // Check if the Decl is for an __label__. If so, elide it from the
  2342. // CFG entirely.
  2343. if (isa<LabelDecl>(*DS->decl_begin()))
  2344. return Block;
  2345. // This case also handles static_asserts.
  2346. if (DS->isSingleDecl())
  2347. return VisitDeclSubExpr(DS);
  2348. CFGBlock *B = nullptr;
  2349. // Build an individual DeclStmt for each decl.
  2350. for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
  2351. E = DS->decl_rend();
  2352. I != E; ++I) {
  2353. // Allocate the DeclStmt using the BumpPtrAllocator. It will get
  2354. // automatically freed with the CFG.
  2355. DeclGroupRef DG(*I);
  2356. Decl *D = *I;
  2357. DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
  2358. cfg->addSyntheticDeclStmt(DSNew, DS);
  2359. // Append the fake DeclStmt to block.
  2360. B = VisitDeclSubExpr(DSNew);
  2361. }
  2362. return B;
  2363. }
  2364. /// VisitDeclSubExpr - Utility method to add block-level expressions for
  2365. /// DeclStmts and initializers in them.
  2366. CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
  2367. assert(DS->isSingleDecl() && "Can handle single declarations only.");
  2368. VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  2369. if (!VD) {
  2370. // Of everything that can be declared in a DeclStmt, only VarDecls impact
  2371. // runtime semantics.
  2372. return Block;
  2373. }
  2374. bool HasTemporaries = false;
  2375. // Guard static initializers under a branch.
  2376. CFGBlock *blockAfterStaticInit = nullptr;
  2377. if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
  2378. // For static variables, we need to create a branch to track
  2379. // whether or not they are initialized.
  2380. if (Block) {
  2381. Succ = Block;
  2382. Block = nullptr;
  2383. if (badCFG)
  2384. return nullptr;
  2385. }
  2386. blockAfterStaticInit = Succ;
  2387. }
  2388. // Destructors of temporaries in initialization expression should be called
  2389. // after initialization finishes.
  2390. Expr *Init = VD->getInit();
  2391. if (Init) {
  2392. HasTemporaries = isa<ExprWithCleanups>(Init);
  2393. if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
  2394. // Generate destructors for temporaries in initialization expression.
  2395. TempDtorContext Context;
  2396. VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
  2397. /*ExternallyDestructed=*/true, Context);
  2398. }
  2399. }
  2400. autoCreateBlock();
  2401. appendStmt(Block, DS);
  2402. findConstructionContexts(
  2403. ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
  2404. Init);
  2405. // Keep track of the last non-null block, as 'Block' can be nulled out
  2406. // if the initializer expression is something like a 'while' in a
  2407. // statement-expression.
  2408. CFGBlock *LastBlock = Block;
  2409. if (Init) {
  2410. if (HasTemporaries) {
  2411. // For expression with temporaries go directly to subexpression to omit
  2412. // generating destructors for the second time.
  2413. ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
  2414. if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
  2415. LastBlock = newBlock;
  2416. }
  2417. else {
  2418. if (CFGBlock *newBlock = Visit(Init))
  2419. LastBlock = newBlock;
  2420. }
  2421. }
  2422. // If the type of VD is a VLA, then we must process its size expressions.
  2423. for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
  2424. VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
  2425. if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
  2426. LastBlock = newBlock;
  2427. }
  2428. maybeAddScopeBeginForVarDecl(Block, VD, DS);
  2429. // Remove variable from local scope.
  2430. if (ScopePos && VD == *ScopePos)
  2431. ++ScopePos;
  2432. CFGBlock *B = LastBlock;
  2433. if (blockAfterStaticInit) {
  2434. Succ = B;
  2435. Block = createBlock(false);
  2436. Block->setTerminator(DS);
  2437. addSuccessor(Block, blockAfterStaticInit);
  2438. addSuccessor(Block, B);
  2439. B = Block;
  2440. }
  2441. return B;
  2442. }
  2443. CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
  2444. // We may see an if statement in the middle of a basic block, or it may be the
  2445. // first statement we are processing. In either case, we create a new basic
  2446. // block. First, we create the blocks for the then...else statements, and
  2447. // then we create the block containing the if statement. If we were in the
  2448. // middle of a block, we stop processing that block. That block is then the
  2449. // implicit successor for the "then" and "else" clauses.
  2450. // Save local scope position because in case of condition variable ScopePos
  2451. // won't be restored when traversing AST.
  2452. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2453. // Create local scope for C++17 if init-stmt if one exists.
  2454. if (Stmt *Init = I->getInit())
  2455. addLocalScopeForStmt(Init);
  2456. // Create local scope for possible condition variable.
  2457. // Store scope position. Add implicit destructor.
  2458. if (VarDecl *VD = I->getConditionVariable())
  2459. addLocalScopeForVarDecl(VD);
  2460. addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
  2461. // The block we were processing is now finished. Make it the successor
  2462. // block.
  2463. if (Block) {
  2464. Succ = Block;
  2465. if (badCFG)
  2466. return nullptr;
  2467. }
  2468. // Process the false branch.
  2469. CFGBlock *ElseBlock = Succ;
  2470. if (Stmt *Else = I->getElse()) {
  2471. SaveAndRestore<CFGBlock*> sv(Succ);
  2472. // NULL out Block so that the recursive call to Visit will
  2473. // create a new basic block.
  2474. Block = nullptr;
  2475. // If branch is not a compound statement create implicit scope
  2476. // and add destructors.
  2477. if (!isa<CompoundStmt>(Else))
  2478. addLocalScopeAndDtors(Else);
  2479. ElseBlock = addStmt(Else);
  2480. if (!ElseBlock) // Can occur when the Else body has all NullStmts.
  2481. ElseBlock = sv.get();
  2482. else if (Block) {
  2483. if (badCFG)
  2484. return nullptr;
  2485. }
  2486. }
  2487. // Process the true branch.
  2488. CFGBlock *ThenBlock;
  2489. {
  2490. Stmt *Then = I->getThen();
  2491. assert(Then);
  2492. SaveAndRestore<CFGBlock*> sv(Succ);
  2493. Block = nullptr;
  2494. // If branch is not a compound statement create implicit scope
  2495. // and add destructors.
  2496. if (!isa<CompoundStmt>(Then))
  2497. addLocalScopeAndDtors(Then);
  2498. ThenBlock = addStmt(Then);
  2499. if (!ThenBlock) {
  2500. // We can reach here if the "then" body has all NullStmts.
  2501. // Create an empty block so we can distinguish between true and false
  2502. // branches in path-sensitive analyses.
  2503. ThenBlock = createBlock(false);
  2504. addSuccessor(ThenBlock, sv.get());
  2505. } else if (Block) {
  2506. if (badCFG)
  2507. return nullptr;
  2508. }
  2509. }
  2510. // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
  2511. // having these handle the actual control-flow jump. Note that
  2512. // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
  2513. // we resort to the old control-flow behavior. This special handling
  2514. // removes infeasible paths from the control-flow graph by having the
  2515. // control-flow transfer of '&&' or '||' go directly into the then/else
  2516. // blocks directly.
  2517. BinaryOperator *Cond =
  2518. I->getConditionVariable()
  2519. ? nullptr
  2520. : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
  2521. CFGBlock *LastBlock;
  2522. if (Cond && Cond->isLogicalOp())
  2523. LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
  2524. else {
  2525. // Now create a new block containing the if statement.
  2526. Block = createBlock(false);
  2527. // Set the terminator of the new block to the If statement.
  2528. Block->setTerminator(I);
  2529. // See if this is a known constant.
  2530. const TryResult &KnownVal = tryEvaluateBool(I->getCond());
  2531. // Add the successors. If we know that specific branches are
  2532. // unreachable, inform addSuccessor() of that knowledge.
  2533. addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse());
  2534. addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue());
  2535. // Add the condition as the last statement in the new block. This may
  2536. // create new blocks as the condition may contain control-flow. Any newly
  2537. // created blocks will be pointed to be "Block".
  2538. LastBlock = addStmt(I->getCond());
  2539. // If the IfStmt contains a condition variable, add it and its
  2540. // initializer to the CFG.
  2541. if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
  2542. autoCreateBlock();
  2543. LastBlock = addStmt(const_cast<DeclStmt *>(DS));
  2544. }
  2545. }
  2546. // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
  2547. if (Stmt *Init = I->getInit()) {
  2548. autoCreateBlock();
  2549. LastBlock = addStmt(Init);
  2550. }
  2551. return LastBlock;
  2552. }
  2553. CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
  2554. // If we were in the middle of a block we stop processing that block.
  2555. //
  2556. // NOTE: If a "return" or "co_return" appears in the middle of a block, this
  2557. // means that the code afterwards is DEAD (unreachable). We still keep
  2558. // a basic block for that code; a simple "mark-and-sweep" from the entry
  2559. // block will be able to report such dead blocks.
  2560. assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
  2561. // Create the new block.
  2562. Block = createBlock(false);
  2563. addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S);
  2564. if (auto *R = dyn_cast<ReturnStmt>(S))
  2565. findConstructionContexts(
  2566. ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
  2567. R->getRetValue());
  2568. // If the one of the destructors does not return, we already have the Exit
  2569. // block as a successor.
  2570. if (!Block->hasNoReturnElement())
  2571. addSuccessor(Block, &cfg->getExit());
  2572. // Add the return statement to the block.
  2573. appendStmt(Block, S);
  2574. // Visit children
  2575. if (ReturnStmt *RS = dyn_cast<ReturnStmt>(S)) {
  2576. if (Expr *O = RS->getRetValue())
  2577. return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
  2578. return Block;
  2579. } else { // co_return
  2580. return VisitChildren(S);
  2581. }
  2582. }
  2583. CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
  2584. // SEHExceptStmt are treated like labels, so they are the first statement in a
  2585. // block.
  2586. // Save local scope position because in case of exception variable ScopePos
  2587. // won't be restored when traversing AST.
  2588. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2589. addStmt(ES->getBlock());
  2590. CFGBlock *SEHExceptBlock = Block;
  2591. if (!SEHExceptBlock)
  2592. SEHExceptBlock = createBlock();
  2593. appendStmt(SEHExceptBlock, ES);
  2594. // Also add the SEHExceptBlock as a label, like with regular labels.
  2595. SEHExceptBlock->setLabel(ES);
  2596. // Bail out if the CFG is bad.
  2597. if (badCFG)
  2598. return nullptr;
  2599. // We set Block to NULL to allow lazy creation of a new block (if necessary).
  2600. Block = nullptr;
  2601. return SEHExceptBlock;
  2602. }
  2603. CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
  2604. return VisitCompoundStmt(FS->getBlock(), /*ExternallyDestructed=*/false);
  2605. }
  2606. CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
  2607. // "__leave" is a control-flow statement. Thus we stop processing the current
  2608. // block.
  2609. if (badCFG)
  2610. return nullptr;
  2611. // Now create a new block that ends with the __leave statement.
  2612. Block = createBlock(false);
  2613. Block->setTerminator(LS);
  2614. // If there is no target for the __leave, then we are looking at an incomplete
  2615. // AST. This means that the CFG cannot be constructed.
  2616. if (SEHLeaveJumpTarget.block) {
  2617. addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
  2618. addSuccessor(Block, SEHLeaveJumpTarget.block);
  2619. } else
  2620. badCFG = true;
  2621. return Block;
  2622. }
  2623. CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
  2624. // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
  2625. // processing the current block.
  2626. CFGBlock *SEHTrySuccessor = nullptr;
  2627. if (Block) {
  2628. if (badCFG)
  2629. return nullptr;
  2630. SEHTrySuccessor = Block;
  2631. } else SEHTrySuccessor = Succ;
  2632. // FIXME: Implement __finally support.
  2633. if (Terminator->getFinallyHandler())
  2634. return NYS();
  2635. CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
  2636. // Create a new block that will contain the __try statement.
  2637. CFGBlock *NewTryTerminatedBlock = createBlock(false);
  2638. // Add the terminator in the __try block.
  2639. NewTryTerminatedBlock->setTerminator(Terminator);
  2640. if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
  2641. // The code after the try is the implicit successor if there's an __except.
  2642. Succ = SEHTrySuccessor;
  2643. Block = nullptr;
  2644. CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
  2645. if (!ExceptBlock)
  2646. return nullptr;
  2647. // Add this block to the list of successors for the block with the try
  2648. // statement.
  2649. addSuccessor(NewTryTerminatedBlock, ExceptBlock);
  2650. }
  2651. if (PrevSEHTryTerminatedBlock)
  2652. addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
  2653. else
  2654. addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
  2655. // The code after the try is the implicit successor.
  2656. Succ = SEHTrySuccessor;
  2657. // Save the current "__try" context.
  2658. SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
  2659. NewTryTerminatedBlock);
  2660. cfg->addTryDispatchBlock(TryTerminatedBlock);
  2661. // Save the current value for the __leave target.
  2662. // All __leaves should go to the code following the __try
  2663. // (FIXME: or if the __try has a __finally, to the __finally.)
  2664. SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
  2665. SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
  2666. assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
  2667. Block = nullptr;
  2668. return addStmt(Terminator->getTryBlock());
  2669. }
  2670. CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
  2671. // Get the block of the labeled statement. Add it to our map.
  2672. addStmt(L->getSubStmt());
  2673. CFGBlock *LabelBlock = Block;
  2674. if (!LabelBlock) // This can happen when the body is empty, i.e.
  2675. LabelBlock = createBlock(); // scopes that only contains NullStmts.
  2676. assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
  2677. "label already in map");
  2678. LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
  2679. // Labels partition blocks, so this is the end of the basic block we were
  2680. // processing (L is the block's label). Because this is label (and we have
  2681. // already processed the substatement) there is no extra control-flow to worry
  2682. // about.
  2683. LabelBlock->setLabel(L);
  2684. if (badCFG)
  2685. return nullptr;
  2686. // We set Block to NULL to allow lazy creation of a new block (if necessary);
  2687. Block = nullptr;
  2688. // This block is now the implicit successor of other blocks.
  2689. Succ = LabelBlock;
  2690. return LabelBlock;
  2691. }
  2692. CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
  2693. CFGBlock *LastBlock = VisitNoRecurse(E, asc);
  2694. for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
  2695. if (Expr *CopyExpr = CI.getCopyExpr()) {
  2696. CFGBlock *Tmp = Visit(CopyExpr);
  2697. if (Tmp)
  2698. LastBlock = Tmp;
  2699. }
  2700. }
  2701. return LastBlock;
  2702. }
  2703. CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
  2704. CFGBlock *LastBlock = VisitNoRecurse(E, asc);
  2705. for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
  2706. et = E->capture_init_end(); it != et; ++it) {
  2707. if (Expr *Init = *it) {
  2708. CFGBlock *Tmp = Visit(Init);
  2709. if (Tmp)
  2710. LastBlock = Tmp;
  2711. }
  2712. }
  2713. return LastBlock;
  2714. }
  2715. CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
  2716. // Goto is a control-flow statement. Thus we stop processing the current
  2717. // block and create a new one.
  2718. Block = createBlock(false);
  2719. Block->setTerminator(G);
  2720. // If we already know the mapping to the label block add the successor now.
  2721. LabelMapTy::iterator I = LabelMap.find(G->getLabel());
  2722. if (I == LabelMap.end())
  2723. // We will need to backpatch this block later.
  2724. BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
  2725. else {
  2726. JumpTarget JT = I->second;
  2727. addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
  2728. addSuccessor(Block, JT.block);
  2729. }
  2730. return Block;
  2731. }
  2732. CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
  2733. // Goto is a control-flow statement. Thus we stop processing the current
  2734. // block and create a new one.
  2735. if (!G->isAsmGoto())
  2736. return VisitStmt(G, asc);
  2737. if (Block) {
  2738. Succ = Block;
  2739. if (badCFG)
  2740. return nullptr;
  2741. }
  2742. Block = createBlock();
  2743. Block->setTerminator(G);
  2744. // We will backpatch this block later for all the labels.
  2745. BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
  2746. // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
  2747. // used to avoid adding "Succ" again.
  2748. BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
  2749. return Block;
  2750. }
  2751. CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
  2752. CFGBlock *LoopSuccessor = nullptr;
  2753. // Save local scope position because in case of condition variable ScopePos
  2754. // won't be restored when traversing AST.
  2755. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2756. // Create local scope for init statement and possible condition variable.
  2757. // Add destructor for init statement and condition variable.
  2758. // Store scope position for continue statement.
  2759. if (Stmt *Init = F->getInit())
  2760. addLocalScopeForStmt(Init);
  2761. LocalScope::const_iterator LoopBeginScopePos = ScopePos;
  2762. if (VarDecl *VD = F->getConditionVariable())
  2763. addLocalScopeForVarDecl(VD);
  2764. LocalScope::const_iterator ContinueScopePos = ScopePos;
  2765. addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
  2766. addLoopExit(F);
  2767. // "for" is a control-flow statement. Thus we stop processing the current
  2768. // block.
  2769. if (Block) {
  2770. if (badCFG)
  2771. return nullptr;
  2772. LoopSuccessor = Block;
  2773. } else
  2774. LoopSuccessor = Succ;
  2775. // Save the current value for the break targets.
  2776. // All breaks should go to the code following the loop.
  2777. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
  2778. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  2779. CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
  2780. // Now create the loop body.
  2781. {
  2782. assert(F->getBody());
  2783. // Save the current values for Block, Succ, continue and break targets.
  2784. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  2785. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
  2786. // Create an empty block to represent the transition block for looping back
  2787. // to the head of the loop. If we have increment code, it will
  2788. // go in this block as well.
  2789. Block = Succ = TransitionBlock = createBlock(false);
  2790. TransitionBlock->setLoopTarget(F);
  2791. if (Stmt *I = F->getInc()) {
  2792. // Generate increment code in its own basic block. This is the target of
  2793. // continue statements.
  2794. Succ = addStmt(I);
  2795. }
  2796. // Finish up the increment (or empty) block if it hasn't been already.
  2797. if (Block) {
  2798. assert(Block == Succ);
  2799. if (badCFG)
  2800. return nullptr;
  2801. Block = nullptr;
  2802. }
  2803. // The starting block for the loop increment is the block that should
  2804. // represent the 'loop target' for looping back to the start of the loop.
  2805. ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
  2806. ContinueJumpTarget.block->setLoopTarget(F);
  2807. // Loop body should end with destructor of Condition variable (if any).
  2808. addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
  2809. // If body is not a compound statement create implicit scope
  2810. // and add destructors.
  2811. if (!isa<CompoundStmt>(F->getBody()))
  2812. addLocalScopeAndDtors(F->getBody());
  2813. // Now populate the body block, and in the process create new blocks as we
  2814. // walk the body of the loop.
  2815. BodyBlock = addStmt(F->getBody());
  2816. if (!BodyBlock) {
  2817. // In the case of "for (...;...;...);" we can have a null BodyBlock.
  2818. // Use the continue jump target as the proxy for the body.
  2819. BodyBlock = ContinueJumpTarget.block;
  2820. }
  2821. else if (badCFG)
  2822. return nullptr;
  2823. }
  2824. // Because of short-circuit evaluation, the condition of the loop can span
  2825. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  2826. // evaluate the condition.
  2827. CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
  2828. do {
  2829. Expr *C = F->getCond();
  2830. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2831. // Specially handle logical operators, which have a slightly
  2832. // more optimal CFG representation.
  2833. if (BinaryOperator *Cond =
  2834. dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
  2835. if (Cond->isLogicalOp()) {
  2836. std::tie(EntryConditionBlock, ExitConditionBlock) =
  2837. VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
  2838. break;
  2839. }
  2840. // The default case when not handling logical operators.
  2841. EntryConditionBlock = ExitConditionBlock = createBlock(false);
  2842. ExitConditionBlock->setTerminator(F);
  2843. // See if this is a known constant.
  2844. TryResult KnownVal(true);
  2845. if (C) {
  2846. // Now add the actual condition to the condition block.
  2847. // Because the condition itself may contain control-flow, new blocks may
  2848. // be created. Thus we update "Succ" after adding the condition.
  2849. Block = ExitConditionBlock;
  2850. EntryConditionBlock = addStmt(C);
  2851. // If this block contains a condition variable, add both the condition
  2852. // variable and initializer to the CFG.
  2853. if (VarDecl *VD = F->getConditionVariable()) {
  2854. if (Expr *Init = VD->getInit()) {
  2855. autoCreateBlock();
  2856. const DeclStmt *DS = F->getConditionVariableDeclStmt();
  2857. assert(DS->isSingleDecl());
  2858. findConstructionContexts(
  2859. ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
  2860. Init);
  2861. appendStmt(Block, DS);
  2862. EntryConditionBlock = addStmt(Init);
  2863. assert(Block == EntryConditionBlock);
  2864. maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
  2865. }
  2866. }
  2867. if (Block && badCFG)
  2868. return nullptr;
  2869. KnownVal = tryEvaluateBool(C);
  2870. }
  2871. // Add the loop body entry as a successor to the condition.
  2872. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
  2873. // Link up the condition block with the code that follows the loop. (the
  2874. // false branch).
  2875. addSuccessor(ExitConditionBlock,
  2876. KnownVal.isTrue() ? nullptr : LoopSuccessor);
  2877. } while (false);
  2878. // Link up the loop-back block to the entry condition block.
  2879. addSuccessor(TransitionBlock, EntryConditionBlock);
  2880. // The condition block is the implicit successor for any code above the loop.
  2881. Succ = EntryConditionBlock;
  2882. // If the loop contains initialization, create a new block for those
  2883. // statements. This block can also contain statements that precede the loop.
  2884. if (Stmt *I = F->getInit()) {
  2885. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2886. ScopePos = LoopBeginScopePos;
  2887. Block = createBlock();
  2888. return addStmt(I);
  2889. }
  2890. // There is no loop initialization. We are thus basically a while loop.
  2891. // NULL out Block to force lazy block construction.
  2892. Block = nullptr;
  2893. Succ = EntryConditionBlock;
  2894. return EntryConditionBlock;
  2895. }
  2896. CFGBlock *
  2897. CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
  2898. AddStmtChoice asc) {
  2899. findConstructionContexts(
  2900. ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
  2901. MTE->getTemporary());
  2902. return VisitStmt(MTE, asc);
  2903. }
  2904. CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
  2905. if (asc.alwaysAdd(*this, M)) {
  2906. autoCreateBlock();
  2907. appendStmt(Block, M);
  2908. }
  2909. return Visit(M->getBase());
  2910. }
  2911. CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
  2912. // Objective-C fast enumeration 'for' statements:
  2913. // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
  2914. //
  2915. // for ( Type newVariable in collection_expression ) { statements }
  2916. //
  2917. // becomes:
  2918. //
  2919. // prologue:
  2920. // 1. collection_expression
  2921. // T. jump to loop_entry
  2922. // loop_entry:
  2923. // 1. side-effects of element expression
  2924. // 1. ObjCForCollectionStmt [performs binding to newVariable]
  2925. // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
  2926. // TB:
  2927. // statements
  2928. // T. jump to loop_entry
  2929. // FB:
  2930. // what comes after
  2931. //
  2932. // and
  2933. //
  2934. // Type existingItem;
  2935. // for ( existingItem in expression ) { statements }
  2936. //
  2937. // becomes:
  2938. //
  2939. // the same with newVariable replaced with existingItem; the binding works
  2940. // the same except that for one ObjCForCollectionStmt::getElement() returns
  2941. // a DeclStmt and the other returns a DeclRefExpr.
  2942. CFGBlock *LoopSuccessor = nullptr;
  2943. if (Block) {
  2944. if (badCFG)
  2945. return nullptr;
  2946. LoopSuccessor = Block;
  2947. Block = nullptr;
  2948. } else
  2949. LoopSuccessor = Succ;
  2950. // Build the condition blocks.
  2951. CFGBlock *ExitConditionBlock = createBlock(false);
  2952. // Set the terminator for the "exit" condition block.
  2953. ExitConditionBlock->setTerminator(S);
  2954. // The last statement in the block should be the ObjCForCollectionStmt, which
  2955. // performs the actual binding to 'element' and determines if there are any
  2956. // more items in the collection.
  2957. appendStmt(ExitConditionBlock, S);
  2958. Block = ExitConditionBlock;
  2959. // Walk the 'element' expression to see if there are any side-effects. We
  2960. // generate new blocks as necessary. We DON'T add the statement by default to
  2961. // the CFG unless it contains control-flow.
  2962. CFGBlock *EntryConditionBlock = Visit(S->getElement(),
  2963. AddStmtChoice::NotAlwaysAdd);
  2964. if (Block) {
  2965. if (badCFG)
  2966. return nullptr;
  2967. Block = nullptr;
  2968. }
  2969. // The condition block is the implicit successor for the loop body as well as
  2970. // any code above the loop.
  2971. Succ = EntryConditionBlock;
  2972. // Now create the true branch.
  2973. {
  2974. // Save the current values for Succ, continue and break targets.
  2975. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  2976. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
  2977. save_break(BreakJumpTarget);
  2978. // Add an intermediate block between the BodyBlock and the
  2979. // EntryConditionBlock to represent the "loop back" transition, for looping
  2980. // back to the head of the loop.
  2981. CFGBlock *LoopBackBlock = nullptr;
  2982. Succ = LoopBackBlock = createBlock();
  2983. LoopBackBlock->setLoopTarget(S);
  2984. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  2985. ContinueJumpTarget = JumpTarget(Succ, ScopePos);
  2986. CFGBlock *BodyBlock = addStmt(S->getBody());
  2987. if (!BodyBlock)
  2988. BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
  2989. else if (Block) {
  2990. if (badCFG)
  2991. return nullptr;
  2992. }
  2993. // This new body block is a successor to our "exit" condition block.
  2994. addSuccessor(ExitConditionBlock, BodyBlock);
  2995. }
  2996. // Link up the condition block with the code that follows the loop.
  2997. // (the false branch).
  2998. addSuccessor(ExitConditionBlock, LoopSuccessor);
  2999. // Now create a prologue block to contain the collection expression.
  3000. Block = createBlock();
  3001. return addStmt(S->getCollection());
  3002. }
  3003. CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
  3004. // Inline the body.
  3005. return addStmt(S->getSubStmt());
  3006. // TODO: consider adding cleanups for the end of @autoreleasepool scope.
  3007. }
  3008. CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
  3009. // FIXME: Add locking 'primitives' to CFG for @synchronized.
  3010. // Inline the body.
  3011. CFGBlock *SyncBlock = addStmt(S->getSynchBody());
  3012. // The sync body starts its own basic block. This makes it a little easier
  3013. // for diagnostic clients.
  3014. if (SyncBlock) {
  3015. if (badCFG)
  3016. return nullptr;
  3017. Block = nullptr;
  3018. Succ = SyncBlock;
  3019. }
  3020. // Add the @synchronized to the CFG.
  3021. autoCreateBlock();
  3022. appendStmt(Block, S);
  3023. // Inline the sync expression.
  3024. return addStmt(S->getSynchExpr());
  3025. }
  3026. CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
  3027. // FIXME
  3028. return NYS();
  3029. }
  3030. CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  3031. autoCreateBlock();
  3032. // Add the PseudoObject as the last thing.
  3033. appendStmt(Block, E);
  3034. CFGBlock *lastBlock = Block;
  3035. // Before that, evaluate all of the semantics in order. In
  3036. // CFG-land, that means appending them in reverse order.
  3037. for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
  3038. Expr *Semantic = E->getSemanticExpr(--i);
  3039. // If the semantic is an opaque value, we're being asked to bind
  3040. // it to its source expression.
  3041. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
  3042. Semantic = OVE->getSourceExpr();
  3043. if (CFGBlock *B = Visit(Semantic))
  3044. lastBlock = B;
  3045. }
  3046. return lastBlock;
  3047. }
  3048. CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
  3049. CFGBlock *LoopSuccessor = nullptr;
  3050. // Save local scope position because in case of condition variable ScopePos
  3051. // won't be restored when traversing AST.
  3052. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  3053. // Create local scope for possible condition variable.
  3054. // Store scope position for continue statement.
  3055. LocalScope::const_iterator LoopBeginScopePos = ScopePos;
  3056. if (VarDecl *VD = W->getConditionVariable()) {
  3057. addLocalScopeForVarDecl(VD);
  3058. addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
  3059. }
  3060. addLoopExit(W);
  3061. // "while" is a control-flow statement. Thus we stop processing the current
  3062. // block.
  3063. if (Block) {
  3064. if (badCFG)
  3065. return nullptr;
  3066. LoopSuccessor = Block;
  3067. Block = nullptr;
  3068. } else {
  3069. LoopSuccessor = Succ;
  3070. }
  3071. CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
  3072. // Process the loop body.
  3073. {
  3074. assert(W->getBody());
  3075. // Save the current values for Block, Succ, continue and break targets.
  3076. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  3077. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
  3078. save_break(BreakJumpTarget);
  3079. // Create an empty block to represent the transition block for looping back
  3080. // to the head of the loop.
  3081. Succ = TransitionBlock = createBlock(false);
  3082. TransitionBlock->setLoopTarget(W);
  3083. ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
  3084. // All breaks should go to the code following the loop.
  3085. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  3086. // Loop body should end with destructor of Condition variable (if any).
  3087. addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
  3088. // If body is not a compound statement create implicit scope
  3089. // and add destructors.
  3090. if (!isa<CompoundStmt>(W->getBody()))
  3091. addLocalScopeAndDtors(W->getBody());
  3092. // Create the body. The returned block is the entry to the loop body.
  3093. BodyBlock = addStmt(W->getBody());
  3094. if (!BodyBlock)
  3095. BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
  3096. else if (Block && badCFG)
  3097. return nullptr;
  3098. }
  3099. // Because of short-circuit evaluation, the condition of the loop can span
  3100. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  3101. // evaluate the condition.
  3102. CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
  3103. do {
  3104. Expr *C = W->getCond();
  3105. // Specially handle logical operators, which have a slightly
  3106. // more optimal CFG representation.
  3107. if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
  3108. if (Cond->isLogicalOp()) {
  3109. std::tie(EntryConditionBlock, ExitConditionBlock) =
  3110. VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
  3111. break;
  3112. }
  3113. // The default case when not handling logical operators.
  3114. ExitConditionBlock = createBlock(false);
  3115. ExitConditionBlock->setTerminator(W);
  3116. // Now add the actual condition to the condition block.
  3117. // Because the condition itself may contain control-flow, new blocks may
  3118. // be created. Thus we update "Succ" after adding the condition.
  3119. Block = ExitConditionBlock;
  3120. Block = EntryConditionBlock = addStmt(C);
  3121. // If this block contains a condition variable, add both the condition
  3122. // variable and initializer to the CFG.
  3123. if (VarDecl *VD = W->getConditionVariable()) {
  3124. if (Expr *Init = VD->getInit()) {
  3125. autoCreateBlock();
  3126. const DeclStmt *DS = W->getConditionVariableDeclStmt();
  3127. assert(DS->isSingleDecl());
  3128. findConstructionContexts(
  3129. ConstructionContextLayer::create(cfg->getBumpVectorContext(),
  3130. const_cast<DeclStmt *>(DS)),
  3131. Init);
  3132. appendStmt(Block, DS);
  3133. EntryConditionBlock = addStmt(Init);
  3134. assert(Block == EntryConditionBlock);
  3135. maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
  3136. }
  3137. }
  3138. if (Block && badCFG)
  3139. return nullptr;
  3140. // See if this is a known constant.
  3141. const TryResult& KnownVal = tryEvaluateBool(C);
  3142. // Add the loop body entry as a successor to the condition.
  3143. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
  3144. // Link up the condition block with the code that follows the loop. (the
  3145. // false branch).
  3146. addSuccessor(ExitConditionBlock,
  3147. KnownVal.isTrue() ? nullptr : LoopSuccessor);
  3148. } while(false);
  3149. // Link up the loop-back block to the entry condition block.
  3150. addSuccessor(TransitionBlock, EntryConditionBlock);
  3151. // There can be no more statements in the condition block since we loop back
  3152. // to this block. NULL out Block to force lazy creation of another block.
  3153. Block = nullptr;
  3154. // Return the condition block, which is the dominating block for the loop.
  3155. Succ = EntryConditionBlock;
  3156. return EntryConditionBlock;
  3157. }
  3158. CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
  3159. // FIXME: For now we pretend that @catch and the code it contains does not
  3160. // exit.
  3161. return Block;
  3162. }
  3163. CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
  3164. // FIXME: This isn't complete. We basically treat @throw like a return
  3165. // statement.
  3166. // If we were in the middle of a block we stop processing that block.
  3167. if (badCFG)
  3168. return nullptr;
  3169. // Create the new block.
  3170. Block = createBlock(false);
  3171. // The Exit block is the only successor.
  3172. addSuccessor(Block, &cfg->getExit());
  3173. // Add the statement to the block. This may create new blocks if S contains
  3174. // control-flow (short-circuit operations).
  3175. return VisitStmt(S, AddStmtChoice::AlwaysAdd);
  3176. }
  3177. CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
  3178. AddStmtChoice asc) {
  3179. findConstructionContextsForArguments(ME);
  3180. autoCreateBlock();
  3181. appendObjCMessage(Block, ME);
  3182. return VisitChildren(ME);
  3183. }
  3184. CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
  3185. // If we were in the middle of a block we stop processing that block.
  3186. if (badCFG)
  3187. return nullptr;
  3188. // Create the new block.
  3189. Block = createBlock(false);
  3190. if (TryTerminatedBlock)
  3191. // The current try statement is the only successor.
  3192. addSuccessor(Block, TryTerminatedBlock);
  3193. else
  3194. // otherwise the Exit block is the only successor.
  3195. addSuccessor(Block, &cfg->getExit());
  3196. // Add the statement to the block. This may create new blocks if S contains
  3197. // control-flow (short-circuit operations).
  3198. return VisitStmt(T, AddStmtChoice::AlwaysAdd);
  3199. }
  3200. CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
  3201. CFGBlock *LoopSuccessor = nullptr;
  3202. addLoopExit(D);
  3203. // "do...while" is a control-flow statement. Thus we stop processing the
  3204. // current block.
  3205. if (Block) {
  3206. if (badCFG)
  3207. return nullptr;
  3208. LoopSuccessor = Block;
  3209. } else
  3210. LoopSuccessor = Succ;
  3211. // Because of short-circuit evaluation, the condition of the loop can span
  3212. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  3213. // evaluate the condition.
  3214. CFGBlock *ExitConditionBlock = createBlock(false);
  3215. CFGBlock *EntryConditionBlock = ExitConditionBlock;
  3216. // Set the terminator for the "exit" condition block.
  3217. ExitConditionBlock->setTerminator(D);
  3218. // Now add the actual condition to the condition block. Because the condition
  3219. // itself may contain control-flow, new blocks may be created.
  3220. if (Stmt *C = D->getCond()) {
  3221. Block = ExitConditionBlock;
  3222. EntryConditionBlock = addStmt(C);
  3223. if (Block) {
  3224. if (badCFG)
  3225. return nullptr;
  3226. }
  3227. }
  3228. // The condition block is the implicit successor for the loop body.
  3229. Succ = EntryConditionBlock;
  3230. // See if this is a known constant.
  3231. const TryResult &KnownVal = tryEvaluateBool(D->getCond());
  3232. // Process the loop body.
  3233. CFGBlock *BodyBlock = nullptr;
  3234. {
  3235. assert(D->getBody());
  3236. // Save the current values for Block, Succ, and continue and break targets
  3237. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  3238. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
  3239. save_break(BreakJumpTarget);
  3240. // All continues within this loop should go to the condition block
  3241. ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
  3242. // All breaks should go to the code following the loop.
  3243. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  3244. // NULL out Block to force lazy instantiation of blocks for the body.
  3245. Block = nullptr;
  3246. // If body is not a compound statement create implicit scope
  3247. // and add destructors.
  3248. if (!isa<CompoundStmt>(D->getBody()))
  3249. addLocalScopeAndDtors(D->getBody());
  3250. // Create the body. The returned block is the entry to the loop body.
  3251. BodyBlock = addStmt(D->getBody());
  3252. if (!BodyBlock)
  3253. BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
  3254. else if (Block) {
  3255. if (badCFG)
  3256. return nullptr;
  3257. }
  3258. // Add an intermediate block between the BodyBlock and the
  3259. // ExitConditionBlock to represent the "loop back" transition. Create an
  3260. // empty block to represent the transition block for looping back to the
  3261. // head of the loop.
  3262. // FIXME: Can we do this more efficiently without adding another block?
  3263. Block = nullptr;
  3264. Succ = BodyBlock;
  3265. CFGBlock *LoopBackBlock = createBlock();
  3266. LoopBackBlock->setLoopTarget(D);
  3267. if (!KnownVal.isFalse())
  3268. // Add the loop body entry as a successor to the condition.
  3269. addSuccessor(ExitConditionBlock, LoopBackBlock);
  3270. else
  3271. addSuccessor(ExitConditionBlock, nullptr);
  3272. }
  3273. // Link up the condition block with the code that follows the loop.
  3274. // (the false branch).
  3275. addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
  3276. // There can be no more statements in the body block(s) since we loop back to
  3277. // the body. NULL out Block to force lazy creation of another block.
  3278. Block = nullptr;
  3279. // Return the loop body, which is the dominating block for the loop.
  3280. Succ = BodyBlock;
  3281. return BodyBlock;
  3282. }
  3283. CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
  3284. // "continue" is a control-flow statement. Thus we stop processing the
  3285. // current block.
  3286. if (badCFG)
  3287. return nullptr;
  3288. // Now create a new block that ends with the continue statement.
  3289. Block = createBlock(false);
  3290. Block->setTerminator(C);
  3291. // If there is no target for the continue, then we are looking at an
  3292. // incomplete AST. This means the CFG cannot be constructed.
  3293. if (ContinueJumpTarget.block) {
  3294. addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
  3295. addSuccessor(Block, ContinueJumpTarget.block);
  3296. } else
  3297. badCFG = true;
  3298. return Block;
  3299. }
  3300. CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
  3301. AddStmtChoice asc) {
  3302. if (asc.alwaysAdd(*this, E)) {
  3303. autoCreateBlock();
  3304. appendStmt(Block, E);
  3305. }
  3306. // VLA types have expressions that must be evaluated.
  3307. CFGBlock *lastBlock = Block;
  3308. if (E->isArgumentType()) {
  3309. for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
  3310. VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
  3311. lastBlock = addStmt(VA->getSizeExpr());
  3312. }
  3313. return lastBlock;
  3314. }
  3315. /// VisitStmtExpr - Utility method to handle (nested) statement
  3316. /// expressions (a GCC extension).
  3317. CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
  3318. if (asc.alwaysAdd(*this, SE)) {
  3319. autoCreateBlock();
  3320. appendStmt(Block, SE);
  3321. }
  3322. return VisitCompoundStmt(SE->getSubStmt(), /*ExternallyDestructed=*/true);
  3323. }
  3324. CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
  3325. // "switch" is a control-flow statement. Thus we stop processing the current
  3326. // block.
  3327. CFGBlock *SwitchSuccessor = nullptr;
  3328. // Save local scope position because in case of condition variable ScopePos
  3329. // won't be restored when traversing AST.
  3330. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  3331. // Create local scope for C++17 switch init-stmt if one exists.
  3332. if (Stmt *Init = Terminator->getInit())
  3333. addLocalScopeForStmt(Init);
  3334. // Create local scope for possible condition variable.
  3335. // Store scope position. Add implicit destructor.
  3336. if (VarDecl *VD = Terminator->getConditionVariable())
  3337. addLocalScopeForVarDecl(VD);
  3338. addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
  3339. if (Block) {
  3340. if (badCFG)
  3341. return nullptr;
  3342. SwitchSuccessor = Block;
  3343. } else SwitchSuccessor = Succ;
  3344. // Save the current "switch" context.
  3345. SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
  3346. save_default(DefaultCaseBlock);
  3347. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
  3348. // Set the "default" case to be the block after the switch statement. If the
  3349. // switch statement contains a "default:", this value will be overwritten with
  3350. // the block for that code.
  3351. DefaultCaseBlock = SwitchSuccessor;
  3352. // Create a new block that will contain the switch statement.
  3353. SwitchTerminatedBlock = createBlock(false);
  3354. // Now process the switch body. The code after the switch is the implicit
  3355. // successor.
  3356. Succ = SwitchSuccessor;
  3357. BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
  3358. // When visiting the body, the case statements should automatically get linked
  3359. // up to the switch. We also don't keep a pointer to the body, since all
  3360. // control-flow from the switch goes to case/default statements.
  3361. assert(Terminator->getBody() && "switch must contain a non-NULL body");
  3362. Block = nullptr;
  3363. // For pruning unreachable case statements, save the current state
  3364. // for tracking the condition value.
  3365. SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
  3366. false);
  3367. // Determine if the switch condition can be explicitly evaluated.
  3368. assert(Terminator->getCond() && "switch condition must be non-NULL");
  3369. Expr::EvalResult result;
  3370. bool b = tryEvaluate(Terminator->getCond(), result);
  3371. SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
  3372. b ? &result : nullptr);
  3373. // If body is not a compound statement create implicit scope
  3374. // and add destructors.
  3375. if (!isa<CompoundStmt>(Terminator->getBody()))
  3376. addLocalScopeAndDtors(Terminator->getBody());
  3377. addStmt(Terminator->getBody());
  3378. if (Block) {
  3379. if (badCFG)
  3380. return nullptr;
  3381. }
  3382. // If we have no "default:" case, the default transition is to the code
  3383. // following the switch body. Moreover, take into account if all the
  3384. // cases of a switch are covered (e.g., switching on an enum value).
  3385. //
  3386. // Note: We add a successor to a switch that is considered covered yet has no
  3387. // case statements if the enumeration has no enumerators.
  3388. bool SwitchAlwaysHasSuccessor = false;
  3389. SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
  3390. SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
  3391. Terminator->getSwitchCaseList();
  3392. addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
  3393. !SwitchAlwaysHasSuccessor);
  3394. // Add the terminator and condition in the switch block.
  3395. SwitchTerminatedBlock->setTerminator(Terminator);
  3396. Block = SwitchTerminatedBlock;
  3397. CFGBlock *LastBlock = addStmt(Terminator->getCond());
  3398. // If the SwitchStmt contains a condition variable, add both the
  3399. // SwitchStmt and the condition variable initialization to the CFG.
  3400. if (VarDecl *VD = Terminator->getConditionVariable()) {
  3401. if (Expr *Init = VD->getInit()) {
  3402. autoCreateBlock();
  3403. appendStmt(Block, Terminator->getConditionVariableDeclStmt());
  3404. LastBlock = addStmt(Init);
  3405. maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
  3406. }
  3407. }
  3408. // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
  3409. if (Stmt *Init = Terminator->getInit()) {
  3410. autoCreateBlock();
  3411. LastBlock = addStmt(Init);
  3412. }
  3413. return LastBlock;
  3414. }
  3415. static bool shouldAddCase(bool &switchExclusivelyCovered,
  3416. const Expr::EvalResult *switchCond,
  3417. const CaseStmt *CS,
  3418. ASTContext &Ctx) {
  3419. if (!switchCond)
  3420. return true;
  3421. bool addCase = false;
  3422. if (!switchExclusivelyCovered) {
  3423. if (switchCond->Val.isInt()) {
  3424. // Evaluate the LHS of the case value.
  3425. const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
  3426. const llvm::APSInt &condInt = switchCond->Val.getInt();
  3427. if (condInt == lhsInt) {
  3428. addCase = true;
  3429. switchExclusivelyCovered = true;
  3430. }
  3431. else if (condInt > lhsInt) {
  3432. if (const Expr *RHS = CS->getRHS()) {
  3433. // Evaluate the RHS of the case value.
  3434. const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
  3435. if (V2 >= condInt) {
  3436. addCase = true;
  3437. switchExclusivelyCovered = true;
  3438. }
  3439. }
  3440. }
  3441. }
  3442. else
  3443. addCase = true;
  3444. }
  3445. return addCase;
  3446. }
  3447. CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
  3448. // CaseStmts are essentially labels, so they are the first statement in a
  3449. // block.
  3450. CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
  3451. if (Stmt *Sub = CS->getSubStmt()) {
  3452. // For deeply nested chains of CaseStmts, instead of doing a recursion
  3453. // (which can blow out the stack), manually unroll and create blocks
  3454. // along the way.
  3455. while (isa<CaseStmt>(Sub)) {
  3456. CFGBlock *currentBlock = createBlock(false);
  3457. currentBlock->setLabel(CS);
  3458. if (TopBlock)
  3459. addSuccessor(LastBlock, currentBlock);
  3460. else
  3461. TopBlock = currentBlock;
  3462. addSuccessor(SwitchTerminatedBlock,
  3463. shouldAddCase(switchExclusivelyCovered, switchCond,
  3464. CS, *Context)
  3465. ? currentBlock : nullptr);
  3466. LastBlock = currentBlock;
  3467. CS = cast<CaseStmt>(Sub);
  3468. Sub = CS->getSubStmt();
  3469. }
  3470. addStmt(Sub);
  3471. }
  3472. CFGBlock *CaseBlock = Block;
  3473. if (!CaseBlock)
  3474. CaseBlock = createBlock();
  3475. // Cases statements partition blocks, so this is the top of the basic block we
  3476. // were processing (the "case XXX:" is the label).
  3477. CaseBlock->setLabel(CS);
  3478. if (badCFG)
  3479. return nullptr;
  3480. // Add this block to the list of successors for the block with the switch
  3481. // statement.
  3482. assert(SwitchTerminatedBlock);
  3483. addSuccessor(SwitchTerminatedBlock, CaseBlock,
  3484. shouldAddCase(switchExclusivelyCovered, switchCond,
  3485. CS, *Context));
  3486. // We set Block to NULL to allow lazy creation of a new block (if necessary)
  3487. Block = nullptr;
  3488. if (TopBlock) {
  3489. addSuccessor(LastBlock, CaseBlock);
  3490. Succ = TopBlock;
  3491. } else {
  3492. // This block is now the implicit successor of other blocks.
  3493. Succ = CaseBlock;
  3494. }
  3495. return Succ;
  3496. }
  3497. CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
  3498. if (Terminator->getSubStmt())
  3499. addStmt(Terminator->getSubStmt());
  3500. DefaultCaseBlock = Block;
  3501. if (!DefaultCaseBlock)
  3502. DefaultCaseBlock = createBlock();
  3503. // Default statements partition blocks, so this is the top of the basic block
  3504. // we were processing (the "default:" is the label).
  3505. DefaultCaseBlock->setLabel(Terminator);
  3506. if (badCFG)
  3507. return nullptr;
  3508. // Unlike case statements, we don't add the default block to the successors
  3509. // for the switch statement immediately. This is done when we finish
  3510. // processing the switch statement. This allows for the default case
  3511. // (including a fall-through to the code after the switch statement) to always
  3512. // be the last successor of a switch-terminated block.
  3513. // We set Block to NULL to allow lazy creation of a new block (if necessary)
  3514. Block = nullptr;
  3515. // This block is now the implicit successor of other blocks.
  3516. Succ = DefaultCaseBlock;
  3517. return DefaultCaseBlock;
  3518. }
  3519. CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
  3520. // "try"/"catch" is a control-flow statement. Thus we stop processing the
  3521. // current block.
  3522. CFGBlock *TrySuccessor = nullptr;
  3523. if (Block) {
  3524. if (badCFG)
  3525. return nullptr;
  3526. TrySuccessor = Block;
  3527. } else TrySuccessor = Succ;
  3528. CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
  3529. // Create a new block that will contain the try statement.
  3530. CFGBlock *NewTryTerminatedBlock = createBlock(false);
  3531. // Add the terminator in the try block.
  3532. NewTryTerminatedBlock->setTerminator(Terminator);
  3533. bool HasCatchAll = false;
  3534. for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
  3535. // The code after the try is the implicit successor.
  3536. Succ = TrySuccessor;
  3537. CXXCatchStmt *CS = Terminator->getHandler(h);
  3538. if (CS->getExceptionDecl() == nullptr) {
  3539. HasCatchAll = true;
  3540. }
  3541. Block = nullptr;
  3542. CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
  3543. if (!CatchBlock)
  3544. return nullptr;
  3545. // Add this block to the list of successors for the block with the try
  3546. // statement.
  3547. addSuccessor(NewTryTerminatedBlock, CatchBlock);
  3548. }
  3549. if (!HasCatchAll) {
  3550. if (PrevTryTerminatedBlock)
  3551. addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
  3552. else
  3553. addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
  3554. }
  3555. // The code after the try is the implicit successor.
  3556. Succ = TrySuccessor;
  3557. // Save the current "try" context.
  3558. SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
  3559. cfg->addTryDispatchBlock(TryTerminatedBlock);
  3560. assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
  3561. Block = nullptr;
  3562. return addStmt(Terminator->getTryBlock());
  3563. }
  3564. CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
  3565. // CXXCatchStmt are treated like labels, so they are the first statement in a
  3566. // block.
  3567. // Save local scope position because in case of exception variable ScopePos
  3568. // won't be restored when traversing AST.
  3569. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  3570. // Create local scope for possible exception variable.
  3571. // Store scope position. Add implicit destructor.
  3572. if (VarDecl *VD = CS->getExceptionDecl()) {
  3573. LocalScope::const_iterator BeginScopePos = ScopePos;
  3574. addLocalScopeForVarDecl(VD);
  3575. addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
  3576. }
  3577. if (CS->getHandlerBlock())
  3578. addStmt(CS->getHandlerBlock());
  3579. CFGBlock *CatchBlock = Block;
  3580. if (!CatchBlock)
  3581. CatchBlock = createBlock();
  3582. // CXXCatchStmt is more than just a label. They have semantic meaning
  3583. // as well, as they implicitly "initialize" the catch variable. Add
  3584. // it to the CFG as a CFGElement so that the control-flow of these
  3585. // semantics gets captured.
  3586. appendStmt(CatchBlock, CS);
  3587. // Also add the CXXCatchStmt as a label, to mirror handling of regular
  3588. // labels.
  3589. CatchBlock->setLabel(CS);
  3590. // Bail out if the CFG is bad.
  3591. if (badCFG)
  3592. return nullptr;
  3593. // We set Block to NULL to allow lazy creation of a new block (if necessary)
  3594. Block = nullptr;
  3595. return CatchBlock;
  3596. }
  3597. CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
  3598. // C++0x for-range statements are specified as [stmt.ranged]:
  3599. //
  3600. // {
  3601. // auto && __range = range-init;
  3602. // for ( auto __begin = begin-expr,
  3603. // __end = end-expr;
  3604. // __begin != __end;
  3605. // ++__begin ) {
  3606. // for-range-declaration = *__begin;
  3607. // statement
  3608. // }
  3609. // }
  3610. // Save local scope position before the addition of the implicit variables.
  3611. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  3612. // Create local scopes and destructors for range, begin and end variables.
  3613. if (Stmt *Range = S->getRangeStmt())
  3614. addLocalScopeForStmt(Range);
  3615. if (Stmt *Begin = S->getBeginStmt())
  3616. addLocalScopeForStmt(Begin);
  3617. if (Stmt *End = S->getEndStmt())
  3618. addLocalScopeForStmt(End);
  3619. addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
  3620. LocalScope::const_iterator ContinueScopePos = ScopePos;
  3621. // "for" is a control-flow statement. Thus we stop processing the current
  3622. // block.
  3623. CFGBlock *LoopSuccessor = nullptr;
  3624. if (Block) {
  3625. if (badCFG)
  3626. return nullptr;
  3627. LoopSuccessor = Block;
  3628. } else
  3629. LoopSuccessor = Succ;
  3630. // Save the current value for the break targets.
  3631. // All breaks should go to the code following the loop.
  3632. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
  3633. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  3634. // The block for the __begin != __end expression.
  3635. CFGBlock *ConditionBlock = createBlock(false);
  3636. ConditionBlock->setTerminator(S);
  3637. // Now add the actual condition to the condition block.
  3638. if (Expr *C = S->getCond()) {
  3639. Block = ConditionBlock;
  3640. CFGBlock *BeginConditionBlock = addStmt(C);
  3641. if (badCFG)
  3642. return nullptr;
  3643. assert(BeginConditionBlock == ConditionBlock &&
  3644. "condition block in for-range was unexpectedly complex");
  3645. (void)BeginConditionBlock;
  3646. }
  3647. // The condition block is the implicit successor for the loop body as well as
  3648. // any code above the loop.
  3649. Succ = ConditionBlock;
  3650. // See if this is a known constant.
  3651. TryResult KnownVal(true);
  3652. if (S->getCond())
  3653. KnownVal = tryEvaluateBool(S->getCond());
  3654. // Now create the loop body.
  3655. {
  3656. assert(S->getBody());
  3657. // Save the current values for Block, Succ, and continue targets.
  3658. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  3659. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
  3660. // Generate increment code in its own basic block. This is the target of
  3661. // continue statements.
  3662. Block = nullptr;
  3663. Succ = addStmt(S->getInc());
  3664. if (badCFG)
  3665. return nullptr;
  3666. ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
  3667. // The starting block for the loop increment is the block that should
  3668. // represent the 'loop target' for looping back to the start of the loop.
  3669. ContinueJumpTarget.block->setLoopTarget(S);
  3670. // Finish up the increment block and prepare to start the loop body.
  3671. assert(Block);
  3672. if (badCFG)
  3673. return nullptr;
  3674. Block = nullptr;
  3675. // Add implicit scope and dtors for loop variable.
  3676. addLocalScopeAndDtors(S->getLoopVarStmt());
  3677. // Populate a new block to contain the loop body and loop variable.
  3678. addStmt(S->getBody());
  3679. if (badCFG)
  3680. return nullptr;
  3681. CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
  3682. if (badCFG)
  3683. return nullptr;
  3684. // This new body block is a successor to our condition block.
  3685. addSuccessor(ConditionBlock,
  3686. KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
  3687. }
  3688. // Link up the condition block with the code that follows the loop (the
  3689. // false branch).
  3690. addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
  3691. // Add the initialization statements.
  3692. Block = createBlock();
  3693. addStmt(S->getBeginStmt());
  3694. addStmt(S->getEndStmt());
  3695. CFGBlock *Head = addStmt(S->getRangeStmt());
  3696. if (S->getInit())
  3697. Head = addStmt(S->getInit());
  3698. return Head;
  3699. }
  3700. CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
  3701. AddStmtChoice asc, bool ExternallyDestructed) {
  3702. if (BuildOpts.AddTemporaryDtors) {
  3703. // If adding implicit destructors visit the full expression for adding
  3704. // destructors of temporaries.
  3705. TempDtorContext Context;
  3706. VisitForTemporaryDtors(E->getSubExpr(), ExternallyDestructed, Context);
  3707. // Full expression has to be added as CFGStmt so it will be sequenced
  3708. // before destructors of it's temporaries.
  3709. asc = asc.withAlwaysAdd(true);
  3710. }
  3711. return Visit(E->getSubExpr(), asc);
  3712. }
  3713. CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
  3714. AddStmtChoice asc) {
  3715. if (asc.alwaysAdd(*this, E)) {
  3716. autoCreateBlock();
  3717. appendStmt(Block, E);
  3718. findConstructionContexts(
  3719. ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
  3720. E->getSubExpr());
  3721. // We do not want to propagate the AlwaysAdd property.
  3722. asc = asc.withAlwaysAdd(false);
  3723. }
  3724. return Visit(E->getSubExpr(), asc);
  3725. }
  3726. CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
  3727. AddStmtChoice asc) {
  3728. // If the constructor takes objects as arguments by value, we need to properly
  3729. // construct these objects. Construction contexts we find here aren't for the
  3730. // constructor C, they're for its arguments only.
  3731. findConstructionContextsForArguments(C);
  3732. autoCreateBlock();
  3733. appendConstructor(Block, C);
  3734. return VisitChildren(C);
  3735. }
  3736. CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
  3737. AddStmtChoice asc) {
  3738. autoCreateBlock();
  3739. appendStmt(Block, NE);
  3740. findConstructionContexts(
  3741. ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
  3742. const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
  3743. if (NE->getInitializer())
  3744. Block = Visit(NE->getInitializer());
  3745. if (BuildOpts.AddCXXNewAllocator)
  3746. appendNewAllocator(Block, NE);
  3747. if (NE->isArray() && *NE->getArraySize())
  3748. Block = Visit(*NE->getArraySize());
  3749. for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
  3750. E = NE->placement_arg_end(); I != E; ++I)
  3751. Block = Visit(*I);
  3752. return Block;
  3753. }
  3754. CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
  3755. AddStmtChoice asc) {
  3756. autoCreateBlock();
  3757. appendStmt(Block, DE);
  3758. QualType DTy = DE->getDestroyedType();
  3759. if (!DTy.isNull()) {
  3760. DTy = DTy.getNonReferenceType();
  3761. CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
  3762. if (RD) {
  3763. if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
  3764. appendDeleteDtor(Block, RD, DE);
  3765. }
  3766. }
  3767. return VisitChildren(DE);
  3768. }
  3769. CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
  3770. AddStmtChoice asc) {
  3771. if (asc.alwaysAdd(*this, E)) {
  3772. autoCreateBlock();
  3773. appendStmt(Block, E);
  3774. // We do not want to propagate the AlwaysAdd property.
  3775. asc = asc.withAlwaysAdd(false);
  3776. }
  3777. return Visit(E->getSubExpr(), asc);
  3778. }
  3779. CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
  3780. AddStmtChoice asc) {
  3781. // If the constructor takes objects as arguments by value, we need to properly
  3782. // construct these objects. Construction contexts we find here aren't for the
  3783. // constructor C, they're for its arguments only.
  3784. findConstructionContextsForArguments(C);
  3785. autoCreateBlock();
  3786. appendConstructor(Block, C);
  3787. return VisitChildren(C);
  3788. }
  3789. CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
  3790. AddStmtChoice asc) {
  3791. if (asc.alwaysAdd(*this, E)) {
  3792. autoCreateBlock();
  3793. appendStmt(Block, E);
  3794. }
  3795. if (E->getCastKind() == CK_IntegralToBoolean)
  3796. tryEvaluateBool(E->getSubExpr()->IgnoreParens());
  3797. return Visit(E->getSubExpr(), AddStmtChoice());
  3798. }
  3799. CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
  3800. return Visit(E->getSubExpr(), AddStmtChoice());
  3801. }
  3802. CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
  3803. // Lazily create the indirect-goto dispatch block if there isn't one already.
  3804. CFGBlock *IBlock = cfg->getIndirectGotoBlock();
  3805. if (!IBlock) {
  3806. IBlock = createBlock(false);
  3807. cfg->setIndirectGotoBlock(IBlock);
  3808. }
  3809. // IndirectGoto is a control-flow statement. Thus we stop processing the
  3810. // current block and create a new one.
  3811. if (badCFG)
  3812. return nullptr;
  3813. Block = createBlock(false);
  3814. Block->setTerminator(I);
  3815. addSuccessor(Block, IBlock);
  3816. return addStmt(I->getTarget());
  3817. }
  3818. CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
  3819. TempDtorContext &Context) {
  3820. assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
  3821. tryAgain:
  3822. if (!E) {
  3823. badCFG = true;
  3824. return nullptr;
  3825. }
  3826. switch (E->getStmtClass()) {
  3827. default:
  3828. return VisitChildrenForTemporaryDtors(E, false, Context);
  3829. case Stmt::InitListExprClass:
  3830. return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
  3831. case Stmt::BinaryOperatorClass:
  3832. return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
  3833. ExternallyDestructed,
  3834. Context);
  3835. case Stmt::CXXBindTemporaryExprClass:
  3836. return VisitCXXBindTemporaryExprForTemporaryDtors(
  3837. cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context);
  3838. case Stmt::BinaryConditionalOperatorClass:
  3839. case Stmt::ConditionalOperatorClass:
  3840. return VisitConditionalOperatorForTemporaryDtors(
  3841. cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context);
  3842. case Stmt::ImplicitCastExprClass:
  3843. // For implicit cast we want ExternallyDestructed to be passed further.
  3844. E = cast<CastExpr>(E)->getSubExpr();
  3845. goto tryAgain;
  3846. case Stmt::CXXFunctionalCastExprClass:
  3847. // For functional cast we want ExternallyDestructed to be passed further.
  3848. E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
  3849. goto tryAgain;
  3850. case Stmt::ConstantExprClass:
  3851. E = cast<ConstantExpr>(E)->getSubExpr();
  3852. goto tryAgain;
  3853. case Stmt::ParenExprClass:
  3854. E = cast<ParenExpr>(E)->getSubExpr();
  3855. goto tryAgain;
  3856. case Stmt::MaterializeTemporaryExprClass: {
  3857. const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
  3858. ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression);
  3859. SmallVector<const Expr *, 2> CommaLHSs;
  3860. SmallVector<SubobjectAdjustment, 2> Adjustments;
  3861. // Find the expression whose lifetime needs to be extended.
  3862. E = const_cast<Expr *>(
  3863. cast<MaterializeTemporaryExpr>(E)
  3864. ->GetTemporaryExpr()
  3865. ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
  3866. // Visit the skipped comma operator left-hand sides for other temporaries.
  3867. for (const Expr *CommaLHS : CommaLHSs) {
  3868. VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
  3869. /*ExternallyDestructed=*/false, Context);
  3870. }
  3871. goto tryAgain;
  3872. }
  3873. case Stmt::BlockExprClass:
  3874. // Don't recurse into blocks; their subexpressions don't get evaluated
  3875. // here.
  3876. return Block;
  3877. case Stmt::LambdaExprClass: {
  3878. // For lambda expressions, only recurse into the capture initializers,
  3879. // and not the body.
  3880. auto *LE = cast<LambdaExpr>(E);
  3881. CFGBlock *B = Block;
  3882. for (Expr *Init : LE->capture_inits()) {
  3883. if (Init) {
  3884. if (CFGBlock *R = VisitForTemporaryDtors(
  3885. Init, /*ExternallyDestructed=*/true, Context))
  3886. B = R;
  3887. }
  3888. }
  3889. return B;
  3890. }
  3891. case Stmt::StmtExprClass:
  3892. // Don't recurse into statement expressions; any cleanups inside them
  3893. // will be wrapped in their own ExprWithCleanups.
  3894. return Block;
  3895. case Stmt::CXXDefaultArgExprClass:
  3896. E = cast<CXXDefaultArgExpr>(E)->getExpr();
  3897. goto tryAgain;
  3898. case Stmt::CXXDefaultInitExprClass:
  3899. E = cast<CXXDefaultInitExpr>(E)->getExpr();
  3900. goto tryAgain;
  3901. }
  3902. }
  3903. CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
  3904. bool ExternallyDestructed,
  3905. TempDtorContext &Context) {
  3906. if (isa<LambdaExpr>(E)) {
  3907. // Do not visit the children of lambdas; they have their own CFGs.
  3908. return Block;
  3909. }
  3910. // When visiting children for destructors we want to visit them in reverse
  3911. // order that they will appear in the CFG. Because the CFG is built
  3912. // bottom-up, this means we visit them in their natural order, which
  3913. // reverses them in the CFG.
  3914. CFGBlock *B = Block;
  3915. for (Stmt *Child : E->children())
  3916. if (Child)
  3917. if (CFGBlock *R = VisitForTemporaryDtors(Child, ExternallyDestructed, Context))
  3918. B = R;
  3919. return B;
  3920. }
  3921. CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
  3922. BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) {
  3923. if (E->isCommaOp()) {
  3924. // For comma operator LHS expression is visited
  3925. // before RHS expression. For destructors visit them in reverse order.
  3926. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context);
  3927. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
  3928. return LHSBlock ? LHSBlock : RHSBlock;
  3929. }
  3930. if (E->isLogicalOp()) {
  3931. VisitForTemporaryDtors(E->getLHS(), false, Context);
  3932. TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
  3933. if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
  3934. RHSExecuted.negate();
  3935. // We do not know at CFG-construction time whether the right-hand-side was
  3936. // executed, thus we add a branch node that depends on the temporary
  3937. // constructor call.
  3938. TempDtorContext RHSContext(
  3939. bothKnownTrue(Context.KnownExecuted, RHSExecuted));
  3940. VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
  3941. InsertTempDtorDecisionBlock(RHSContext);
  3942. return Block;
  3943. }
  3944. if (E->isAssignmentOp()) {
  3945. // For assignment operator (=) LHS expression is visited
  3946. // before RHS expression. For destructors visit them in reverse order.
  3947. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
  3948. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
  3949. return LHSBlock ? LHSBlock : RHSBlock;
  3950. }
  3951. // For any other binary operator RHS expression is visited before
  3952. // LHS expression (order of children). For destructors visit them in reverse
  3953. // order.
  3954. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
  3955. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
  3956. return RHSBlock ? RHSBlock : LHSBlock;
  3957. }
  3958. CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
  3959. CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) {
  3960. // First add destructors for temporaries in subexpression.
  3961. // Because VisitCXXBindTemporaryExpr calls setDestructed:
  3962. CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context);
  3963. if (!ExternallyDestructed) {
  3964. // If lifetime of temporary is not prolonged (by assigning to constant
  3965. // reference) add destructor for it.
  3966. const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
  3967. if (Dtor->getParent()->isAnyDestructorNoReturn()) {
  3968. // If the destructor is marked as a no-return destructor, we need to
  3969. // create a new block for the destructor which does not have as a
  3970. // successor anything built thus far. Control won't flow out of this
  3971. // block.
  3972. if (B) Succ = B;
  3973. Block = createNoReturnBlock();
  3974. } else if (Context.needsTempDtorBranch()) {
  3975. // If we need to introduce a branch, we add a new block that we will hook
  3976. // up to a decision block later.
  3977. if (B) Succ = B;
  3978. Block = createBlock();
  3979. } else {
  3980. autoCreateBlock();
  3981. }
  3982. if (Context.needsTempDtorBranch()) {
  3983. Context.setDecisionPoint(Succ, E);
  3984. }
  3985. appendTemporaryDtor(Block, E);
  3986. B = Block;
  3987. }
  3988. return B;
  3989. }
  3990. void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
  3991. CFGBlock *FalseSucc) {
  3992. if (!Context.TerminatorExpr) {
  3993. // If no temporary was found, we do not need to insert a decision point.
  3994. return;
  3995. }
  3996. assert(Context.TerminatorExpr);
  3997. CFGBlock *Decision = createBlock(false);
  3998. Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
  3999. CFGTerminator::TemporaryDtorsBranch));
  4000. addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
  4001. addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
  4002. !Context.KnownExecuted.isTrue());
  4003. Block = Decision;
  4004. }
  4005. CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
  4006. AbstractConditionalOperator *E, bool ExternallyDestructed,
  4007. TempDtorContext &Context) {
  4008. VisitForTemporaryDtors(E->getCond(), false, Context);
  4009. CFGBlock *ConditionBlock = Block;
  4010. CFGBlock *ConditionSucc = Succ;
  4011. TryResult ConditionVal = tryEvaluateBool(E->getCond());
  4012. TryResult NegatedVal = ConditionVal;
  4013. if (NegatedVal.isKnown()) NegatedVal.negate();
  4014. TempDtorContext TrueContext(
  4015. bothKnownTrue(Context.KnownExecuted, ConditionVal));
  4016. VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext);
  4017. CFGBlock *TrueBlock = Block;
  4018. Block = ConditionBlock;
  4019. Succ = ConditionSucc;
  4020. TempDtorContext FalseContext(
  4021. bothKnownTrue(Context.KnownExecuted, NegatedVal));
  4022. VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext);
  4023. if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
  4024. InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
  4025. } else if (TrueContext.TerminatorExpr) {
  4026. Block = TrueBlock;
  4027. InsertTempDtorDecisionBlock(TrueContext);
  4028. } else {
  4029. InsertTempDtorDecisionBlock(FalseContext);
  4030. }
  4031. return Block;
  4032. }
  4033. CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
  4034. AddStmtChoice asc) {
  4035. if (asc.alwaysAdd(*this, D)) {
  4036. autoCreateBlock();
  4037. appendStmt(Block, D);
  4038. }
  4039. // Iterate over all used expression in clauses.
  4040. CFGBlock *B = Block;
  4041. // Reverse the elements to process them in natural order. Iterators are not
  4042. // bidirectional, so we need to create temp vector.
  4043. SmallVector<Stmt *, 8> Used(
  4044. OMPExecutableDirective::used_clauses_children(D->clauses()));
  4045. for (Stmt *S : llvm::reverse(Used)) {
  4046. assert(S && "Expected non-null used-in-clause child.");
  4047. if (CFGBlock *R = Visit(S))
  4048. B = R;
  4049. }
  4050. // Visit associated structured block if any.
  4051. if (!D->isStandaloneDirective())
  4052. if (CapturedStmt *CS = D->getInnermostCapturedStmt()) {
  4053. Stmt *S = CS->getCapturedStmt();
  4054. if (!isa<CompoundStmt>(S))
  4055. addLocalScopeAndDtors(S);
  4056. if (CFGBlock *R = addStmt(S))
  4057. B = R;
  4058. }
  4059. return B;
  4060. }
  4061. /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
  4062. /// no successors or predecessors. If this is the first block created in the
  4063. /// CFG, it is automatically set to be the Entry and Exit of the CFG.
  4064. CFGBlock *CFG::createBlock() {
  4065. bool first_block = begin() == end();
  4066. // Create the block.
  4067. CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
  4068. new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
  4069. Blocks.push_back(Mem, BlkBVC);
  4070. // If this is the first block, set it as the Entry and Exit.
  4071. if (first_block)
  4072. Entry = Exit = &back();
  4073. // Return the block.
  4074. return &back();
  4075. }
  4076. /// buildCFG - Constructs a CFG from an AST.
  4077. std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
  4078. ASTContext *C, const BuildOptions &BO) {
  4079. CFGBuilder Builder(C, BO);
  4080. return Builder.buildCFG(D, Statement);
  4081. }
  4082. bool CFG::isLinear() const {
  4083. // Quick path: if we only have the ENTRY block, the EXIT block, and some code
  4084. // in between, then we have no room for control flow.
  4085. if (size() <= 3)
  4086. return true;
  4087. // Traverse the CFG until we find a branch.
  4088. // TODO: While this should still be very fast,
  4089. // maybe we should cache the answer.
  4090. llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
  4091. const CFGBlock *B = Entry;
  4092. while (B != Exit) {
  4093. auto IteratorAndFlag = Visited.insert(B);
  4094. if (!IteratorAndFlag.second) {
  4095. // We looped back to a block that we've already visited. Not linear.
  4096. return false;
  4097. }
  4098. // Iterate over reachable successors.
  4099. const CFGBlock *FirstReachableB = nullptr;
  4100. for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
  4101. if (!AB.isReachable())
  4102. continue;
  4103. if (FirstReachableB == nullptr) {
  4104. FirstReachableB = &*AB;
  4105. } else {
  4106. // We've encountered a branch. It's not a linear CFG.
  4107. return false;
  4108. }
  4109. }
  4110. if (!FirstReachableB) {
  4111. // We reached a dead end. EXIT is unreachable. This is linear enough.
  4112. return true;
  4113. }
  4114. // There's only one way to move forward. Proceed.
  4115. B = FirstReachableB;
  4116. }
  4117. // We reached EXIT and found no branches.
  4118. return true;
  4119. }
  4120. const CXXDestructorDecl *
  4121. CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
  4122. switch (getKind()) {
  4123. case CFGElement::Initializer:
  4124. case CFGElement::NewAllocator:
  4125. case CFGElement::LoopExit:
  4126. case CFGElement::LifetimeEnds:
  4127. case CFGElement::Statement:
  4128. case CFGElement::Constructor:
  4129. case CFGElement::CXXRecordTypedCall:
  4130. case CFGElement::ScopeBegin:
  4131. case CFGElement::ScopeEnd:
  4132. llvm_unreachable("getDestructorDecl should only be used with "
  4133. "ImplicitDtors");
  4134. case CFGElement::AutomaticObjectDtor: {
  4135. const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
  4136. QualType ty = var->getType();
  4137. // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
  4138. //
  4139. // Lifetime-extending constructs are handled here. This works for a single
  4140. // temporary in an initializer expression.
  4141. if (ty->isReferenceType()) {
  4142. if (const Expr *Init = var->getInit()) {
  4143. ty = getReferenceInitTemporaryType(Init);
  4144. }
  4145. }
  4146. while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
  4147. ty = arrayType->getElementType();
  4148. }
  4149. // The situation when the type of the lifetime-extending reference
  4150. // does not correspond to the type of the object is supposed
  4151. // to be handled by now. In particular, 'ty' is now the unwrapped
  4152. // record type.
  4153. const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
  4154. assert(classDecl);
  4155. return classDecl->getDestructor();
  4156. }
  4157. case CFGElement::DeleteDtor: {
  4158. const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
  4159. QualType DTy = DE->getDestroyedType();
  4160. DTy = DTy.getNonReferenceType();
  4161. const CXXRecordDecl *classDecl =
  4162. astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
  4163. return classDecl->getDestructor();
  4164. }
  4165. case CFGElement::TemporaryDtor: {
  4166. const CXXBindTemporaryExpr *bindExpr =
  4167. castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
  4168. const CXXTemporary *temp = bindExpr->getTemporary();
  4169. return temp->getDestructor();
  4170. }
  4171. case CFGElement::BaseDtor:
  4172. case CFGElement::MemberDtor:
  4173. // Not yet supported.
  4174. return nullptr;
  4175. }
  4176. llvm_unreachable("getKind() returned bogus value");
  4177. }
  4178. //===----------------------------------------------------------------------===//
  4179. // CFGBlock operations.
  4180. //===----------------------------------------------------------------------===//
  4181. CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
  4182. : ReachableBlock(IsReachable ? B : nullptr),
  4183. UnreachableBlock(!IsReachable ? B : nullptr,
  4184. B && IsReachable ? AB_Normal : AB_Unreachable) {}
  4185. CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
  4186. : ReachableBlock(B),
  4187. UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
  4188. B == AlternateBlock ? AB_Alternate : AB_Normal) {}
  4189. void CFGBlock::addSuccessor(AdjacentBlock Succ,
  4190. BumpVectorContext &C) {
  4191. if (CFGBlock *B = Succ.getReachableBlock())
  4192. B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
  4193. if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
  4194. UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
  4195. Succs.push_back(Succ, C);
  4196. }
  4197. bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
  4198. const CFGBlock *From, const CFGBlock *To) {
  4199. if (F.IgnoreNullPredecessors && !From)
  4200. return true;
  4201. if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
  4202. // If the 'To' has no label or is labeled but the label isn't a
  4203. // CaseStmt then filter this edge.
  4204. if (const SwitchStmt *S =
  4205. dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
  4206. if (S->isAllEnumCasesCovered()) {
  4207. const Stmt *L = To->getLabel();
  4208. if (!L || !isa<CaseStmt>(L))
  4209. return true;
  4210. }
  4211. }
  4212. }
  4213. return false;
  4214. }
  4215. //===----------------------------------------------------------------------===//
  4216. // CFG pretty printing
  4217. //===----------------------------------------------------------------------===//
  4218. namespace {
  4219. class StmtPrinterHelper : public PrinterHelper {
  4220. using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
  4221. using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
  4222. StmtMapTy StmtMap;
  4223. DeclMapTy DeclMap;
  4224. signed currentBlock = 0;
  4225. unsigned currStmt = 0;
  4226. const LangOptions &LangOpts;
  4227. public:
  4228. StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
  4229. : LangOpts(LO) {
  4230. if (!cfg)
  4231. return;
  4232. for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
  4233. unsigned j = 1;
  4234. for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
  4235. BI != BEnd; ++BI, ++j ) {
  4236. if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
  4237. const Stmt *stmt= SE->getStmt();
  4238. std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
  4239. StmtMap[stmt] = P;
  4240. switch (stmt->getStmtClass()) {
  4241. case Stmt::DeclStmtClass:
  4242. DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
  4243. break;
  4244. case Stmt::IfStmtClass: {
  4245. const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
  4246. if (var)
  4247. DeclMap[var] = P;
  4248. break;
  4249. }
  4250. case Stmt::ForStmtClass: {
  4251. const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
  4252. if (var)
  4253. DeclMap[var] = P;
  4254. break;
  4255. }
  4256. case Stmt::WhileStmtClass: {
  4257. const VarDecl *var =
  4258. cast<WhileStmt>(stmt)->getConditionVariable();
  4259. if (var)
  4260. DeclMap[var] = P;
  4261. break;
  4262. }
  4263. case Stmt::SwitchStmtClass: {
  4264. const VarDecl *var =
  4265. cast<SwitchStmt>(stmt)->getConditionVariable();
  4266. if (var)
  4267. DeclMap[var] = P;
  4268. break;
  4269. }
  4270. case Stmt::CXXCatchStmtClass: {
  4271. const VarDecl *var =
  4272. cast<CXXCatchStmt>(stmt)->getExceptionDecl();
  4273. if (var)
  4274. DeclMap[var] = P;
  4275. break;
  4276. }
  4277. default:
  4278. break;
  4279. }
  4280. }
  4281. }
  4282. }
  4283. }
  4284. ~StmtPrinterHelper() override = default;
  4285. const LangOptions &getLangOpts() const { return LangOpts; }
  4286. void setBlockID(signed i) { currentBlock = i; }
  4287. void setStmtID(unsigned i) { currStmt = i; }
  4288. bool handledStmt(Stmt *S, raw_ostream &OS) override {
  4289. StmtMapTy::iterator I = StmtMap.find(S);
  4290. if (I == StmtMap.end())
  4291. return false;
  4292. if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
  4293. && I->second.second == currStmt) {
  4294. return false;
  4295. }
  4296. OS << "[B" << I->second.first << "." << I->second.second << "]";
  4297. return true;
  4298. }
  4299. bool handleDecl(const Decl *D, raw_ostream &OS) {
  4300. DeclMapTy::iterator I = DeclMap.find(D);
  4301. if (I == DeclMap.end())
  4302. return false;
  4303. if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
  4304. && I->second.second == currStmt) {
  4305. return false;
  4306. }
  4307. OS << "[B" << I->second.first << "." << I->second.second << "]";
  4308. return true;
  4309. }
  4310. };
  4311. class CFGBlockTerminatorPrint
  4312. : public StmtVisitor<CFGBlockTerminatorPrint,void> {
  4313. raw_ostream &OS;
  4314. StmtPrinterHelper* Helper;
  4315. PrintingPolicy Policy;
  4316. public:
  4317. CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
  4318. const PrintingPolicy &Policy)
  4319. : OS(os), Helper(helper), Policy(Policy) {
  4320. this->Policy.IncludeNewlines = false;
  4321. }
  4322. void VisitIfStmt(IfStmt *I) {
  4323. OS << "if ";
  4324. if (Stmt *C = I->getCond())
  4325. C->printPretty(OS, Helper, Policy);
  4326. }
  4327. // Default case.
  4328. void VisitStmt(Stmt *Terminator) {
  4329. Terminator->printPretty(OS, Helper, Policy);
  4330. }
  4331. void VisitDeclStmt(DeclStmt *DS) {
  4332. VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  4333. OS << "static init " << VD->getName();
  4334. }
  4335. void VisitForStmt(ForStmt *F) {
  4336. OS << "for (" ;
  4337. if (F->getInit())
  4338. OS << "...";
  4339. OS << "; ";
  4340. if (Stmt *C = F->getCond())
  4341. C->printPretty(OS, Helper, Policy);
  4342. OS << "; ";
  4343. if (F->getInc())
  4344. OS << "...";
  4345. OS << ")";
  4346. }
  4347. void VisitWhileStmt(WhileStmt *W) {
  4348. OS << "while " ;
  4349. if (Stmt *C = W->getCond())
  4350. C->printPretty(OS, Helper, Policy);
  4351. }
  4352. void VisitDoStmt(DoStmt *D) {
  4353. OS << "do ... while ";
  4354. if (Stmt *C = D->getCond())
  4355. C->printPretty(OS, Helper, Policy);
  4356. }
  4357. void VisitSwitchStmt(SwitchStmt *Terminator) {
  4358. OS << "switch ";
  4359. Terminator->getCond()->printPretty(OS, Helper, Policy);
  4360. }
  4361. void VisitCXXTryStmt(CXXTryStmt *CS) {
  4362. OS << "try ...";
  4363. }
  4364. void VisitSEHTryStmt(SEHTryStmt *CS) {
  4365. OS << "__try ...";
  4366. }
  4367. void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
  4368. if (Stmt *Cond = C->getCond())
  4369. Cond->printPretty(OS, Helper, Policy);
  4370. OS << " ? ... : ...";
  4371. }
  4372. void VisitChooseExpr(ChooseExpr *C) {
  4373. OS << "__builtin_choose_expr( ";
  4374. if (Stmt *Cond = C->getCond())
  4375. Cond->printPretty(OS, Helper, Policy);
  4376. OS << " )";
  4377. }
  4378. void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
  4379. OS << "goto *";
  4380. if (Stmt *T = I->getTarget())
  4381. T->printPretty(OS, Helper, Policy);
  4382. }
  4383. void VisitBinaryOperator(BinaryOperator* B) {
  4384. if (!B->isLogicalOp()) {
  4385. VisitExpr(B);
  4386. return;
  4387. }
  4388. if (B->getLHS())
  4389. B->getLHS()->printPretty(OS, Helper, Policy);
  4390. switch (B->getOpcode()) {
  4391. case BO_LOr:
  4392. OS << " || ...";
  4393. return;
  4394. case BO_LAnd:
  4395. OS << " && ...";
  4396. return;
  4397. default:
  4398. llvm_unreachable("Invalid logical operator.");
  4399. }
  4400. }
  4401. void VisitExpr(Expr *E) {
  4402. E->printPretty(OS, Helper, Policy);
  4403. }
  4404. public:
  4405. void print(CFGTerminator T) {
  4406. switch (T.getKind()) {
  4407. case CFGTerminator::StmtBranch:
  4408. Visit(T.getStmt());
  4409. break;
  4410. case CFGTerminator::TemporaryDtorsBranch:
  4411. OS << "(Temp Dtor) ";
  4412. Visit(T.getStmt());
  4413. break;
  4414. case CFGTerminator::VirtualBaseBranch:
  4415. OS << "(See if most derived ctor has already initialized vbases)";
  4416. break;
  4417. }
  4418. }
  4419. };
  4420. } // namespace
  4421. static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
  4422. const CXXCtorInitializer *I) {
  4423. if (I->isBaseInitializer())
  4424. OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
  4425. else if (I->isDelegatingInitializer())
  4426. OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
  4427. else
  4428. OS << I->getAnyMember()->getName();
  4429. OS << "(";
  4430. if (Expr *IE = I->getInit())
  4431. IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
  4432. OS << ")";
  4433. if (I->isBaseInitializer())
  4434. OS << " (Base initializer)";
  4435. else if (I->isDelegatingInitializer())
  4436. OS << " (Delegating initializer)";
  4437. else
  4438. OS << " (Member initializer)";
  4439. }
  4440. static void print_construction_context(raw_ostream &OS,
  4441. StmtPrinterHelper &Helper,
  4442. const ConstructionContext *CC) {
  4443. SmallVector<const Stmt *, 3> Stmts;
  4444. switch (CC->getKind()) {
  4445. case ConstructionContext::SimpleConstructorInitializerKind: {
  4446. OS << ", ";
  4447. const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
  4448. print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
  4449. return;
  4450. }
  4451. case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
  4452. OS << ", ";
  4453. const auto *CICC =
  4454. cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
  4455. print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
  4456. Stmts.push_back(CICC->getCXXBindTemporaryExpr());
  4457. break;
  4458. }
  4459. case ConstructionContext::SimpleVariableKind: {
  4460. const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
  4461. Stmts.push_back(SDSCC->getDeclStmt());
  4462. break;
  4463. }
  4464. case ConstructionContext::CXX17ElidedCopyVariableKind: {
  4465. const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
  4466. Stmts.push_back(CDSCC->getDeclStmt());
  4467. Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
  4468. break;
  4469. }
  4470. case ConstructionContext::NewAllocatedObjectKind: {
  4471. const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
  4472. Stmts.push_back(NECC->getCXXNewExpr());
  4473. break;
  4474. }
  4475. case ConstructionContext::SimpleReturnedValueKind: {
  4476. const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
  4477. Stmts.push_back(RSCC->getReturnStmt());
  4478. break;
  4479. }
  4480. case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
  4481. const auto *RSCC =
  4482. cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
  4483. Stmts.push_back(RSCC->getReturnStmt());
  4484. Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
  4485. break;
  4486. }
  4487. case ConstructionContext::SimpleTemporaryObjectKind: {
  4488. const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
  4489. Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
  4490. Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
  4491. break;
  4492. }
  4493. case ConstructionContext::ElidedTemporaryObjectKind: {
  4494. const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
  4495. Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
  4496. Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
  4497. Stmts.push_back(TOCC->getConstructorAfterElision());
  4498. break;
  4499. }
  4500. case ConstructionContext::ArgumentKind: {
  4501. const auto *ACC = cast<ArgumentConstructionContext>(CC);
  4502. if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
  4503. OS << ", ";
  4504. Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
  4505. }
  4506. OS << ", ";
  4507. Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
  4508. OS << "+" << ACC->getIndex();
  4509. return;
  4510. }
  4511. }
  4512. for (auto I: Stmts)
  4513. if (I) {
  4514. OS << ", ";
  4515. Helper.handledStmt(const_cast<Stmt *>(I), OS);
  4516. }
  4517. }
  4518. static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
  4519. const CFGElement &E);
  4520. void CFGElement::dumpToStream(llvm::raw_ostream &OS) const {
  4521. StmtPrinterHelper Helper(nullptr, {});
  4522. print_elem(OS, Helper, *this);
  4523. }
  4524. static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
  4525. const CFGElement &E) {
  4526. switch (E.getKind()) {
  4527. case CFGElement::Kind::Statement:
  4528. case CFGElement::Kind::CXXRecordTypedCall:
  4529. case CFGElement::Kind::Constructor: {
  4530. CFGStmt CS = E.castAs<CFGStmt>();
  4531. const Stmt *S = CS.getStmt();
  4532. assert(S != nullptr && "Expecting non-null Stmt");
  4533. // special printing for statement-expressions.
  4534. if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
  4535. const CompoundStmt *Sub = SE->getSubStmt();
  4536. auto Children = Sub->children();
  4537. if (Children.begin() != Children.end()) {
  4538. OS << "({ ... ; ";
  4539. Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
  4540. OS << " })\n";
  4541. return;
  4542. }
  4543. }
  4544. // special printing for comma expressions.
  4545. if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
  4546. if (B->getOpcode() == BO_Comma) {
  4547. OS << "... , ";
  4548. Helper.handledStmt(B->getRHS(),OS);
  4549. OS << '\n';
  4550. return;
  4551. }
  4552. }
  4553. S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
  4554. if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
  4555. if (isa<CXXOperatorCallExpr>(S))
  4556. OS << " (OperatorCall)";
  4557. OS << " (CXXRecordTypedCall";
  4558. print_construction_context(OS, Helper, VTC->getConstructionContext());
  4559. OS << ")";
  4560. } else if (isa<CXXOperatorCallExpr>(S)) {
  4561. OS << " (OperatorCall)";
  4562. } else if (isa<CXXBindTemporaryExpr>(S)) {
  4563. OS << " (BindTemporary)";
  4564. } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
  4565. OS << " (CXXConstructExpr";
  4566. if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
  4567. print_construction_context(OS, Helper, CE->getConstructionContext());
  4568. }
  4569. OS << ", " << CCE->getType().getAsString() << ")";
  4570. } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
  4571. OS << " (" << CE->getStmtClassName() << ", "
  4572. << CE->getCastKindName()
  4573. << ", " << CE->getType().getAsString()
  4574. << ")";
  4575. }
  4576. // Expressions need a newline.
  4577. if (isa<Expr>(S))
  4578. OS << '\n';
  4579. break;
  4580. }
  4581. case CFGElement::Kind::Initializer:
  4582. print_initializer(OS, Helper, E.castAs<CFGInitializer>().getInitializer());
  4583. OS << '\n';
  4584. break;
  4585. case CFGElement::Kind::AutomaticObjectDtor: {
  4586. CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>();
  4587. const VarDecl *VD = DE.getVarDecl();
  4588. Helper.handleDecl(VD, OS);
  4589. QualType T = VD->getType();
  4590. if (T->isReferenceType())
  4591. T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
  4592. OS << ".~";
  4593. T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts()));
  4594. OS << "() (Implicit destructor)\n";
  4595. break;
  4596. }
  4597. case CFGElement::Kind::LifetimeEnds:
  4598. Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS);
  4599. OS << " (Lifetime ends)\n";
  4600. break;
  4601. case CFGElement::Kind::LoopExit:
  4602. OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n";
  4603. break;
  4604. case CFGElement::Kind::ScopeBegin:
  4605. OS << "CFGScopeBegin(";
  4606. if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl())
  4607. OS << VD->getQualifiedNameAsString();
  4608. OS << ")\n";
  4609. break;
  4610. case CFGElement::Kind::ScopeEnd:
  4611. OS << "CFGScopeEnd(";
  4612. if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl())
  4613. OS << VD->getQualifiedNameAsString();
  4614. OS << ")\n";
  4615. break;
  4616. case CFGElement::Kind::NewAllocator:
  4617. OS << "CFGNewAllocator(";
  4618. if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr())
  4619. AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
  4620. OS << ")\n";
  4621. break;
  4622. case CFGElement::Kind::DeleteDtor: {
  4623. CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>();
  4624. const CXXRecordDecl *RD = DE.getCXXRecordDecl();
  4625. if (!RD)
  4626. return;
  4627. CXXDeleteExpr *DelExpr =
  4628. const_cast<CXXDeleteExpr*>(DE.getDeleteExpr());
  4629. Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
  4630. OS << "->~" << RD->getName().str() << "()";
  4631. OS << " (Implicit destructor)\n";
  4632. break;
  4633. }
  4634. case CFGElement::Kind::BaseDtor: {
  4635. const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier();
  4636. OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
  4637. OS << " (Base object destructor)\n";
  4638. break;
  4639. }
  4640. case CFGElement::Kind::MemberDtor: {
  4641. const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl();
  4642. const Type *T = FD->getType()->getBaseElementTypeUnsafe();
  4643. OS << "this->" << FD->getName();
  4644. OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
  4645. OS << " (Member object destructor)\n";
  4646. break;
  4647. }
  4648. case CFGElement::Kind::TemporaryDtor: {
  4649. const CXXBindTemporaryExpr *BT = E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
  4650. OS << "~";
  4651. BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
  4652. OS << "() (Temporary object destructor)\n";
  4653. break;
  4654. }
  4655. }
  4656. }
  4657. static void print_block(raw_ostream &OS, const CFG* cfg,
  4658. const CFGBlock &B,
  4659. StmtPrinterHelper &Helper, bool print_edges,
  4660. bool ShowColors) {
  4661. Helper.setBlockID(B.getBlockID());
  4662. // Print the header.
  4663. if (ShowColors)
  4664. OS.changeColor(raw_ostream::YELLOW, true);
  4665. OS << "\n [B" << B.getBlockID();
  4666. if (&B == &cfg->getEntry())
  4667. OS << " (ENTRY)]\n";
  4668. else if (&B == &cfg->getExit())
  4669. OS << " (EXIT)]\n";
  4670. else if (&B == cfg->getIndirectGotoBlock())
  4671. OS << " (INDIRECT GOTO DISPATCH)]\n";
  4672. else if (B.hasNoReturnElement())
  4673. OS << " (NORETURN)]\n";
  4674. else
  4675. OS << "]\n";
  4676. if (ShowColors)
  4677. OS.resetColor();
  4678. // Print the label of this block.
  4679. if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
  4680. if (print_edges)
  4681. OS << " ";
  4682. if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
  4683. OS << L->getName();
  4684. else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  4685. OS << "case ";
  4686. if (C->getLHS())
  4687. C->getLHS()->printPretty(OS, &Helper,
  4688. PrintingPolicy(Helper.getLangOpts()));
  4689. if (C->getRHS()) {
  4690. OS << " ... ";
  4691. C->getRHS()->printPretty(OS, &Helper,
  4692. PrintingPolicy(Helper.getLangOpts()));
  4693. }
  4694. } else if (isa<DefaultStmt>(Label))
  4695. OS << "default";
  4696. else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
  4697. OS << "catch (";
  4698. if (CS->getExceptionDecl())
  4699. CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
  4700. 0);
  4701. else
  4702. OS << "...";
  4703. OS << ")";
  4704. } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
  4705. OS << "__except (";
  4706. ES->getFilterExpr()->printPretty(OS, &Helper,
  4707. PrintingPolicy(Helper.getLangOpts()), 0);
  4708. OS << ")";
  4709. } else
  4710. llvm_unreachable("Invalid label statement in CFGBlock.");
  4711. OS << ":\n";
  4712. }
  4713. // Iterate through the statements in the block and print them.
  4714. unsigned j = 1;
  4715. for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
  4716. I != E ; ++I, ++j ) {
  4717. // Print the statement # in the basic block and the statement itself.
  4718. if (print_edges)
  4719. OS << " ";
  4720. OS << llvm::format("%3d", j) << ": ";
  4721. Helper.setStmtID(j);
  4722. print_elem(OS, Helper, *I);
  4723. }
  4724. // Print the terminator of this block.
  4725. if (B.getTerminator().isValid()) {
  4726. if (ShowColors)
  4727. OS.changeColor(raw_ostream::GREEN);
  4728. OS << " T: ";
  4729. Helper.setBlockID(-1);
  4730. PrintingPolicy PP(Helper.getLangOpts());
  4731. CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
  4732. TPrinter.print(B.getTerminator());
  4733. OS << '\n';
  4734. if (ShowColors)
  4735. OS.resetColor();
  4736. }
  4737. if (print_edges) {
  4738. // Print the predecessors of this block.
  4739. if (!B.pred_empty()) {
  4740. const raw_ostream::Colors Color = raw_ostream::BLUE;
  4741. if (ShowColors)
  4742. OS.changeColor(Color);
  4743. OS << " Preds " ;
  4744. if (ShowColors)
  4745. OS.resetColor();
  4746. OS << '(' << B.pred_size() << "):";
  4747. unsigned i = 0;
  4748. if (ShowColors)
  4749. OS.changeColor(Color);
  4750. for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
  4751. I != E; ++I, ++i) {
  4752. if (i % 10 == 8)
  4753. OS << "\n ";
  4754. CFGBlock *B = *I;
  4755. bool Reachable = true;
  4756. if (!B) {
  4757. Reachable = false;
  4758. B = I->getPossiblyUnreachableBlock();
  4759. }
  4760. OS << " B" << B->getBlockID();
  4761. if (!Reachable)
  4762. OS << "(Unreachable)";
  4763. }
  4764. if (ShowColors)
  4765. OS.resetColor();
  4766. OS << '\n';
  4767. }
  4768. // Print the successors of this block.
  4769. if (!B.succ_empty()) {
  4770. const raw_ostream::Colors Color = raw_ostream::MAGENTA;
  4771. if (ShowColors)
  4772. OS.changeColor(Color);
  4773. OS << " Succs ";
  4774. if (ShowColors)
  4775. OS.resetColor();
  4776. OS << '(' << B.succ_size() << "):";
  4777. unsigned i = 0;
  4778. if (ShowColors)
  4779. OS.changeColor(Color);
  4780. for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
  4781. I != E; ++I, ++i) {
  4782. if (i % 10 == 8)
  4783. OS << "\n ";
  4784. CFGBlock *B = *I;
  4785. bool Reachable = true;
  4786. if (!B) {
  4787. Reachable = false;
  4788. B = I->getPossiblyUnreachableBlock();
  4789. }
  4790. if (B) {
  4791. OS << " B" << B->getBlockID();
  4792. if (!Reachable)
  4793. OS << "(Unreachable)";
  4794. }
  4795. else {
  4796. OS << " NULL";
  4797. }
  4798. }
  4799. if (ShowColors)
  4800. OS.resetColor();
  4801. OS << '\n';
  4802. }
  4803. }
  4804. }
  4805. /// dump - A simple pretty printer of a CFG that outputs to stderr.
  4806. void CFG::dump(const LangOptions &LO, bool ShowColors) const {
  4807. print(llvm::errs(), LO, ShowColors);
  4808. }
  4809. /// print - A simple pretty printer of a CFG that outputs to an ostream.
  4810. void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
  4811. StmtPrinterHelper Helper(this, LO);
  4812. // Print the entry block.
  4813. print_block(OS, this, getEntry(), Helper, true, ShowColors);
  4814. // Iterate through the CFGBlocks and print them one by one.
  4815. for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
  4816. // Skip the entry block, because we already printed it.
  4817. if (&(**I) == &getEntry() || &(**I) == &getExit())
  4818. continue;
  4819. print_block(OS, this, **I, Helper, true, ShowColors);
  4820. }
  4821. // Print the exit block.
  4822. print_block(OS, this, getExit(), Helper, true, ShowColors);
  4823. OS << '\n';
  4824. OS.flush();
  4825. }
  4826. size_t CFGBlock::getIndexInCFG() const {
  4827. return llvm::find(*getParent(), this) - getParent()->begin();
  4828. }
  4829. /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
  4830. void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
  4831. bool ShowColors) const {
  4832. print(llvm::errs(), cfg, LO, ShowColors);
  4833. }
  4834. LLVM_DUMP_METHOD void CFGBlock::dump() const {
  4835. dump(getParent(), LangOptions(), false);
  4836. }
  4837. /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
  4838. /// Generally this will only be called from CFG::print.
  4839. void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
  4840. const LangOptions &LO, bool ShowColors) const {
  4841. StmtPrinterHelper Helper(cfg, LO);
  4842. print_block(OS, cfg, *this, Helper, true, ShowColors);
  4843. OS << '\n';
  4844. }
  4845. /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
  4846. void CFGBlock::printTerminator(raw_ostream &OS,
  4847. const LangOptions &LO) const {
  4848. CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
  4849. TPrinter.print(getTerminator());
  4850. }
  4851. /// printTerminatorJson - Pretty-prints the terminator in JSON format.
  4852. void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
  4853. bool AddQuotes) const {
  4854. std::string Buf;
  4855. llvm::raw_string_ostream TempOut(Buf);
  4856. printTerminator(TempOut, LO);
  4857. Out << JsonFormat(TempOut.str(), AddQuotes);
  4858. }
  4859. // Returns true if by simply looking at the block, we can be sure that it
  4860. // results in a sink during analysis. This is useful to know when the analysis
  4861. // was interrupted, and we try to figure out if it would sink eventually.
  4862. // There may be many more reasons why a sink would appear during analysis
  4863. // (eg. checkers may generate sinks arbitrarily), but here we only consider
  4864. // sinks that would be obvious by looking at the CFG.
  4865. static bool isImmediateSinkBlock(const CFGBlock *Blk) {
  4866. if (Blk->hasNoReturnElement())
  4867. return true;
  4868. // FIXME: Throw-expressions are currently generating sinks during analysis:
  4869. // they're not supported yet, and also often used for actually terminating
  4870. // the program. So we should treat them as sinks in this analysis as well,
  4871. // at least for now, but once we have better support for exceptions,
  4872. // we'd need to carefully handle the case when the throw is being
  4873. // immediately caught.
  4874. if (std::any_of(Blk->begin(), Blk->end(), [](const CFGElement &Elm) {
  4875. if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
  4876. if (isa<CXXThrowExpr>(StmtElm->getStmt()))
  4877. return true;
  4878. return false;
  4879. }))
  4880. return true;
  4881. return false;
  4882. }
  4883. bool CFGBlock::isInevitablySinking() const {
  4884. const CFG &Cfg = *getParent();
  4885. const CFGBlock *StartBlk = this;
  4886. if (isImmediateSinkBlock(StartBlk))
  4887. return true;
  4888. llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
  4889. llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
  4890. DFSWorkList.push_back(StartBlk);
  4891. while (!DFSWorkList.empty()) {
  4892. const CFGBlock *Blk = DFSWorkList.back();
  4893. DFSWorkList.pop_back();
  4894. Visited.insert(Blk);
  4895. // If at least one path reaches the CFG exit, it means that control is
  4896. // returned to the caller. For now, say that we are not sure what
  4897. // happens next. If necessary, this can be improved to analyze
  4898. // the parent StackFrameContext's call site in a similar manner.
  4899. if (Blk == &Cfg.getExit())
  4900. return false;
  4901. for (const auto &Succ : Blk->succs()) {
  4902. if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
  4903. if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
  4904. // If the block has reachable child blocks that aren't no-return,
  4905. // add them to the worklist.
  4906. DFSWorkList.push_back(SuccBlk);
  4907. }
  4908. }
  4909. }
  4910. }
  4911. // Nothing reached the exit. It can only mean one thing: there's no return.
  4912. return true;
  4913. }
  4914. const Expr *CFGBlock::getLastCondition() const {
  4915. // If the terminator is a temporary dtor or a virtual base, etc, we can't
  4916. // retrieve a meaningful condition, bail out.
  4917. if (Terminator.getKind() != CFGTerminator::StmtBranch)
  4918. return nullptr;
  4919. // Also, if this method was called on a block that doesn't have 2 successors,
  4920. // this block doesn't have retrievable condition.
  4921. if (succ_size() < 2)
  4922. return nullptr;
  4923. auto StmtElem = rbegin()->getAs<CFGStmt>();
  4924. if (!StmtElem)
  4925. return nullptr;
  4926. const Stmt *Cond = StmtElem->getStmt();
  4927. if (isa<ObjCForCollectionStmt>(Cond))
  4928. return nullptr;
  4929. // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
  4930. // the cast<>.
  4931. return cast<Expr>(Cond)->IgnoreParens();
  4932. }
  4933. Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
  4934. Stmt *Terminator = getTerminatorStmt();
  4935. if (!Terminator)
  4936. return nullptr;
  4937. Expr *E = nullptr;
  4938. switch (Terminator->getStmtClass()) {
  4939. default:
  4940. break;
  4941. case Stmt::CXXForRangeStmtClass:
  4942. E = cast<CXXForRangeStmt>(Terminator)->getCond();
  4943. break;
  4944. case Stmt::ForStmtClass:
  4945. E = cast<ForStmt>(Terminator)->getCond();
  4946. break;
  4947. case Stmt::WhileStmtClass:
  4948. E = cast<WhileStmt>(Terminator)->getCond();
  4949. break;
  4950. case Stmt::DoStmtClass:
  4951. E = cast<DoStmt>(Terminator)->getCond();
  4952. break;
  4953. case Stmt::IfStmtClass:
  4954. E = cast<IfStmt>(Terminator)->getCond();
  4955. break;
  4956. case Stmt::ChooseExprClass:
  4957. E = cast<ChooseExpr>(Terminator)->getCond();
  4958. break;
  4959. case Stmt::IndirectGotoStmtClass:
  4960. E = cast<IndirectGotoStmt>(Terminator)->getTarget();
  4961. break;
  4962. case Stmt::SwitchStmtClass:
  4963. E = cast<SwitchStmt>(Terminator)->getCond();
  4964. break;
  4965. case Stmt::BinaryConditionalOperatorClass:
  4966. E = cast<BinaryConditionalOperator>(Terminator)->getCond();
  4967. break;
  4968. case Stmt::ConditionalOperatorClass:
  4969. E = cast<ConditionalOperator>(Terminator)->getCond();
  4970. break;
  4971. case Stmt::BinaryOperatorClass: // '&&' and '||'
  4972. E = cast<BinaryOperator>(Terminator)->getLHS();
  4973. break;
  4974. case Stmt::ObjCForCollectionStmtClass:
  4975. return Terminator;
  4976. }
  4977. if (!StripParens)
  4978. return E;
  4979. return E ? E->IgnoreParens() : nullptr;
  4980. }
  4981. //===----------------------------------------------------------------------===//
  4982. // CFG Graphviz Visualization
  4983. //===----------------------------------------------------------------------===//
  4984. #ifndef NDEBUG
  4985. static StmtPrinterHelper* GraphHelper;
  4986. #endif
  4987. void CFG::viewCFG(const LangOptions &LO) const {
  4988. #ifndef NDEBUG
  4989. StmtPrinterHelper H(this, LO);
  4990. GraphHelper = &H;
  4991. llvm::ViewGraph(this,"CFG");
  4992. GraphHelper = nullptr;
  4993. #endif
  4994. }
  4995. namespace llvm {
  4996. template<>
  4997. struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
  4998. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  4999. static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
  5000. #ifndef NDEBUG
  5001. std::string OutSStr;
  5002. llvm::raw_string_ostream Out(OutSStr);
  5003. print_block(Out,Graph, *Node, *GraphHelper, false, false);
  5004. std::string& OutStr = Out.str();
  5005. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  5006. // Process string output to make it nicer...
  5007. for (unsigned i = 0; i != OutStr.length(); ++i)
  5008. if (OutStr[i] == '\n') { // Left justify
  5009. OutStr[i] = '\\';
  5010. OutStr.insert(OutStr.begin()+i+1, 'l');
  5011. }
  5012. return OutStr;
  5013. #else
  5014. return {};
  5015. #endif
  5016. }
  5017. };
  5018. } // namespace llvm