AttributorAttributes.cpp 304 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181
  1. //===- AttributorAttributes.cpp - Attributes for Attributor deduction -----===//
  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. // See the Attributor.h file comment and the class descriptions in that file for
  10. // more information.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/IPO/Attributor.h"
  14. #include "llvm/ADT/SCCIterator.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/Analysis/AliasAnalysis.h"
  18. #include "llvm/Analysis/AssumeBundleQueries.h"
  19. #include "llvm/Analysis/AssumptionCache.h"
  20. #include "llvm/Analysis/CaptureTracking.h"
  21. #include "llvm/Analysis/LazyValueInfo.h"
  22. #include "llvm/Analysis/MemoryBuiltins.h"
  23. #include "llvm/Analysis/ScalarEvolution.h"
  24. #include "llvm/Analysis/TargetTransformInfo.h"
  25. #include "llvm/Analysis/ValueTracking.h"
  26. #include "llvm/IR/IRBuilder.h"
  27. #include "llvm/IR/Instruction.h"
  28. #include "llvm/IR/IntrinsicInst.h"
  29. #include "llvm/IR/NoFolder.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Transforms/IPO/ArgumentPromotion.h"
  32. #include "llvm/Transforms/Utils/Local.h"
  33. #include <cassert>
  34. using namespace llvm;
  35. #define DEBUG_TYPE "attributor"
  36. static cl::opt<bool> ManifestInternal(
  37. "attributor-manifest-internal", cl::Hidden,
  38. cl::desc("Manifest Attributor internal string attributes."),
  39. cl::init(false));
  40. static cl::opt<int> MaxHeapToStackSize("max-heap-to-stack-size", cl::init(128),
  41. cl::Hidden);
  42. template <>
  43. unsigned llvm::PotentialConstantIntValuesState::MaxPotentialValues = 0;
  44. static cl::opt<unsigned, true> MaxPotentialValues(
  45. "attributor-max-potential-values", cl::Hidden,
  46. cl::desc("Maximum number of potential values to be "
  47. "tracked for each position."),
  48. cl::location(llvm::PotentialConstantIntValuesState::MaxPotentialValues),
  49. cl::init(7));
  50. STATISTIC(NumAAs, "Number of abstract attributes created");
  51. // Some helper macros to deal with statistics tracking.
  52. //
  53. // Usage:
  54. // For simple IR attribute tracking overload trackStatistics in the abstract
  55. // attribute and choose the right STATS_DECLTRACK_********* macro,
  56. // e.g.,:
  57. // void trackStatistics() const override {
  58. // STATS_DECLTRACK_ARG_ATTR(returned)
  59. // }
  60. // If there is a single "increment" side one can use the macro
  61. // STATS_DECLTRACK with a custom message. If there are multiple increment
  62. // sides, STATS_DECL and STATS_TRACK can also be used separately.
  63. //
  64. #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \
  65. ("Number of " #TYPE " marked '" #NAME "'")
  66. #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
  67. #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG);
  68. #define STATS_DECL(NAME, TYPE, MSG) \
  69. STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG);
  70. #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
  71. #define STATS_DECLTRACK(NAME, TYPE, MSG) \
  72. { \
  73. STATS_DECL(NAME, TYPE, MSG) \
  74. STATS_TRACK(NAME, TYPE) \
  75. }
  76. #define STATS_DECLTRACK_ARG_ATTR(NAME) \
  77. STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
  78. #define STATS_DECLTRACK_CSARG_ATTR(NAME) \
  79. STATS_DECLTRACK(NAME, CSArguments, \
  80. BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
  81. #define STATS_DECLTRACK_FN_ATTR(NAME) \
  82. STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
  83. #define STATS_DECLTRACK_CS_ATTR(NAME) \
  84. STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME))
  85. #define STATS_DECLTRACK_FNRET_ATTR(NAME) \
  86. STATS_DECLTRACK(NAME, FunctionReturn, \
  87. BUILD_STAT_MSG_IR_ATTR(function returns, NAME))
  88. #define STATS_DECLTRACK_CSRET_ATTR(NAME) \
  89. STATS_DECLTRACK(NAME, CSReturn, \
  90. BUILD_STAT_MSG_IR_ATTR(call site returns, NAME))
  91. #define STATS_DECLTRACK_FLOATING_ATTR(NAME) \
  92. STATS_DECLTRACK(NAME, Floating, \
  93. ("Number of floating values known to be '" #NAME "'"))
  94. // Specialization of the operator<< for abstract attributes subclasses. This
  95. // disambiguates situations where multiple operators are applicable.
  96. namespace llvm {
  97. #define PIPE_OPERATOR(CLASS) \
  98. raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) { \
  99. return OS << static_cast<const AbstractAttribute &>(AA); \
  100. }
  101. PIPE_OPERATOR(AAIsDead)
  102. PIPE_OPERATOR(AANoUnwind)
  103. PIPE_OPERATOR(AANoSync)
  104. PIPE_OPERATOR(AANoRecurse)
  105. PIPE_OPERATOR(AAWillReturn)
  106. PIPE_OPERATOR(AANoReturn)
  107. PIPE_OPERATOR(AAReturnedValues)
  108. PIPE_OPERATOR(AANonNull)
  109. PIPE_OPERATOR(AANoAlias)
  110. PIPE_OPERATOR(AADereferenceable)
  111. PIPE_OPERATOR(AAAlign)
  112. PIPE_OPERATOR(AANoCapture)
  113. PIPE_OPERATOR(AAValueSimplify)
  114. PIPE_OPERATOR(AANoFree)
  115. PIPE_OPERATOR(AAHeapToStack)
  116. PIPE_OPERATOR(AAReachability)
  117. PIPE_OPERATOR(AAMemoryBehavior)
  118. PIPE_OPERATOR(AAMemoryLocation)
  119. PIPE_OPERATOR(AAValueConstantRange)
  120. PIPE_OPERATOR(AAPrivatizablePtr)
  121. PIPE_OPERATOR(AAUndefinedBehavior)
  122. PIPE_OPERATOR(AAPotentialValues)
  123. PIPE_OPERATOR(AANoUndef)
  124. #undef PIPE_OPERATOR
  125. } // namespace llvm
  126. namespace {
  127. static Optional<ConstantInt *>
  128. getAssumedConstantInt(Attributor &A, const Value &V,
  129. const AbstractAttribute &AA,
  130. bool &UsedAssumedInformation) {
  131. Optional<Constant *> C = A.getAssumedConstant(V, AA, UsedAssumedInformation);
  132. if (C.hasValue())
  133. return dyn_cast_or_null<ConstantInt>(C.getValue());
  134. return llvm::None;
  135. }
  136. /// Get pointer operand of memory accessing instruction. If \p I is
  137. /// not a memory accessing instruction, return nullptr. If \p AllowVolatile,
  138. /// is set to false and the instruction is volatile, return nullptr.
  139. static const Value *getPointerOperand(const Instruction *I,
  140. bool AllowVolatile) {
  141. if (auto *LI = dyn_cast<LoadInst>(I)) {
  142. if (!AllowVolatile && LI->isVolatile())
  143. return nullptr;
  144. return LI->getPointerOperand();
  145. }
  146. if (auto *SI = dyn_cast<StoreInst>(I)) {
  147. if (!AllowVolatile && SI->isVolatile())
  148. return nullptr;
  149. return SI->getPointerOperand();
  150. }
  151. if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(I)) {
  152. if (!AllowVolatile && CXI->isVolatile())
  153. return nullptr;
  154. return CXI->getPointerOperand();
  155. }
  156. if (auto *RMWI = dyn_cast<AtomicRMWInst>(I)) {
  157. if (!AllowVolatile && RMWI->isVolatile())
  158. return nullptr;
  159. return RMWI->getPointerOperand();
  160. }
  161. return nullptr;
  162. }
  163. /// Helper function to create a pointer of type \p ResTy, based on \p Ptr, and
  164. /// advanced by \p Offset bytes. To aid later analysis the method tries to build
  165. /// getelement pointer instructions that traverse the natural type of \p Ptr if
  166. /// possible. If that fails, the remaining offset is adjusted byte-wise, hence
  167. /// through a cast to i8*.
  168. ///
  169. /// TODO: This could probably live somewhere more prominantly if it doesn't
  170. /// already exist.
  171. static Value *constructPointer(Type *ResTy, Value *Ptr, int64_t Offset,
  172. IRBuilder<NoFolder> &IRB, const DataLayout &DL) {
  173. assert(Offset >= 0 && "Negative offset not supported yet!");
  174. LLVM_DEBUG(dbgs() << "Construct pointer: " << *Ptr << " + " << Offset
  175. << "-bytes as " << *ResTy << "\n");
  176. // The initial type we are trying to traverse to get nice GEPs.
  177. Type *Ty = Ptr->getType();
  178. SmallVector<Value *, 4> Indices;
  179. std::string GEPName = Ptr->getName().str();
  180. while (Offset) {
  181. uint64_t Idx, Rem;
  182. if (auto *STy = dyn_cast<StructType>(Ty)) {
  183. const StructLayout *SL = DL.getStructLayout(STy);
  184. if (int64_t(SL->getSizeInBytes()) < Offset)
  185. break;
  186. Idx = SL->getElementContainingOffset(Offset);
  187. assert(Idx < STy->getNumElements() && "Offset calculation error!");
  188. Rem = Offset - SL->getElementOffset(Idx);
  189. Ty = STy->getElementType(Idx);
  190. } else if (auto *PTy = dyn_cast<PointerType>(Ty)) {
  191. Ty = PTy->getElementType();
  192. if (!Ty->isSized())
  193. break;
  194. uint64_t ElementSize = DL.getTypeAllocSize(Ty);
  195. assert(ElementSize && "Expected type with size!");
  196. Idx = Offset / ElementSize;
  197. Rem = Offset % ElementSize;
  198. } else {
  199. // Non-aggregate type, we cast and make byte-wise progress now.
  200. break;
  201. }
  202. LLVM_DEBUG(errs() << "Ty: " << *Ty << " Offset: " << Offset
  203. << " Idx: " << Idx << " Rem: " << Rem << "\n");
  204. GEPName += "." + std::to_string(Idx);
  205. Indices.push_back(ConstantInt::get(IRB.getInt32Ty(), Idx));
  206. Offset = Rem;
  207. }
  208. // Create a GEP if we collected indices above.
  209. if (Indices.size())
  210. Ptr = IRB.CreateGEP(Ptr, Indices, GEPName);
  211. // If an offset is left we use byte-wise adjustment.
  212. if (Offset) {
  213. Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy());
  214. Ptr = IRB.CreateGEP(Ptr, IRB.getInt32(Offset),
  215. GEPName + ".b" + Twine(Offset));
  216. }
  217. // Ensure the result has the requested type.
  218. Ptr = IRB.CreateBitOrPointerCast(Ptr, ResTy, Ptr->getName() + ".cast");
  219. LLVM_DEBUG(dbgs() << "Constructed pointer: " << *Ptr << "\n");
  220. return Ptr;
  221. }
  222. /// Recursively visit all values that might become \p IRP at some point. This
  223. /// will be done by looking through cast instructions, selects, phis, and calls
  224. /// with the "returned" attribute. Once we cannot look through the value any
  225. /// further, the callback \p VisitValueCB is invoked and passed the current
  226. /// value, the \p State, and a flag to indicate if we stripped anything.
  227. /// Stripped means that we unpacked the value associated with \p IRP at least
  228. /// once. Note that the value used for the callback may still be the value
  229. /// associated with \p IRP (due to PHIs). To limit how much effort is invested,
  230. /// we will never visit more values than specified by \p MaxValues.
  231. template <typename AAType, typename StateTy>
  232. static bool genericValueTraversal(
  233. Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State,
  234. function_ref<bool(Value &, const Instruction *, StateTy &, bool)>
  235. VisitValueCB,
  236. const Instruction *CtxI, bool UseValueSimplify = true, int MaxValues = 16,
  237. function_ref<Value *(Value *)> StripCB = nullptr) {
  238. const AAIsDead *LivenessAA = nullptr;
  239. if (IRP.getAnchorScope())
  240. LivenessAA = &A.getAAFor<AAIsDead>(
  241. QueryingAA, IRPosition::function(*IRP.getAnchorScope()),
  242. /* TrackDependence */ false);
  243. bool AnyDead = false;
  244. using Item = std::pair<Value *, const Instruction *>;
  245. SmallSet<Item, 16> Visited;
  246. SmallVector<Item, 16> Worklist;
  247. Worklist.push_back({&IRP.getAssociatedValue(), CtxI});
  248. int Iteration = 0;
  249. do {
  250. Item I = Worklist.pop_back_val();
  251. Value *V = I.first;
  252. CtxI = I.second;
  253. if (StripCB)
  254. V = StripCB(V);
  255. // Check if we should process the current value. To prevent endless
  256. // recursion keep a record of the values we followed!
  257. if (!Visited.insert(I).second)
  258. continue;
  259. // Make sure we limit the compile time for complex expressions.
  260. if (Iteration++ >= MaxValues)
  261. return false;
  262. // Explicitly look through calls with a "returned" attribute if we do
  263. // not have a pointer as stripPointerCasts only works on them.
  264. Value *NewV = nullptr;
  265. if (V->getType()->isPointerTy()) {
  266. NewV = V->stripPointerCasts();
  267. } else {
  268. auto *CB = dyn_cast<CallBase>(V);
  269. if (CB && CB->getCalledFunction()) {
  270. for (Argument &Arg : CB->getCalledFunction()->args())
  271. if (Arg.hasReturnedAttr()) {
  272. NewV = CB->getArgOperand(Arg.getArgNo());
  273. break;
  274. }
  275. }
  276. }
  277. if (NewV && NewV != V) {
  278. Worklist.push_back({NewV, CtxI});
  279. continue;
  280. }
  281. // Look through select instructions, visit both potential values.
  282. if (auto *SI = dyn_cast<SelectInst>(V)) {
  283. Worklist.push_back({SI->getTrueValue(), CtxI});
  284. Worklist.push_back({SI->getFalseValue(), CtxI});
  285. continue;
  286. }
  287. // Look through phi nodes, visit all live operands.
  288. if (auto *PHI = dyn_cast<PHINode>(V)) {
  289. assert(LivenessAA &&
  290. "Expected liveness in the presence of instructions!");
  291. for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
  292. BasicBlock *IncomingBB = PHI->getIncomingBlock(u);
  293. if (A.isAssumedDead(*IncomingBB->getTerminator(), &QueryingAA,
  294. LivenessAA,
  295. /* CheckBBLivenessOnly */ true)) {
  296. AnyDead = true;
  297. continue;
  298. }
  299. Worklist.push_back(
  300. {PHI->getIncomingValue(u), IncomingBB->getTerminator()});
  301. }
  302. continue;
  303. }
  304. if (UseValueSimplify && !isa<Constant>(V)) {
  305. bool UsedAssumedInformation = false;
  306. Optional<Constant *> C =
  307. A.getAssumedConstant(*V, QueryingAA, UsedAssumedInformation);
  308. if (!C.hasValue())
  309. continue;
  310. if (Value *NewV = C.getValue()) {
  311. Worklist.push_back({NewV, CtxI});
  312. continue;
  313. }
  314. }
  315. // Once a leaf is reached we inform the user through the callback.
  316. if (!VisitValueCB(*V, CtxI, State, Iteration > 1))
  317. return false;
  318. } while (!Worklist.empty());
  319. // If we actually used liveness information so we have to record a dependence.
  320. if (AnyDead)
  321. A.recordDependence(*LivenessAA, QueryingAA, DepClassTy::OPTIONAL);
  322. // All values have been visited.
  323. return true;
  324. }
  325. const Value *stripAndAccumulateMinimalOffsets(
  326. Attributor &A, const AbstractAttribute &QueryingAA, const Value *Val,
  327. const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
  328. bool UseAssumed = false) {
  329. auto AttributorAnalysis = [&](Value &V, APInt &ROffset) -> bool {
  330. const IRPosition &Pos = IRPosition::value(V);
  331. // Only track dependence if we are going to use the assumed info.
  332. const AAValueConstantRange &ValueConstantRangeAA =
  333. A.getAAFor<AAValueConstantRange>(QueryingAA, Pos,
  334. /* TrackDependence */ UseAssumed);
  335. ConstantRange Range = UseAssumed ? ValueConstantRangeAA.getAssumed()
  336. : ValueConstantRangeAA.getKnown();
  337. // We can only use the lower part of the range because the upper part can
  338. // be higher than what the value can really be.
  339. ROffset = Range.getSignedMin();
  340. return true;
  341. };
  342. return Val->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds,
  343. AttributorAnalysis);
  344. }
  345. static const Value *getMinimalBaseOfAccsesPointerOperand(
  346. Attributor &A, const AbstractAttribute &QueryingAA, const Instruction *I,
  347. int64_t &BytesOffset, const DataLayout &DL, bool AllowNonInbounds = false) {
  348. const Value *Ptr = getPointerOperand(I, /* AllowVolatile */ false);
  349. if (!Ptr)
  350. return nullptr;
  351. APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
  352. const Value *Base = stripAndAccumulateMinimalOffsets(
  353. A, QueryingAA, Ptr, DL, OffsetAPInt, AllowNonInbounds);
  354. BytesOffset = OffsetAPInt.getSExtValue();
  355. return Base;
  356. }
  357. static const Value *
  358. getBasePointerOfAccessPointerOperand(const Instruction *I, int64_t &BytesOffset,
  359. const DataLayout &DL,
  360. bool AllowNonInbounds = false) {
  361. const Value *Ptr = getPointerOperand(I, /* AllowVolatile */ false);
  362. if (!Ptr)
  363. return nullptr;
  364. return GetPointerBaseWithConstantOffset(Ptr, BytesOffset, DL,
  365. AllowNonInbounds);
  366. }
  367. /// Helper function to clamp a state \p S of type \p StateType with the
  368. /// information in \p R and indicate/return if \p S did change (as-in update is
  369. /// required to be run again).
  370. template <typename StateType>
  371. ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R) {
  372. auto Assumed = S.getAssumed();
  373. S ^= R;
  374. return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
  375. : ChangeStatus::CHANGED;
  376. }
  377. /// Clamp the information known for all returned values of a function
  378. /// (identified by \p QueryingAA) into \p S.
  379. template <typename AAType, typename StateType = typename AAType::StateType>
  380. static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA,
  381. StateType &S) {
  382. LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for "
  383. << QueryingAA << " into " << S << "\n");
  384. assert((QueryingAA.getIRPosition().getPositionKind() ==
  385. IRPosition::IRP_RETURNED ||
  386. QueryingAA.getIRPosition().getPositionKind() ==
  387. IRPosition::IRP_CALL_SITE_RETURNED) &&
  388. "Can only clamp returned value states for a function returned or call "
  389. "site returned position!");
  390. // Use an optional state as there might not be any return values and we want
  391. // to join (IntegerState::operator&) the state of all there are.
  392. Optional<StateType> T;
  393. // Callback for each possibly returned value.
  394. auto CheckReturnValue = [&](Value &RV) -> bool {
  395. const IRPosition &RVPos = IRPosition::value(RV);
  396. const AAType &AA = A.getAAFor<AAType>(QueryingAA, RVPos);
  397. LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr()
  398. << " @ " << RVPos << "\n");
  399. const StateType &AAS = AA.getState();
  400. if (T.hasValue())
  401. *T &= AAS;
  402. else
  403. T = AAS;
  404. LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T
  405. << "\n");
  406. return T->isValidState();
  407. };
  408. if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA))
  409. S.indicatePessimisticFixpoint();
  410. else if (T.hasValue())
  411. S ^= *T;
  412. }
  413. /// Helper class for generic deduction: return value -> returned position.
  414. template <typename AAType, typename BaseType,
  415. typename StateType = typename BaseType::StateType>
  416. struct AAReturnedFromReturnedValues : public BaseType {
  417. AAReturnedFromReturnedValues(const IRPosition &IRP, Attributor &A)
  418. : BaseType(IRP, A) {}
  419. /// See AbstractAttribute::updateImpl(...).
  420. ChangeStatus updateImpl(Attributor &A) override {
  421. StateType S(StateType::getBestState(this->getState()));
  422. clampReturnedValueStates<AAType, StateType>(A, *this, S);
  423. // TODO: If we know we visited all returned values, thus no are assumed
  424. // dead, we can take the known information from the state T.
  425. return clampStateAndIndicateChange<StateType>(this->getState(), S);
  426. }
  427. };
  428. /// Clamp the information known at all call sites for a given argument
  429. /// (identified by \p QueryingAA) into \p S.
  430. template <typename AAType, typename StateType = typename AAType::StateType>
  431. static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA,
  432. StateType &S) {
  433. LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for "
  434. << QueryingAA << " into " << S << "\n");
  435. assert(QueryingAA.getIRPosition().getPositionKind() ==
  436. IRPosition::IRP_ARGUMENT &&
  437. "Can only clamp call site argument states for an argument position!");
  438. // Use an optional state as there might not be any return values and we want
  439. // to join (IntegerState::operator&) the state of all there are.
  440. Optional<StateType> T;
  441. // The argument number which is also the call site argument number.
  442. unsigned ArgNo = QueryingAA.getIRPosition().getCallSiteArgNo();
  443. auto CallSiteCheck = [&](AbstractCallSite ACS) {
  444. const IRPosition &ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
  445. // Check if a coresponding argument was found or if it is on not associated
  446. // (which can happen for callback calls).
  447. if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
  448. return false;
  449. const AAType &AA = A.getAAFor<AAType>(QueryingAA, ACSArgPos);
  450. LLVM_DEBUG(dbgs() << "[Attributor] ACS: " << *ACS.getInstruction()
  451. << " AA: " << AA.getAsStr() << " @" << ACSArgPos << "\n");
  452. const StateType &AAS = AA.getState();
  453. if (T.hasValue())
  454. *T &= AAS;
  455. else
  456. T = AAS;
  457. LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T
  458. << "\n");
  459. return T->isValidState();
  460. };
  461. bool AllCallSitesKnown;
  462. if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true,
  463. AllCallSitesKnown))
  464. S.indicatePessimisticFixpoint();
  465. else if (T.hasValue())
  466. S ^= *T;
  467. }
  468. /// Helper class for generic deduction: call site argument -> argument position.
  469. template <typename AAType, typename BaseType,
  470. typename StateType = typename AAType::StateType>
  471. struct AAArgumentFromCallSiteArguments : public BaseType {
  472. AAArgumentFromCallSiteArguments(const IRPosition &IRP, Attributor &A)
  473. : BaseType(IRP, A) {}
  474. /// See AbstractAttribute::updateImpl(...).
  475. ChangeStatus updateImpl(Attributor &A) override {
  476. StateType S(StateType::getBestState(this->getState()));
  477. clampCallSiteArgumentStates<AAType, StateType>(A, *this, S);
  478. // TODO: If we know we visited all incoming values, thus no are assumed
  479. // dead, we can take the known information from the state T.
  480. return clampStateAndIndicateChange<StateType>(this->getState(), S);
  481. }
  482. };
  483. /// Helper class for generic replication: function returned -> cs returned.
  484. template <typename AAType, typename BaseType,
  485. typename StateType = typename BaseType::StateType>
  486. struct AACallSiteReturnedFromReturned : public BaseType {
  487. AACallSiteReturnedFromReturned(const IRPosition &IRP, Attributor &A)
  488. : BaseType(IRP, A) {}
  489. /// See AbstractAttribute::updateImpl(...).
  490. ChangeStatus updateImpl(Attributor &A) override {
  491. assert(this->getIRPosition().getPositionKind() ==
  492. IRPosition::IRP_CALL_SITE_RETURNED &&
  493. "Can only wrap function returned positions for call site returned "
  494. "positions!");
  495. auto &S = this->getState();
  496. const Function *AssociatedFunction =
  497. this->getIRPosition().getAssociatedFunction();
  498. if (!AssociatedFunction)
  499. return S.indicatePessimisticFixpoint();
  500. IRPosition FnPos = IRPosition::returned(*AssociatedFunction);
  501. const AAType &AA = A.getAAFor<AAType>(*this, FnPos);
  502. return clampStateAndIndicateChange(S, AA.getState());
  503. }
  504. };
  505. /// Helper function to accumulate uses.
  506. template <class AAType, typename StateType = typename AAType::StateType>
  507. static void followUsesInContext(AAType &AA, Attributor &A,
  508. MustBeExecutedContextExplorer &Explorer,
  509. const Instruction *CtxI,
  510. SetVector<const Use *> &Uses,
  511. StateType &State) {
  512. auto EIt = Explorer.begin(CtxI), EEnd = Explorer.end(CtxI);
  513. for (unsigned u = 0; u < Uses.size(); ++u) {
  514. const Use *U = Uses[u];
  515. if (const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) {
  516. bool Found = Explorer.findInContextOf(UserI, EIt, EEnd);
  517. if (Found && AA.followUseInMBEC(A, U, UserI, State))
  518. for (const Use &Us : UserI->uses())
  519. Uses.insert(&Us);
  520. }
  521. }
  522. }
  523. /// Use the must-be-executed-context around \p I to add information into \p S.
  524. /// The AAType class is required to have `followUseInMBEC` method with the
  525. /// following signature and behaviour:
  526. ///
  527. /// bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I)
  528. /// U - Underlying use.
  529. /// I - The user of the \p U.
  530. /// Returns true if the value should be tracked transitively.
  531. ///
  532. template <class AAType, typename StateType = typename AAType::StateType>
  533. static void followUsesInMBEC(AAType &AA, Attributor &A, StateType &S,
  534. Instruction &CtxI) {
  535. // Container for (transitive) uses of the associated value.
  536. SetVector<const Use *> Uses;
  537. for (const Use &U : AA.getIRPosition().getAssociatedValue().uses())
  538. Uses.insert(&U);
  539. MustBeExecutedContextExplorer &Explorer =
  540. A.getInfoCache().getMustBeExecutedContextExplorer();
  541. followUsesInContext<AAType>(AA, A, Explorer, &CtxI, Uses, S);
  542. if (S.isAtFixpoint())
  543. return;
  544. SmallVector<const BranchInst *, 4> BrInsts;
  545. auto Pred = [&](const Instruction *I) {
  546. if (const BranchInst *Br = dyn_cast<BranchInst>(I))
  547. if (Br->isConditional())
  548. BrInsts.push_back(Br);
  549. return true;
  550. };
  551. // Here, accumulate conditional branch instructions in the context. We
  552. // explore the child paths and collect the known states. The disjunction of
  553. // those states can be merged to its own state. Let ParentState_i be a state
  554. // to indicate the known information for an i-th branch instruction in the
  555. // context. ChildStates are created for its successors respectively.
  556. //
  557. // ParentS_1 = ChildS_{1, 1} /\ ChildS_{1, 2} /\ ... /\ ChildS_{1, n_1}
  558. // ParentS_2 = ChildS_{2, 1} /\ ChildS_{2, 2} /\ ... /\ ChildS_{2, n_2}
  559. // ...
  560. // ParentS_m = ChildS_{m, 1} /\ ChildS_{m, 2} /\ ... /\ ChildS_{m, n_m}
  561. //
  562. // Known State |= ParentS_1 \/ ParentS_2 \/... \/ ParentS_m
  563. //
  564. // FIXME: Currently, recursive branches are not handled. For example, we
  565. // can't deduce that ptr must be dereferenced in below function.
  566. //
  567. // void f(int a, int c, int *ptr) {
  568. // if(a)
  569. // if (b) {
  570. // *ptr = 0;
  571. // } else {
  572. // *ptr = 1;
  573. // }
  574. // else {
  575. // if (b) {
  576. // *ptr = 0;
  577. // } else {
  578. // *ptr = 1;
  579. // }
  580. // }
  581. // }
  582. Explorer.checkForAllContext(&CtxI, Pred);
  583. for (const BranchInst *Br : BrInsts) {
  584. StateType ParentState;
  585. // The known state of the parent state is a conjunction of children's
  586. // known states so it is initialized with a best state.
  587. ParentState.indicateOptimisticFixpoint();
  588. for (const BasicBlock *BB : Br->successors()) {
  589. StateType ChildState;
  590. size_t BeforeSize = Uses.size();
  591. followUsesInContext(AA, A, Explorer, &BB->front(), Uses, ChildState);
  592. // Erase uses which only appear in the child.
  593. for (auto It = Uses.begin() + BeforeSize; It != Uses.end();)
  594. It = Uses.erase(It);
  595. ParentState &= ChildState;
  596. }
  597. // Use only known state.
  598. S += ParentState;
  599. }
  600. }
  601. /// -----------------------NoUnwind Function Attribute--------------------------
  602. struct AANoUnwindImpl : AANoUnwind {
  603. AANoUnwindImpl(const IRPosition &IRP, Attributor &A) : AANoUnwind(IRP, A) {}
  604. const std::string getAsStr() const override {
  605. return getAssumed() ? "nounwind" : "may-unwind";
  606. }
  607. /// See AbstractAttribute::updateImpl(...).
  608. ChangeStatus updateImpl(Attributor &A) override {
  609. auto Opcodes = {
  610. (unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
  611. (unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet,
  612. (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
  613. auto CheckForNoUnwind = [&](Instruction &I) {
  614. if (!I.mayThrow())
  615. return true;
  616. if (const auto *CB = dyn_cast<CallBase>(&I)) {
  617. const auto &NoUnwindAA =
  618. A.getAAFor<AANoUnwind>(*this, IRPosition::callsite_function(*CB));
  619. return NoUnwindAA.isAssumedNoUnwind();
  620. }
  621. return false;
  622. };
  623. if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes))
  624. return indicatePessimisticFixpoint();
  625. return ChangeStatus::UNCHANGED;
  626. }
  627. };
  628. struct AANoUnwindFunction final : public AANoUnwindImpl {
  629. AANoUnwindFunction(const IRPosition &IRP, Attributor &A)
  630. : AANoUnwindImpl(IRP, A) {}
  631. /// See AbstractAttribute::trackStatistics()
  632. void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) }
  633. };
  634. /// NoUnwind attribute deduction for a call sites.
  635. struct AANoUnwindCallSite final : AANoUnwindImpl {
  636. AANoUnwindCallSite(const IRPosition &IRP, Attributor &A)
  637. : AANoUnwindImpl(IRP, A) {}
  638. /// See AbstractAttribute::initialize(...).
  639. void initialize(Attributor &A) override {
  640. AANoUnwindImpl::initialize(A);
  641. Function *F = getAssociatedFunction();
  642. if (!F || F->isDeclaration())
  643. indicatePessimisticFixpoint();
  644. }
  645. /// See AbstractAttribute::updateImpl(...).
  646. ChangeStatus updateImpl(Attributor &A) override {
  647. // TODO: Once we have call site specific value information we can provide
  648. // call site specific liveness information and then it makes
  649. // sense to specialize attributes for call sites arguments instead of
  650. // redirecting requests to the callee argument.
  651. Function *F = getAssociatedFunction();
  652. const IRPosition &FnPos = IRPosition::function(*F);
  653. auto &FnAA = A.getAAFor<AANoUnwind>(*this, FnPos);
  654. return clampStateAndIndicateChange(getState(), FnAA.getState());
  655. }
  656. /// See AbstractAttribute::trackStatistics()
  657. void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); }
  658. };
  659. /// --------------------- Function Return Values -------------------------------
  660. /// "Attribute" that collects all potential returned values and the return
  661. /// instructions that they arise from.
  662. ///
  663. /// If there is a unique returned value R, the manifest method will:
  664. /// - mark R with the "returned" attribute, if R is an argument.
  665. class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState {
  666. /// Mapping of values potentially returned by the associated function to the
  667. /// return instructions that might return them.
  668. MapVector<Value *, SmallSetVector<ReturnInst *, 4>> ReturnedValues;
  669. /// Mapping to remember the number of returned values for a call site such
  670. /// that we can avoid updates if nothing changed.
  671. DenseMap<const CallBase *, unsigned> NumReturnedValuesPerKnownAA;
  672. /// Set of unresolved calls returned by the associated function.
  673. SmallSetVector<CallBase *, 4> UnresolvedCalls;
  674. /// State flags
  675. ///
  676. ///{
  677. bool IsFixed = false;
  678. bool IsValidState = true;
  679. ///}
  680. public:
  681. AAReturnedValuesImpl(const IRPosition &IRP, Attributor &A)
  682. : AAReturnedValues(IRP, A) {}
  683. /// See AbstractAttribute::initialize(...).
  684. void initialize(Attributor &A) override {
  685. // Reset the state.
  686. IsFixed = false;
  687. IsValidState = true;
  688. ReturnedValues.clear();
  689. Function *F = getAssociatedFunction();
  690. if (!F || F->isDeclaration()) {
  691. indicatePessimisticFixpoint();
  692. return;
  693. }
  694. assert(!F->getReturnType()->isVoidTy() &&
  695. "Did not expect a void return type!");
  696. // The map from instruction opcodes to those instructions in the function.
  697. auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F);
  698. // Look through all arguments, if one is marked as returned we are done.
  699. for (Argument &Arg : F->args()) {
  700. if (Arg.hasReturnedAttr()) {
  701. auto &ReturnInstSet = ReturnedValues[&Arg];
  702. if (auto *Insts = OpcodeInstMap.lookup(Instruction::Ret))
  703. for (Instruction *RI : *Insts)
  704. ReturnInstSet.insert(cast<ReturnInst>(RI));
  705. indicateOptimisticFixpoint();
  706. return;
  707. }
  708. }
  709. if (!A.isFunctionIPOAmendable(*F))
  710. indicatePessimisticFixpoint();
  711. }
  712. /// See AbstractAttribute::manifest(...).
  713. ChangeStatus manifest(Attributor &A) override;
  714. /// See AbstractAttribute::getState(...).
  715. AbstractState &getState() override { return *this; }
  716. /// See AbstractAttribute::getState(...).
  717. const AbstractState &getState() const override { return *this; }
  718. /// See AbstractAttribute::updateImpl(Attributor &A).
  719. ChangeStatus updateImpl(Attributor &A) override;
  720. llvm::iterator_range<iterator> returned_values() override {
  721. return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
  722. }
  723. llvm::iterator_range<const_iterator> returned_values() const override {
  724. return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
  725. }
  726. const SmallSetVector<CallBase *, 4> &getUnresolvedCalls() const override {
  727. return UnresolvedCalls;
  728. }
  729. /// Return the number of potential return values, -1 if unknown.
  730. size_t getNumReturnValues() const override {
  731. return isValidState() ? ReturnedValues.size() : -1;
  732. }
  733. /// Return an assumed unique return value if a single candidate is found. If
  734. /// there cannot be one, return a nullptr. If it is not clear yet, return the
  735. /// Optional::NoneType.
  736. Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const;
  737. /// See AbstractState::checkForAllReturnedValues(...).
  738. bool checkForAllReturnedValuesAndReturnInsts(
  739. function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
  740. const override;
  741. /// Pretty print the attribute similar to the IR representation.
  742. const std::string getAsStr() const override;
  743. /// See AbstractState::isAtFixpoint().
  744. bool isAtFixpoint() const override { return IsFixed; }
  745. /// See AbstractState::isValidState().
  746. bool isValidState() const override { return IsValidState; }
  747. /// See AbstractState::indicateOptimisticFixpoint(...).
  748. ChangeStatus indicateOptimisticFixpoint() override {
  749. IsFixed = true;
  750. return ChangeStatus::UNCHANGED;
  751. }
  752. ChangeStatus indicatePessimisticFixpoint() override {
  753. IsFixed = true;
  754. IsValidState = false;
  755. return ChangeStatus::CHANGED;
  756. }
  757. };
  758. ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
  759. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  760. // Bookkeeping.
  761. assert(isValidState());
  762. STATS_DECLTRACK(KnownReturnValues, FunctionReturn,
  763. "Number of function with known return values");
  764. // Check if we have an assumed unique return value that we could manifest.
  765. Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A);
  766. if (!UniqueRV.hasValue() || !UniqueRV.getValue())
  767. return Changed;
  768. // Bookkeeping.
  769. STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
  770. "Number of function with unique return");
  771. // Callback to replace the uses of CB with the constant C.
  772. auto ReplaceCallSiteUsersWith = [&A](CallBase &CB, Constant &C) {
  773. if (CB.use_empty())
  774. return ChangeStatus::UNCHANGED;
  775. if (A.changeValueAfterManifest(CB, C))
  776. return ChangeStatus::CHANGED;
  777. return ChangeStatus::UNCHANGED;
  778. };
  779. // If the assumed unique return value is an argument, annotate it.
  780. if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) {
  781. if (UniqueRVArg->getType()->canLosslesslyBitCastTo(
  782. getAssociatedFunction()->getReturnType())) {
  783. getIRPosition() = IRPosition::argument(*UniqueRVArg);
  784. Changed = IRAttribute::manifest(A);
  785. }
  786. } else if (auto *RVC = dyn_cast<Constant>(UniqueRV.getValue())) {
  787. // We can replace the returned value with the unique returned constant.
  788. Value &AnchorValue = getAnchorValue();
  789. if (Function *F = dyn_cast<Function>(&AnchorValue)) {
  790. for (const Use &U : F->uses())
  791. if (CallBase *CB = dyn_cast<CallBase>(U.getUser()))
  792. if (CB->isCallee(&U)) {
  793. Constant *RVCCast =
  794. CB->getType() == RVC->getType()
  795. ? RVC
  796. : ConstantExpr::getTruncOrBitCast(RVC, CB->getType());
  797. Changed = ReplaceCallSiteUsersWith(*CB, *RVCCast) | Changed;
  798. }
  799. } else {
  800. assert(isa<CallBase>(AnchorValue) &&
  801. "Expcected a function or call base anchor!");
  802. Constant *RVCCast =
  803. AnchorValue.getType() == RVC->getType()
  804. ? RVC
  805. : ConstantExpr::getTruncOrBitCast(RVC, AnchorValue.getType());
  806. Changed = ReplaceCallSiteUsersWith(cast<CallBase>(AnchorValue), *RVCCast);
  807. }
  808. if (Changed == ChangeStatus::CHANGED)
  809. STATS_DECLTRACK(UniqueConstantReturnValue, FunctionReturn,
  810. "Number of function returns replaced by constant return");
  811. }
  812. return Changed;
  813. }
  814. const std::string AAReturnedValuesImpl::getAsStr() const {
  815. return (isAtFixpoint() ? "returns(#" : "may-return(#") +
  816. (isValidState() ? std::to_string(getNumReturnValues()) : "?") +
  817. ")[#UC: " + std::to_string(UnresolvedCalls.size()) + "]";
  818. }
  819. Optional<Value *>
  820. AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const {
  821. // If checkForAllReturnedValues provides a unique value, ignoring potential
  822. // undef values that can also be present, it is assumed to be the actual
  823. // return value and forwarded to the caller of this method. If there are
  824. // multiple, a nullptr is returned indicating there cannot be a unique
  825. // returned value.
  826. Optional<Value *> UniqueRV;
  827. auto Pred = [&](Value &RV) -> bool {
  828. // If we found a second returned value and neither the current nor the saved
  829. // one is an undef, there is no unique returned value. Undefs are special
  830. // since we can pretend they have any value.
  831. if (UniqueRV.hasValue() && UniqueRV != &RV &&
  832. !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) {
  833. UniqueRV = nullptr;
  834. return false;
  835. }
  836. // Do not overwrite a value with an undef.
  837. if (!UniqueRV.hasValue() || !isa<UndefValue>(RV))
  838. UniqueRV = &RV;
  839. return true;
  840. };
  841. if (!A.checkForAllReturnedValues(Pred, *this))
  842. UniqueRV = nullptr;
  843. return UniqueRV;
  844. }
  845. bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts(
  846. function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
  847. const {
  848. if (!isValidState())
  849. return false;
  850. // Check all returned values but ignore call sites as long as we have not
  851. // encountered an overdefined one during an update.
  852. for (auto &It : ReturnedValues) {
  853. Value *RV = It.first;
  854. CallBase *CB = dyn_cast<CallBase>(RV);
  855. if (CB && !UnresolvedCalls.count(CB))
  856. continue;
  857. if (!Pred(*RV, It.second))
  858. return false;
  859. }
  860. return true;
  861. }
  862. ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) {
  863. size_t NumUnresolvedCalls = UnresolvedCalls.size();
  864. bool Changed = false;
  865. // State used in the value traversals starting in returned values.
  866. struct RVState {
  867. // The map in which we collect return values -> return instrs.
  868. decltype(ReturnedValues) &RetValsMap;
  869. // The flag to indicate a change.
  870. bool &Changed;
  871. // The return instrs we come from.
  872. SmallSetVector<ReturnInst *, 4> RetInsts;
  873. };
  874. // Callback for a leaf value returned by the associated function.
  875. auto VisitValueCB = [](Value &Val, const Instruction *, RVState &RVS,
  876. bool) -> bool {
  877. auto Size = RVS.RetValsMap[&Val].size();
  878. RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end());
  879. bool Inserted = RVS.RetValsMap[&Val].size() != Size;
  880. RVS.Changed |= Inserted;
  881. LLVM_DEBUG({
  882. if (Inserted)
  883. dbgs() << "[AAReturnedValues] 1 Add new returned value " << Val
  884. << " => " << RVS.RetInsts.size() << "\n";
  885. });
  886. return true;
  887. };
  888. // Helper method to invoke the generic value traversal.
  889. auto VisitReturnedValue = [&](Value &RV, RVState &RVS,
  890. const Instruction *CtxI) {
  891. IRPosition RetValPos = IRPosition::value(RV);
  892. return genericValueTraversal<AAReturnedValues, RVState>(
  893. A, RetValPos, *this, RVS, VisitValueCB, CtxI,
  894. /* UseValueSimplify */ false);
  895. };
  896. // Callback for all "return intructions" live in the associated function.
  897. auto CheckReturnInst = [this, &VisitReturnedValue, &Changed](Instruction &I) {
  898. ReturnInst &Ret = cast<ReturnInst>(I);
  899. RVState RVS({ReturnedValues, Changed, {}});
  900. RVS.RetInsts.insert(&Ret);
  901. return VisitReturnedValue(*Ret.getReturnValue(), RVS, &I);
  902. };
  903. // Start by discovering returned values from all live returned instructions in
  904. // the associated function.
  905. if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret}))
  906. return indicatePessimisticFixpoint();
  907. // Once returned values "directly" present in the code are handled we try to
  908. // resolve returned calls. To avoid modifications to the ReturnedValues map
  909. // while we iterate over it we kept record of potential new entries in a copy
  910. // map, NewRVsMap.
  911. decltype(ReturnedValues) NewRVsMap;
  912. auto HandleReturnValue = [&](Value *RV,
  913. SmallSetVector<ReturnInst *, 4> &RIs) {
  914. LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned value: " << *RV << " by #"
  915. << RIs.size() << " RIs\n");
  916. CallBase *CB = dyn_cast<CallBase>(RV);
  917. if (!CB || UnresolvedCalls.count(CB))
  918. return;
  919. if (!CB->getCalledFunction()) {
  920. LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB
  921. << "\n");
  922. UnresolvedCalls.insert(CB);
  923. return;
  924. }
  925. // TODO: use the function scope once we have call site AAReturnedValues.
  926. const auto &RetValAA = A.getAAFor<AAReturnedValues>(
  927. *this, IRPosition::function(*CB->getCalledFunction()));
  928. LLVM_DEBUG(dbgs() << "[AAReturnedValues] Found another AAReturnedValues: "
  929. << RetValAA << "\n");
  930. // Skip dead ends, thus if we do not know anything about the returned
  931. // call we mark it as unresolved and it will stay that way.
  932. if (!RetValAA.getState().isValidState()) {
  933. LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB
  934. << "\n");
  935. UnresolvedCalls.insert(CB);
  936. return;
  937. }
  938. // Do not try to learn partial information. If the callee has unresolved
  939. // return values we will treat the call as unresolved/opaque.
  940. auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls();
  941. if (!RetValAAUnresolvedCalls.empty()) {
  942. UnresolvedCalls.insert(CB);
  943. return;
  944. }
  945. // Now check if we can track transitively returned values. If possible, thus
  946. // if all return value can be represented in the current scope, do so.
  947. bool Unresolved = false;
  948. for (auto &RetValAAIt : RetValAA.returned_values()) {
  949. Value *RetVal = RetValAAIt.first;
  950. if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) ||
  951. isa<Constant>(RetVal))
  952. continue;
  953. // Anything that did not fit in the above categories cannot be resolved,
  954. // mark the call as unresolved.
  955. LLVM_DEBUG(dbgs() << "[AAReturnedValues] transitively returned value "
  956. "cannot be translated: "
  957. << *RetVal << "\n");
  958. UnresolvedCalls.insert(CB);
  959. Unresolved = true;
  960. break;
  961. }
  962. if (Unresolved)
  963. return;
  964. // Now track transitively returned values.
  965. unsigned &NumRetAA = NumReturnedValuesPerKnownAA[CB];
  966. if (NumRetAA == RetValAA.getNumReturnValues()) {
  967. LLVM_DEBUG(dbgs() << "[AAReturnedValues] Skip call as it has not "
  968. "changed since it was seen last\n");
  969. return;
  970. }
  971. NumRetAA = RetValAA.getNumReturnValues();
  972. for (auto &RetValAAIt : RetValAA.returned_values()) {
  973. Value *RetVal = RetValAAIt.first;
  974. if (Argument *Arg = dyn_cast<Argument>(RetVal)) {
  975. // Arguments are mapped to call site operands and we begin the traversal
  976. // again.
  977. bool Unused = false;
  978. RVState RVS({NewRVsMap, Unused, RetValAAIt.second});
  979. VisitReturnedValue(*CB->getArgOperand(Arg->getArgNo()), RVS, CB);
  980. continue;
  981. }
  982. if (isa<CallBase>(RetVal)) {
  983. // Call sites are resolved by the callee attribute over time, no need to
  984. // do anything for us.
  985. continue;
  986. }
  987. if (isa<Constant>(RetVal)) {
  988. // Constants are valid everywhere, we can simply take them.
  989. NewRVsMap[RetVal].insert(RIs.begin(), RIs.end());
  990. continue;
  991. }
  992. }
  993. };
  994. for (auto &It : ReturnedValues)
  995. HandleReturnValue(It.first, It.second);
  996. // Because processing the new information can again lead to new return values
  997. // we have to be careful and iterate until this iteration is complete. The
  998. // idea is that we are in a stable state at the end of an update. All return
  999. // values have been handled and properly categorized. We might not update
  1000. // again if we have not requested a non-fix attribute so we cannot "wait" for
  1001. // the next update to analyze a new return value.
  1002. while (!NewRVsMap.empty()) {
  1003. auto It = std::move(NewRVsMap.back());
  1004. NewRVsMap.pop_back();
  1005. assert(!It.second.empty() && "Entry does not add anything.");
  1006. auto &ReturnInsts = ReturnedValues[It.first];
  1007. for (ReturnInst *RI : It.second)
  1008. if (ReturnInsts.insert(RI)) {
  1009. LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value "
  1010. << *It.first << " => " << *RI << "\n");
  1011. HandleReturnValue(It.first, ReturnInsts);
  1012. Changed = true;
  1013. }
  1014. }
  1015. Changed |= (NumUnresolvedCalls != UnresolvedCalls.size());
  1016. return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
  1017. }
  1018. struct AAReturnedValuesFunction final : public AAReturnedValuesImpl {
  1019. AAReturnedValuesFunction(const IRPosition &IRP, Attributor &A)
  1020. : AAReturnedValuesImpl(IRP, A) {}
  1021. /// See AbstractAttribute::trackStatistics()
  1022. void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) }
  1023. };
  1024. /// Returned values information for a call sites.
  1025. struct AAReturnedValuesCallSite final : AAReturnedValuesImpl {
  1026. AAReturnedValuesCallSite(const IRPosition &IRP, Attributor &A)
  1027. : AAReturnedValuesImpl(IRP, A) {}
  1028. /// See AbstractAttribute::initialize(...).
  1029. void initialize(Attributor &A) override {
  1030. // TODO: Once we have call site specific value information we can provide
  1031. // call site specific liveness information and then it makes
  1032. // sense to specialize attributes for call sites instead of
  1033. // redirecting requests to the callee.
  1034. llvm_unreachable("Abstract attributes for returned values are not "
  1035. "supported for call sites yet!");
  1036. }
  1037. /// See AbstractAttribute::updateImpl(...).
  1038. ChangeStatus updateImpl(Attributor &A) override {
  1039. return indicatePessimisticFixpoint();
  1040. }
  1041. /// See AbstractAttribute::trackStatistics()
  1042. void trackStatistics() const override {}
  1043. };
  1044. /// ------------------------ NoSync Function Attribute -------------------------
  1045. struct AANoSyncImpl : AANoSync {
  1046. AANoSyncImpl(const IRPosition &IRP, Attributor &A) : AANoSync(IRP, A) {}
  1047. const std::string getAsStr() const override {
  1048. return getAssumed() ? "nosync" : "may-sync";
  1049. }
  1050. /// See AbstractAttribute::updateImpl(...).
  1051. ChangeStatus updateImpl(Attributor &A) override;
  1052. /// Helper function used to determine whether an instruction is non-relaxed
  1053. /// atomic. In other words, if an atomic instruction does not have unordered
  1054. /// or monotonic ordering
  1055. static bool isNonRelaxedAtomic(Instruction *I);
  1056. /// Helper function used to determine whether an instruction is volatile.
  1057. static bool isVolatile(Instruction *I);
  1058. /// Helper function uset to check if intrinsic is volatile (memcpy, memmove,
  1059. /// memset).
  1060. static bool isNoSyncIntrinsic(Instruction *I);
  1061. };
  1062. bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) {
  1063. if (!I->isAtomic())
  1064. return false;
  1065. AtomicOrdering Ordering;
  1066. switch (I->getOpcode()) {
  1067. case Instruction::AtomicRMW:
  1068. Ordering = cast<AtomicRMWInst>(I)->getOrdering();
  1069. break;
  1070. case Instruction::Store:
  1071. Ordering = cast<StoreInst>(I)->getOrdering();
  1072. break;
  1073. case Instruction::Load:
  1074. Ordering = cast<LoadInst>(I)->getOrdering();
  1075. break;
  1076. case Instruction::Fence: {
  1077. auto *FI = cast<FenceInst>(I);
  1078. if (FI->getSyncScopeID() == SyncScope::SingleThread)
  1079. return false;
  1080. Ordering = FI->getOrdering();
  1081. break;
  1082. }
  1083. case Instruction::AtomicCmpXchg: {
  1084. AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering();
  1085. AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering();
  1086. // Only if both are relaxed, than it can be treated as relaxed.
  1087. // Otherwise it is non-relaxed.
  1088. if (Success != AtomicOrdering::Unordered &&
  1089. Success != AtomicOrdering::Monotonic)
  1090. return true;
  1091. if (Failure != AtomicOrdering::Unordered &&
  1092. Failure != AtomicOrdering::Monotonic)
  1093. return true;
  1094. return false;
  1095. }
  1096. default:
  1097. llvm_unreachable(
  1098. "New atomic operations need to be known in the attributor.");
  1099. }
  1100. // Relaxed.
  1101. if (Ordering == AtomicOrdering::Unordered ||
  1102. Ordering == AtomicOrdering::Monotonic)
  1103. return false;
  1104. return true;
  1105. }
  1106. /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics.
  1107. /// FIXME: We should ipmrove the handling of intrinsics.
  1108. bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) {
  1109. if (auto *II = dyn_cast<IntrinsicInst>(I)) {
  1110. switch (II->getIntrinsicID()) {
  1111. /// Element wise atomic memory intrinsics are can only be unordered,
  1112. /// therefore nosync.
  1113. case Intrinsic::memset_element_unordered_atomic:
  1114. case Intrinsic::memmove_element_unordered_atomic:
  1115. case Intrinsic::memcpy_element_unordered_atomic:
  1116. return true;
  1117. case Intrinsic::memset:
  1118. case Intrinsic::memmove:
  1119. case Intrinsic::memcpy:
  1120. if (!cast<MemIntrinsic>(II)->isVolatile())
  1121. return true;
  1122. return false;
  1123. default:
  1124. return false;
  1125. }
  1126. }
  1127. return false;
  1128. }
  1129. bool AANoSyncImpl::isVolatile(Instruction *I) {
  1130. assert(!isa<CallBase>(I) && "Calls should not be checked here");
  1131. switch (I->getOpcode()) {
  1132. case Instruction::AtomicRMW:
  1133. return cast<AtomicRMWInst>(I)->isVolatile();
  1134. case Instruction::Store:
  1135. return cast<StoreInst>(I)->isVolatile();
  1136. case Instruction::Load:
  1137. return cast<LoadInst>(I)->isVolatile();
  1138. case Instruction::AtomicCmpXchg:
  1139. return cast<AtomicCmpXchgInst>(I)->isVolatile();
  1140. default:
  1141. return false;
  1142. }
  1143. }
  1144. ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) {
  1145. auto CheckRWInstForNoSync = [&](Instruction &I) {
  1146. /// We are looking for volatile instructions or Non-Relaxed atomics.
  1147. /// FIXME: We should improve the handling of intrinsics.
  1148. if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I))
  1149. return true;
  1150. if (const auto *CB = dyn_cast<CallBase>(&I)) {
  1151. if (CB->hasFnAttr(Attribute::NoSync))
  1152. return true;
  1153. const auto &NoSyncAA =
  1154. A.getAAFor<AANoSync>(*this, IRPosition::callsite_function(*CB));
  1155. if (NoSyncAA.isAssumedNoSync())
  1156. return true;
  1157. return false;
  1158. }
  1159. if (!isVolatile(&I) && !isNonRelaxedAtomic(&I))
  1160. return true;
  1161. return false;
  1162. };
  1163. auto CheckForNoSync = [&](Instruction &I) {
  1164. // At this point we handled all read/write effects and they are all
  1165. // nosync, so they can be skipped.
  1166. if (I.mayReadOrWriteMemory())
  1167. return true;
  1168. // non-convergent and readnone imply nosync.
  1169. return !cast<CallBase>(I).isConvergent();
  1170. };
  1171. if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this) ||
  1172. !A.checkForAllCallLikeInstructions(CheckForNoSync, *this))
  1173. return indicatePessimisticFixpoint();
  1174. return ChangeStatus::UNCHANGED;
  1175. }
  1176. struct AANoSyncFunction final : public AANoSyncImpl {
  1177. AANoSyncFunction(const IRPosition &IRP, Attributor &A)
  1178. : AANoSyncImpl(IRP, A) {}
  1179. /// See AbstractAttribute::trackStatistics()
  1180. void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) }
  1181. };
  1182. /// NoSync attribute deduction for a call sites.
  1183. struct AANoSyncCallSite final : AANoSyncImpl {
  1184. AANoSyncCallSite(const IRPosition &IRP, Attributor &A)
  1185. : AANoSyncImpl(IRP, A) {}
  1186. /// See AbstractAttribute::initialize(...).
  1187. void initialize(Attributor &A) override {
  1188. AANoSyncImpl::initialize(A);
  1189. Function *F = getAssociatedFunction();
  1190. if (!F || F->isDeclaration())
  1191. indicatePessimisticFixpoint();
  1192. }
  1193. /// See AbstractAttribute::updateImpl(...).
  1194. ChangeStatus updateImpl(Attributor &A) override {
  1195. // TODO: Once we have call site specific value information we can provide
  1196. // call site specific liveness information and then it makes
  1197. // sense to specialize attributes for call sites arguments instead of
  1198. // redirecting requests to the callee argument.
  1199. Function *F = getAssociatedFunction();
  1200. const IRPosition &FnPos = IRPosition::function(*F);
  1201. auto &FnAA = A.getAAFor<AANoSync>(*this, FnPos);
  1202. return clampStateAndIndicateChange(getState(), FnAA.getState());
  1203. }
  1204. /// See AbstractAttribute::trackStatistics()
  1205. void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); }
  1206. };
  1207. /// ------------------------ No-Free Attributes ----------------------------
  1208. struct AANoFreeImpl : public AANoFree {
  1209. AANoFreeImpl(const IRPosition &IRP, Attributor &A) : AANoFree(IRP, A) {}
  1210. /// See AbstractAttribute::updateImpl(...).
  1211. ChangeStatus updateImpl(Attributor &A) override {
  1212. auto CheckForNoFree = [&](Instruction &I) {
  1213. const auto &CB = cast<CallBase>(I);
  1214. if (CB.hasFnAttr(Attribute::NoFree))
  1215. return true;
  1216. const auto &NoFreeAA =
  1217. A.getAAFor<AANoFree>(*this, IRPosition::callsite_function(CB));
  1218. return NoFreeAA.isAssumedNoFree();
  1219. };
  1220. if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this))
  1221. return indicatePessimisticFixpoint();
  1222. return ChangeStatus::UNCHANGED;
  1223. }
  1224. /// See AbstractAttribute::getAsStr().
  1225. const std::string getAsStr() const override {
  1226. return getAssumed() ? "nofree" : "may-free";
  1227. }
  1228. };
  1229. struct AANoFreeFunction final : public AANoFreeImpl {
  1230. AANoFreeFunction(const IRPosition &IRP, Attributor &A)
  1231. : AANoFreeImpl(IRP, A) {}
  1232. /// See AbstractAttribute::trackStatistics()
  1233. void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) }
  1234. };
  1235. /// NoFree attribute deduction for a call sites.
  1236. struct AANoFreeCallSite final : AANoFreeImpl {
  1237. AANoFreeCallSite(const IRPosition &IRP, Attributor &A)
  1238. : AANoFreeImpl(IRP, A) {}
  1239. /// See AbstractAttribute::initialize(...).
  1240. void initialize(Attributor &A) override {
  1241. AANoFreeImpl::initialize(A);
  1242. Function *F = getAssociatedFunction();
  1243. if (!F || F->isDeclaration())
  1244. indicatePessimisticFixpoint();
  1245. }
  1246. /// See AbstractAttribute::updateImpl(...).
  1247. ChangeStatus updateImpl(Attributor &A) override {
  1248. // TODO: Once we have call site specific value information we can provide
  1249. // call site specific liveness information and then it makes
  1250. // sense to specialize attributes for call sites arguments instead of
  1251. // redirecting requests to the callee argument.
  1252. Function *F = getAssociatedFunction();
  1253. const IRPosition &FnPos = IRPosition::function(*F);
  1254. auto &FnAA = A.getAAFor<AANoFree>(*this, FnPos);
  1255. return clampStateAndIndicateChange(getState(), FnAA.getState());
  1256. }
  1257. /// See AbstractAttribute::trackStatistics()
  1258. void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); }
  1259. };
  1260. /// NoFree attribute for floating values.
  1261. struct AANoFreeFloating : AANoFreeImpl {
  1262. AANoFreeFloating(const IRPosition &IRP, Attributor &A)
  1263. : AANoFreeImpl(IRP, A) {}
  1264. /// See AbstractAttribute::trackStatistics()
  1265. void trackStatistics() const override{STATS_DECLTRACK_FLOATING_ATTR(nofree)}
  1266. /// See Abstract Attribute::updateImpl(...).
  1267. ChangeStatus updateImpl(Attributor &A) override {
  1268. const IRPosition &IRP = getIRPosition();
  1269. const auto &NoFreeAA =
  1270. A.getAAFor<AANoFree>(*this, IRPosition::function_scope(IRP));
  1271. if (NoFreeAA.isAssumedNoFree())
  1272. return ChangeStatus::UNCHANGED;
  1273. Value &AssociatedValue = getIRPosition().getAssociatedValue();
  1274. auto Pred = [&](const Use &U, bool &Follow) -> bool {
  1275. Instruction *UserI = cast<Instruction>(U.getUser());
  1276. if (auto *CB = dyn_cast<CallBase>(UserI)) {
  1277. if (CB->isBundleOperand(&U))
  1278. return false;
  1279. if (!CB->isArgOperand(&U))
  1280. return true;
  1281. unsigned ArgNo = CB->getArgOperandNo(&U);
  1282. const auto &NoFreeArg = A.getAAFor<AANoFree>(
  1283. *this, IRPosition::callsite_argument(*CB, ArgNo));
  1284. return NoFreeArg.isAssumedNoFree();
  1285. }
  1286. if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
  1287. isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
  1288. Follow = true;
  1289. return true;
  1290. }
  1291. if (isa<ReturnInst>(UserI))
  1292. return true;
  1293. // Unknown user.
  1294. return false;
  1295. };
  1296. if (!A.checkForAllUses(Pred, *this, AssociatedValue))
  1297. return indicatePessimisticFixpoint();
  1298. return ChangeStatus::UNCHANGED;
  1299. }
  1300. };
  1301. /// NoFree attribute for a call site argument.
  1302. struct AANoFreeArgument final : AANoFreeFloating {
  1303. AANoFreeArgument(const IRPosition &IRP, Attributor &A)
  1304. : AANoFreeFloating(IRP, A) {}
  1305. /// See AbstractAttribute::trackStatistics()
  1306. void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofree) }
  1307. };
  1308. /// NoFree attribute for call site arguments.
  1309. struct AANoFreeCallSiteArgument final : AANoFreeFloating {
  1310. AANoFreeCallSiteArgument(const IRPosition &IRP, Attributor &A)
  1311. : AANoFreeFloating(IRP, A) {}
  1312. /// See AbstractAttribute::updateImpl(...).
  1313. ChangeStatus updateImpl(Attributor &A) override {
  1314. // TODO: Once we have call site specific value information we can provide
  1315. // call site specific liveness information and then it makes
  1316. // sense to specialize attributes for call sites arguments instead of
  1317. // redirecting requests to the callee argument.
  1318. Argument *Arg = getAssociatedArgument();
  1319. if (!Arg)
  1320. return indicatePessimisticFixpoint();
  1321. const IRPosition &ArgPos = IRPosition::argument(*Arg);
  1322. auto &ArgAA = A.getAAFor<AANoFree>(*this, ArgPos);
  1323. return clampStateAndIndicateChange(getState(), ArgAA.getState());
  1324. }
  1325. /// See AbstractAttribute::trackStatistics()
  1326. void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nofree)};
  1327. };
  1328. /// NoFree attribute for function return value.
  1329. struct AANoFreeReturned final : AANoFreeFloating {
  1330. AANoFreeReturned(const IRPosition &IRP, Attributor &A)
  1331. : AANoFreeFloating(IRP, A) {
  1332. llvm_unreachable("NoFree is not applicable to function returns!");
  1333. }
  1334. /// See AbstractAttribute::initialize(...).
  1335. void initialize(Attributor &A) override {
  1336. llvm_unreachable("NoFree is not applicable to function returns!");
  1337. }
  1338. /// See AbstractAttribute::updateImpl(...).
  1339. ChangeStatus updateImpl(Attributor &A) override {
  1340. llvm_unreachable("NoFree is not applicable to function returns!");
  1341. }
  1342. /// See AbstractAttribute::trackStatistics()
  1343. void trackStatistics() const override {}
  1344. };
  1345. /// NoFree attribute deduction for a call site return value.
  1346. struct AANoFreeCallSiteReturned final : AANoFreeFloating {
  1347. AANoFreeCallSiteReturned(const IRPosition &IRP, Attributor &A)
  1348. : AANoFreeFloating(IRP, A) {}
  1349. ChangeStatus manifest(Attributor &A) override {
  1350. return ChangeStatus::UNCHANGED;
  1351. }
  1352. /// See AbstractAttribute::trackStatistics()
  1353. void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nofree) }
  1354. };
  1355. /// ------------------------ NonNull Argument Attribute ------------------------
  1356. static int64_t getKnownNonNullAndDerefBytesForUse(
  1357. Attributor &A, const AbstractAttribute &QueryingAA, Value &AssociatedValue,
  1358. const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) {
  1359. TrackUse = false;
  1360. const Value *UseV = U->get();
  1361. if (!UseV->getType()->isPointerTy())
  1362. return 0;
  1363. Type *PtrTy = UseV->getType();
  1364. const Function *F = I->getFunction();
  1365. bool NullPointerIsDefined =
  1366. F ? llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()) : true;
  1367. const DataLayout &DL = A.getInfoCache().getDL();
  1368. if (const auto *CB = dyn_cast<CallBase>(I)) {
  1369. if (CB->isBundleOperand(U)) {
  1370. if (RetainedKnowledge RK = getKnowledgeFromUse(
  1371. U, {Attribute::NonNull, Attribute::Dereferenceable})) {
  1372. IsNonNull |=
  1373. (RK.AttrKind == Attribute::NonNull || !NullPointerIsDefined);
  1374. return RK.ArgValue;
  1375. }
  1376. return 0;
  1377. }
  1378. if (CB->isCallee(U)) {
  1379. IsNonNull |= !NullPointerIsDefined;
  1380. return 0;
  1381. }
  1382. unsigned ArgNo = CB->getArgOperandNo(U);
  1383. IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
  1384. // As long as we only use known information there is no need to track
  1385. // dependences here.
  1386. auto &DerefAA = A.getAAFor<AADereferenceable>(QueryingAA, IRP,
  1387. /* TrackDependence */ false);
  1388. IsNonNull |= DerefAA.isKnownNonNull();
  1389. return DerefAA.getKnownDereferenceableBytes();
  1390. }
  1391. // We need to follow common pointer manipulation uses to the accesses they
  1392. // feed into. We can try to be smart to avoid looking through things we do not
  1393. // like for now, e.g., non-inbounds GEPs.
  1394. if (isa<CastInst>(I)) {
  1395. TrackUse = true;
  1396. return 0;
  1397. }
  1398. if (isa<GetElementPtrInst>(I)) {
  1399. TrackUse = true;
  1400. return 0;
  1401. }
  1402. int64_t Offset;
  1403. const Value *Base =
  1404. getMinimalBaseOfAccsesPointerOperand(A, QueryingAA, I, Offset, DL);
  1405. if (Base) {
  1406. if (Base == &AssociatedValue &&
  1407. getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
  1408. int64_t DerefBytes =
  1409. (int64_t)DL.getTypeStoreSize(PtrTy->getPointerElementType()) + Offset;
  1410. IsNonNull |= !NullPointerIsDefined;
  1411. return std::max(int64_t(0), DerefBytes);
  1412. }
  1413. }
  1414. /// Corner case when an offset is 0.
  1415. Base = getBasePointerOfAccessPointerOperand(I, Offset, DL,
  1416. /*AllowNonInbounds*/ true);
  1417. if (Base) {
  1418. if (Offset == 0 && Base == &AssociatedValue &&
  1419. getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
  1420. int64_t DerefBytes =
  1421. (int64_t)DL.getTypeStoreSize(PtrTy->getPointerElementType());
  1422. IsNonNull |= !NullPointerIsDefined;
  1423. return std::max(int64_t(0), DerefBytes);
  1424. }
  1425. }
  1426. return 0;
  1427. }
  1428. struct AANonNullImpl : AANonNull {
  1429. AANonNullImpl(const IRPosition &IRP, Attributor &A)
  1430. : AANonNull(IRP, A),
  1431. NullIsDefined(NullPointerIsDefined(
  1432. getAnchorScope(),
  1433. getAssociatedValue().getType()->getPointerAddressSpace())) {}
  1434. /// See AbstractAttribute::initialize(...).
  1435. void initialize(Attributor &A) override {
  1436. Value &V = getAssociatedValue();
  1437. if (!NullIsDefined &&
  1438. hasAttr({Attribute::NonNull, Attribute::Dereferenceable},
  1439. /* IgnoreSubsumingPositions */ false, &A)) {
  1440. indicateOptimisticFixpoint();
  1441. return;
  1442. }
  1443. if (isa<ConstantPointerNull>(V)) {
  1444. indicatePessimisticFixpoint();
  1445. return;
  1446. }
  1447. AANonNull::initialize(A);
  1448. bool CanBeNull = true;
  1449. if (V.getPointerDereferenceableBytes(A.getDataLayout(), CanBeNull)) {
  1450. if (!CanBeNull) {
  1451. indicateOptimisticFixpoint();
  1452. return;
  1453. }
  1454. }
  1455. if (isa<GlobalValue>(&getAssociatedValue())) {
  1456. indicatePessimisticFixpoint();
  1457. return;
  1458. }
  1459. if (Instruction *CtxI = getCtxI())
  1460. followUsesInMBEC(*this, A, getState(), *CtxI);
  1461. }
  1462. /// See followUsesInMBEC
  1463. bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
  1464. AANonNull::StateType &State) {
  1465. bool IsNonNull = false;
  1466. bool TrackUse = false;
  1467. getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I,
  1468. IsNonNull, TrackUse);
  1469. State.setKnown(IsNonNull);
  1470. return TrackUse;
  1471. }
  1472. /// See AbstractAttribute::getAsStr().
  1473. const std::string getAsStr() const override {
  1474. return getAssumed() ? "nonnull" : "may-null";
  1475. }
  1476. /// Flag to determine if the underlying value can be null and still allow
  1477. /// valid accesses.
  1478. const bool NullIsDefined;
  1479. };
  1480. /// NonNull attribute for a floating value.
  1481. struct AANonNullFloating : public AANonNullImpl {
  1482. AANonNullFloating(const IRPosition &IRP, Attributor &A)
  1483. : AANonNullImpl(IRP, A) {}
  1484. /// See AbstractAttribute::updateImpl(...).
  1485. ChangeStatus updateImpl(Attributor &A) override {
  1486. const DataLayout &DL = A.getDataLayout();
  1487. DominatorTree *DT = nullptr;
  1488. AssumptionCache *AC = nullptr;
  1489. InformationCache &InfoCache = A.getInfoCache();
  1490. if (const Function *Fn = getAnchorScope()) {
  1491. DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*Fn);
  1492. AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*Fn);
  1493. }
  1494. auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
  1495. AANonNull::StateType &T, bool Stripped) -> bool {
  1496. const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V));
  1497. if (!Stripped && this == &AA) {
  1498. if (!isKnownNonZero(&V, DL, 0, AC, CtxI, DT))
  1499. T.indicatePessimisticFixpoint();
  1500. } else {
  1501. // Use abstract attribute information.
  1502. const AANonNull::StateType &NS = AA.getState();
  1503. T ^= NS;
  1504. }
  1505. return T.isValidState();
  1506. };
  1507. StateType T;
  1508. if (!genericValueTraversal<AANonNull, StateType>(
  1509. A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
  1510. return indicatePessimisticFixpoint();
  1511. return clampStateAndIndicateChange(getState(), T);
  1512. }
  1513. /// See AbstractAttribute::trackStatistics()
  1514. void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
  1515. };
  1516. /// NonNull attribute for function return value.
  1517. struct AANonNullReturned final
  1518. : AAReturnedFromReturnedValues<AANonNull, AANonNull> {
  1519. AANonNullReturned(const IRPosition &IRP, Attributor &A)
  1520. : AAReturnedFromReturnedValues<AANonNull, AANonNull>(IRP, A) {}
  1521. /// See AbstractAttribute::getAsStr().
  1522. const std::string getAsStr() const override {
  1523. return getAssumed() ? "nonnull" : "may-null";
  1524. }
  1525. /// See AbstractAttribute::trackStatistics()
  1526. void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
  1527. };
  1528. /// NonNull attribute for function argument.
  1529. struct AANonNullArgument final
  1530. : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> {
  1531. AANonNullArgument(const IRPosition &IRP, Attributor &A)
  1532. : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP, A) {}
  1533. /// See AbstractAttribute::trackStatistics()
  1534. void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) }
  1535. };
  1536. struct AANonNullCallSiteArgument final : AANonNullFloating {
  1537. AANonNullCallSiteArgument(const IRPosition &IRP, Attributor &A)
  1538. : AANonNullFloating(IRP, A) {}
  1539. /// See AbstractAttribute::trackStatistics()
  1540. void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) }
  1541. };
  1542. /// NonNull attribute for a call site return position.
  1543. struct AANonNullCallSiteReturned final
  1544. : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl> {
  1545. AANonNullCallSiteReturned(const IRPosition &IRP, Attributor &A)
  1546. : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl>(IRP, A) {}
  1547. /// See AbstractAttribute::trackStatistics()
  1548. void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) }
  1549. };
  1550. /// ------------------------ No-Recurse Attributes ----------------------------
  1551. struct AANoRecurseImpl : public AANoRecurse {
  1552. AANoRecurseImpl(const IRPosition &IRP, Attributor &A) : AANoRecurse(IRP, A) {}
  1553. /// See AbstractAttribute::getAsStr()
  1554. const std::string getAsStr() const override {
  1555. return getAssumed() ? "norecurse" : "may-recurse";
  1556. }
  1557. };
  1558. struct AANoRecurseFunction final : AANoRecurseImpl {
  1559. AANoRecurseFunction(const IRPosition &IRP, Attributor &A)
  1560. : AANoRecurseImpl(IRP, A) {}
  1561. /// See AbstractAttribute::initialize(...).
  1562. void initialize(Attributor &A) override {
  1563. AANoRecurseImpl::initialize(A);
  1564. if (const Function *F = getAnchorScope())
  1565. if (A.getInfoCache().getSccSize(*F) != 1)
  1566. indicatePessimisticFixpoint();
  1567. }
  1568. /// See AbstractAttribute::updateImpl(...).
  1569. ChangeStatus updateImpl(Attributor &A) override {
  1570. // If all live call sites are known to be no-recurse, we are as well.
  1571. auto CallSitePred = [&](AbstractCallSite ACS) {
  1572. const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
  1573. *this, IRPosition::function(*ACS.getInstruction()->getFunction()),
  1574. /* TrackDependence */ false, DepClassTy::OPTIONAL);
  1575. return NoRecurseAA.isKnownNoRecurse();
  1576. };
  1577. bool AllCallSitesKnown;
  1578. if (A.checkForAllCallSites(CallSitePred, *this, true, AllCallSitesKnown)) {
  1579. // If we know all call sites and all are known no-recurse, we are done.
  1580. // If all known call sites, which might not be all that exist, are known
  1581. // to be no-recurse, we are not done but we can continue to assume
  1582. // no-recurse. If one of the call sites we have not visited will become
  1583. // live, another update is triggered.
  1584. if (AllCallSitesKnown)
  1585. indicateOptimisticFixpoint();
  1586. return ChangeStatus::UNCHANGED;
  1587. }
  1588. // If the above check does not hold anymore we look at the calls.
  1589. auto CheckForNoRecurse = [&](Instruction &I) {
  1590. const auto &CB = cast<CallBase>(I);
  1591. if (CB.hasFnAttr(Attribute::NoRecurse))
  1592. return true;
  1593. const auto &NoRecurseAA =
  1594. A.getAAFor<AANoRecurse>(*this, IRPosition::callsite_function(CB));
  1595. if (!NoRecurseAA.isAssumedNoRecurse())
  1596. return false;
  1597. // Recursion to the same function
  1598. if (CB.getCalledFunction() == getAnchorScope())
  1599. return false;
  1600. return true;
  1601. };
  1602. if (!A.checkForAllCallLikeInstructions(CheckForNoRecurse, *this))
  1603. return indicatePessimisticFixpoint();
  1604. return ChangeStatus::UNCHANGED;
  1605. }
  1606. void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) }
  1607. };
  1608. /// NoRecurse attribute deduction for a call sites.
  1609. struct AANoRecurseCallSite final : AANoRecurseImpl {
  1610. AANoRecurseCallSite(const IRPosition &IRP, Attributor &A)
  1611. : AANoRecurseImpl(IRP, A) {}
  1612. /// See AbstractAttribute::initialize(...).
  1613. void initialize(Attributor &A) override {
  1614. AANoRecurseImpl::initialize(A);
  1615. Function *F = getAssociatedFunction();
  1616. if (!F || F->isDeclaration())
  1617. indicatePessimisticFixpoint();
  1618. }
  1619. /// See AbstractAttribute::updateImpl(...).
  1620. ChangeStatus updateImpl(Attributor &A) override {
  1621. // TODO: Once we have call site specific value information we can provide
  1622. // call site specific liveness information and then it makes
  1623. // sense to specialize attributes for call sites arguments instead of
  1624. // redirecting requests to the callee argument.
  1625. Function *F = getAssociatedFunction();
  1626. const IRPosition &FnPos = IRPosition::function(*F);
  1627. auto &FnAA = A.getAAFor<AANoRecurse>(*this, FnPos);
  1628. return clampStateAndIndicateChange(getState(), FnAA.getState());
  1629. }
  1630. /// See AbstractAttribute::trackStatistics()
  1631. void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); }
  1632. };
  1633. /// -------------------- Undefined-Behavior Attributes ------------------------
  1634. struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior {
  1635. AAUndefinedBehaviorImpl(const IRPosition &IRP, Attributor &A)
  1636. : AAUndefinedBehavior(IRP, A) {}
  1637. /// See AbstractAttribute::updateImpl(...).
  1638. // through a pointer (i.e. also branches etc.)
  1639. ChangeStatus updateImpl(Attributor &A) override {
  1640. const size_t UBPrevSize = KnownUBInsts.size();
  1641. const size_t NoUBPrevSize = AssumedNoUBInsts.size();
  1642. auto InspectMemAccessInstForUB = [&](Instruction &I) {
  1643. // Skip instructions that are already saved.
  1644. if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
  1645. return true;
  1646. // If we reach here, we know we have an instruction
  1647. // that accesses memory through a pointer operand,
  1648. // for which getPointerOperand() should give it to us.
  1649. const Value *PtrOp = getPointerOperand(&I, /* AllowVolatile */ true);
  1650. assert(PtrOp &&
  1651. "Expected pointer operand of memory accessing instruction");
  1652. // Either we stopped and the appropriate action was taken,
  1653. // or we got back a simplified value to continue.
  1654. Optional<Value *> SimplifiedPtrOp = stopOnUndefOrAssumed(A, PtrOp, &I);
  1655. if (!SimplifiedPtrOp.hasValue())
  1656. return true;
  1657. const Value *PtrOpVal = SimplifiedPtrOp.getValue();
  1658. // A memory access through a pointer is considered UB
  1659. // only if the pointer has constant null value.
  1660. // TODO: Expand it to not only check constant values.
  1661. if (!isa<ConstantPointerNull>(PtrOpVal)) {
  1662. AssumedNoUBInsts.insert(&I);
  1663. return true;
  1664. }
  1665. const Type *PtrTy = PtrOpVal->getType();
  1666. // Because we only consider instructions inside functions,
  1667. // assume that a parent function exists.
  1668. const Function *F = I.getFunction();
  1669. // A memory access using constant null pointer is only considered UB
  1670. // if null pointer is _not_ defined for the target platform.
  1671. if (llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()))
  1672. AssumedNoUBInsts.insert(&I);
  1673. else
  1674. KnownUBInsts.insert(&I);
  1675. return true;
  1676. };
  1677. auto InspectBrInstForUB = [&](Instruction &I) {
  1678. // A conditional branch instruction is considered UB if it has `undef`
  1679. // condition.
  1680. // Skip instructions that are already saved.
  1681. if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
  1682. return true;
  1683. // We know we have a branch instruction.
  1684. auto BrInst = cast<BranchInst>(&I);
  1685. // Unconditional branches are never considered UB.
  1686. if (BrInst->isUnconditional())
  1687. return true;
  1688. // Either we stopped and the appropriate action was taken,
  1689. // or we got back a simplified value to continue.
  1690. Optional<Value *> SimplifiedCond =
  1691. stopOnUndefOrAssumed(A, BrInst->getCondition(), BrInst);
  1692. if (!SimplifiedCond.hasValue())
  1693. return true;
  1694. AssumedNoUBInsts.insert(&I);
  1695. return true;
  1696. };
  1697. auto InspectCallSiteForUB = [&](Instruction &I) {
  1698. // Check whether a callsite always cause UB or not
  1699. // Skip instructions that are already saved.
  1700. if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
  1701. return true;
  1702. // Check nonnull and noundef argument attribute violation for each
  1703. // callsite.
  1704. CallBase &CB = cast<CallBase>(I);
  1705. Function *Callee = CB.getCalledFunction();
  1706. if (!Callee)
  1707. return true;
  1708. for (unsigned idx = 0; idx < CB.getNumArgOperands(); idx++) {
  1709. // If current argument is known to be simplified to null pointer and the
  1710. // corresponding argument position is known to have nonnull attribute,
  1711. // the argument is poison. Furthermore, if the argument is poison and
  1712. // the position is known to have noundef attriubte, this callsite is
  1713. // considered UB.
  1714. if (idx >= Callee->arg_size())
  1715. break;
  1716. Value *ArgVal = CB.getArgOperand(idx);
  1717. if (!ArgVal)
  1718. continue;
  1719. // Here, we handle three cases.
  1720. // (1) Not having a value means it is dead. (we can replace the value
  1721. // with undef)
  1722. // (2) Simplified to undef. The argument violate noundef attriubte.
  1723. // (3) Simplified to null pointer where known to be nonnull.
  1724. // The argument is a poison value and violate noundef attribute.
  1725. IRPosition CalleeArgumentIRP = IRPosition::callsite_argument(CB, idx);
  1726. auto &NoUndefAA = A.getAAFor<AANoUndef>(*this, CalleeArgumentIRP,
  1727. /* TrackDependence */ false);
  1728. if (!NoUndefAA.isKnownNoUndef())
  1729. continue;
  1730. auto &ValueSimplifyAA = A.getAAFor<AAValueSimplify>(
  1731. *this, IRPosition::value(*ArgVal), /* TrackDependence */ false);
  1732. if (!ValueSimplifyAA.isKnown())
  1733. continue;
  1734. Optional<Value *> SimplifiedVal =
  1735. ValueSimplifyAA.getAssumedSimplifiedValue(A);
  1736. if (!SimplifiedVal.hasValue() ||
  1737. isa<UndefValue>(*SimplifiedVal.getValue())) {
  1738. KnownUBInsts.insert(&I);
  1739. continue;
  1740. }
  1741. if (!ArgVal->getType()->isPointerTy() ||
  1742. !isa<ConstantPointerNull>(*SimplifiedVal.getValue()))
  1743. continue;
  1744. auto &NonNullAA = A.getAAFor<AANonNull>(*this, CalleeArgumentIRP,
  1745. /* TrackDependence */ false);
  1746. if (NonNullAA.isKnownNonNull())
  1747. KnownUBInsts.insert(&I);
  1748. }
  1749. return true;
  1750. };
  1751. auto InspectReturnInstForUB =
  1752. [&](Value &V, const SmallSetVector<ReturnInst *, 4> RetInsts) {
  1753. // Check if a return instruction always cause UB or not
  1754. // Note: It is guaranteed that the returned position of the anchor
  1755. // scope has noundef attribute when this is called.
  1756. // We also ensure the return position is not "assumed dead"
  1757. // because the returned value was then potentially simplified to
  1758. // `undef` in AAReturnedValues without removing the `noundef`
  1759. // attribute yet.
  1760. // When the returned position has noundef attriubte, UB occur in the
  1761. // following cases.
  1762. // (1) Returned value is known to be undef.
  1763. // (2) The value is known to be a null pointer and the returned
  1764. // position has nonnull attribute (because the returned value is
  1765. // poison).
  1766. bool FoundUB = false;
  1767. if (isa<UndefValue>(V)) {
  1768. FoundUB = true;
  1769. } else {
  1770. if (isa<ConstantPointerNull>(V)) {
  1771. auto &NonNullAA = A.getAAFor<AANonNull>(
  1772. *this, IRPosition::returned(*getAnchorScope()),
  1773. /* TrackDependence */ false);
  1774. if (NonNullAA.isKnownNonNull())
  1775. FoundUB = true;
  1776. }
  1777. }
  1778. if (FoundUB)
  1779. for (ReturnInst *RI : RetInsts)
  1780. KnownUBInsts.insert(RI);
  1781. return true;
  1782. };
  1783. A.checkForAllInstructions(InspectMemAccessInstForUB, *this,
  1784. {Instruction::Load, Instruction::Store,
  1785. Instruction::AtomicCmpXchg,
  1786. Instruction::AtomicRMW},
  1787. /* CheckBBLivenessOnly */ true);
  1788. A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::Br},
  1789. /* CheckBBLivenessOnly */ true);
  1790. A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *this);
  1791. // If the returned position of the anchor scope has noundef attriubte, check
  1792. // all returned instructions.
  1793. if (!getAnchorScope()->getReturnType()->isVoidTy()) {
  1794. const IRPosition &ReturnIRP = IRPosition::returned(*getAnchorScope());
  1795. if (!A.isAssumedDead(ReturnIRP, this, nullptr)) {
  1796. auto &RetPosNoUndefAA =
  1797. A.getAAFor<AANoUndef>(*this, ReturnIRP,
  1798. /* TrackDependence */ false);
  1799. if (RetPosNoUndefAA.isKnownNoUndef())
  1800. A.checkForAllReturnedValuesAndReturnInsts(InspectReturnInstForUB,
  1801. *this);
  1802. }
  1803. }
  1804. if (NoUBPrevSize != AssumedNoUBInsts.size() ||
  1805. UBPrevSize != KnownUBInsts.size())
  1806. return ChangeStatus::CHANGED;
  1807. return ChangeStatus::UNCHANGED;
  1808. }
  1809. bool isKnownToCauseUB(Instruction *I) const override {
  1810. return KnownUBInsts.count(I);
  1811. }
  1812. bool isAssumedToCauseUB(Instruction *I) const override {
  1813. // In simple words, if an instruction is not in the assumed to _not_
  1814. // cause UB, then it is assumed UB (that includes those
  1815. // in the KnownUBInsts set). The rest is boilerplate
  1816. // is to ensure that it is one of the instructions we test
  1817. // for UB.
  1818. switch (I->getOpcode()) {
  1819. case Instruction::Load:
  1820. case Instruction::Store:
  1821. case Instruction::AtomicCmpXchg:
  1822. case Instruction::AtomicRMW:
  1823. return !AssumedNoUBInsts.count(I);
  1824. case Instruction::Br: {
  1825. auto BrInst = cast<BranchInst>(I);
  1826. if (BrInst->isUnconditional())
  1827. return false;
  1828. return !AssumedNoUBInsts.count(I);
  1829. } break;
  1830. default:
  1831. return false;
  1832. }
  1833. return false;
  1834. }
  1835. ChangeStatus manifest(Attributor &A) override {
  1836. if (KnownUBInsts.empty())
  1837. return ChangeStatus::UNCHANGED;
  1838. for (Instruction *I : KnownUBInsts)
  1839. A.changeToUnreachableAfterManifest(I);
  1840. return ChangeStatus::CHANGED;
  1841. }
  1842. /// See AbstractAttribute::getAsStr()
  1843. const std::string getAsStr() const override {
  1844. return getAssumed() ? "undefined-behavior" : "no-ub";
  1845. }
  1846. /// Note: The correctness of this analysis depends on the fact that the
  1847. /// following 2 sets will stop changing after some point.
  1848. /// "Change" here means that their size changes.
  1849. /// The size of each set is monotonically increasing
  1850. /// (we only add items to them) and it is upper bounded by the number of
  1851. /// instructions in the processed function (we can never save more
  1852. /// elements in either set than this number). Hence, at some point,
  1853. /// they will stop increasing.
  1854. /// Consequently, at some point, both sets will have stopped
  1855. /// changing, effectively making the analysis reach a fixpoint.
  1856. /// Note: These 2 sets are disjoint and an instruction can be considered
  1857. /// one of 3 things:
  1858. /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in
  1859. /// the KnownUBInsts set.
  1860. /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior
  1861. /// has a reason to assume it).
  1862. /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior
  1863. /// could not find a reason to assume or prove that it can cause UB,
  1864. /// hence it assumes it doesn't. We have a set for these instructions
  1865. /// so that we don't reprocess them in every update.
  1866. /// Note however that instructions in this set may cause UB.
  1867. protected:
  1868. /// A set of all live instructions _known_ to cause UB.
  1869. SmallPtrSet<Instruction *, 8> KnownUBInsts;
  1870. private:
  1871. /// A set of all the (live) instructions that are assumed to _not_ cause UB.
  1872. SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
  1873. // Should be called on updates in which if we're processing an instruction
  1874. // \p I that depends on a value \p V, one of the following has to happen:
  1875. // - If the value is assumed, then stop.
  1876. // - If the value is known but undef, then consider it UB.
  1877. // - Otherwise, do specific processing with the simplified value.
  1878. // We return None in the first 2 cases to signify that an appropriate
  1879. // action was taken and the caller should stop.
  1880. // Otherwise, we return the simplified value that the caller should
  1881. // use for specific processing.
  1882. Optional<Value *> stopOnUndefOrAssumed(Attributor &A, const Value *V,
  1883. Instruction *I) {
  1884. const auto &ValueSimplifyAA =
  1885. A.getAAFor<AAValueSimplify>(*this, IRPosition::value(*V));
  1886. Optional<Value *> SimplifiedV =
  1887. ValueSimplifyAA.getAssumedSimplifiedValue(A);
  1888. if (!ValueSimplifyAA.isKnown()) {
  1889. // Don't depend on assumed values.
  1890. return llvm::None;
  1891. }
  1892. if (!SimplifiedV.hasValue()) {
  1893. // If it is known (which we tested above) but it doesn't have a value,
  1894. // then we can assume `undef` and hence the instruction is UB.
  1895. KnownUBInsts.insert(I);
  1896. return llvm::None;
  1897. }
  1898. Value *Val = SimplifiedV.getValue();
  1899. if (isa<UndefValue>(Val)) {
  1900. KnownUBInsts.insert(I);
  1901. return llvm::None;
  1902. }
  1903. return Val;
  1904. }
  1905. };
  1906. struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
  1907. AAUndefinedBehaviorFunction(const IRPosition &IRP, Attributor &A)
  1908. : AAUndefinedBehaviorImpl(IRP, A) {}
  1909. /// See AbstractAttribute::trackStatistics()
  1910. void trackStatistics() const override {
  1911. STATS_DECL(UndefinedBehaviorInstruction, Instruction,
  1912. "Number of instructions known to have UB");
  1913. BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) +=
  1914. KnownUBInsts.size();
  1915. }
  1916. };
  1917. /// ------------------------ Will-Return Attributes ----------------------------
  1918. // Helper function that checks whether a function has any cycle which we don't
  1919. // know if it is bounded or not.
  1920. // Loops with maximum trip count are considered bounded, any other cycle not.
  1921. static bool mayContainUnboundedCycle(Function &F, Attributor &A) {
  1922. ScalarEvolution *SE =
  1923. A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F);
  1924. LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F);
  1925. // If either SCEV or LoopInfo is not available for the function then we assume
  1926. // any cycle to be unbounded cycle.
  1927. // We use scc_iterator which uses Tarjan algorithm to find all the maximal
  1928. // SCCs.To detect if there's a cycle, we only need to find the maximal ones.
  1929. if (!SE || !LI) {
  1930. for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI)
  1931. if (SCCI.hasCycle())
  1932. return true;
  1933. return false;
  1934. }
  1935. // If there's irreducible control, the function may contain non-loop cycles.
  1936. if (mayContainIrreducibleControl(F, LI))
  1937. return true;
  1938. // Any loop that does not have a max trip count is considered unbounded cycle.
  1939. for (auto *L : LI->getLoopsInPreorder()) {
  1940. if (!SE->getSmallConstantMaxTripCount(L))
  1941. return true;
  1942. }
  1943. return false;
  1944. }
  1945. struct AAWillReturnImpl : public AAWillReturn {
  1946. AAWillReturnImpl(const IRPosition &IRP, Attributor &A)
  1947. : AAWillReturn(IRP, A) {}
  1948. /// See AbstractAttribute::initialize(...).
  1949. void initialize(Attributor &A) override {
  1950. AAWillReturn::initialize(A);
  1951. Function *F = getAnchorScope();
  1952. if (!F || F->isDeclaration() || mayContainUnboundedCycle(*F, A))
  1953. indicatePessimisticFixpoint();
  1954. }
  1955. /// See AbstractAttribute::updateImpl(...).
  1956. ChangeStatus updateImpl(Attributor &A) override {
  1957. auto CheckForWillReturn = [&](Instruction &I) {
  1958. IRPosition IPos = IRPosition::callsite_function(cast<CallBase>(I));
  1959. const auto &WillReturnAA = A.getAAFor<AAWillReturn>(*this, IPos);
  1960. if (WillReturnAA.isKnownWillReturn())
  1961. return true;
  1962. if (!WillReturnAA.isAssumedWillReturn())
  1963. return false;
  1964. const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(*this, IPos);
  1965. return NoRecurseAA.isAssumedNoRecurse();
  1966. };
  1967. if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this))
  1968. return indicatePessimisticFixpoint();
  1969. return ChangeStatus::UNCHANGED;
  1970. }
  1971. /// See AbstractAttribute::getAsStr()
  1972. const std::string getAsStr() const override {
  1973. return getAssumed() ? "willreturn" : "may-noreturn";
  1974. }
  1975. };
  1976. struct AAWillReturnFunction final : AAWillReturnImpl {
  1977. AAWillReturnFunction(const IRPosition &IRP, Attributor &A)
  1978. : AAWillReturnImpl(IRP, A) {}
  1979. /// See AbstractAttribute::trackStatistics()
  1980. void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
  1981. };
  1982. /// WillReturn attribute deduction for a call sites.
  1983. struct AAWillReturnCallSite final : AAWillReturnImpl {
  1984. AAWillReturnCallSite(const IRPosition &IRP, Attributor &A)
  1985. : AAWillReturnImpl(IRP, A) {}
  1986. /// See AbstractAttribute::initialize(...).
  1987. void initialize(Attributor &A) override {
  1988. AAWillReturn::initialize(A);
  1989. Function *F = getAssociatedFunction();
  1990. if (!F || !A.isFunctionIPOAmendable(*F))
  1991. indicatePessimisticFixpoint();
  1992. }
  1993. /// See AbstractAttribute::updateImpl(...).
  1994. ChangeStatus updateImpl(Attributor &A) override {
  1995. // TODO: Once we have call site specific value information we can provide
  1996. // call site specific liveness information and then it makes
  1997. // sense to specialize attributes for call sites arguments instead of
  1998. // redirecting requests to the callee argument.
  1999. Function *F = getAssociatedFunction();
  2000. const IRPosition &FnPos = IRPosition::function(*F);
  2001. auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos);
  2002. return clampStateAndIndicateChange(getState(), FnAA.getState());
  2003. }
  2004. /// See AbstractAttribute::trackStatistics()
  2005. void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); }
  2006. };
  2007. /// -------------------AAReachability Attribute--------------------------
  2008. struct AAReachabilityImpl : AAReachability {
  2009. AAReachabilityImpl(const IRPosition &IRP, Attributor &A)
  2010. : AAReachability(IRP, A) {}
  2011. const std::string getAsStr() const override {
  2012. // TODO: Return the number of reachable queries.
  2013. return "reachable";
  2014. }
  2015. /// See AbstractAttribute::initialize(...).
  2016. void initialize(Attributor &A) override { indicatePessimisticFixpoint(); }
  2017. /// See AbstractAttribute::updateImpl(...).
  2018. ChangeStatus updateImpl(Attributor &A) override {
  2019. return indicatePessimisticFixpoint();
  2020. }
  2021. };
  2022. struct AAReachabilityFunction final : public AAReachabilityImpl {
  2023. AAReachabilityFunction(const IRPosition &IRP, Attributor &A)
  2024. : AAReachabilityImpl(IRP, A) {}
  2025. /// See AbstractAttribute::trackStatistics()
  2026. void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(reachable); }
  2027. };
  2028. /// ------------------------ NoAlias Argument Attribute ------------------------
  2029. struct AANoAliasImpl : AANoAlias {
  2030. AANoAliasImpl(const IRPosition &IRP, Attributor &A) : AANoAlias(IRP, A) {
  2031. assert(getAssociatedType()->isPointerTy() &&
  2032. "Noalias is a pointer attribute");
  2033. }
  2034. const std::string getAsStr() const override {
  2035. return getAssumed() ? "noalias" : "may-alias";
  2036. }
  2037. };
  2038. /// NoAlias attribute for a floating value.
  2039. struct AANoAliasFloating final : AANoAliasImpl {
  2040. AANoAliasFloating(const IRPosition &IRP, Attributor &A)
  2041. : AANoAliasImpl(IRP, A) {}
  2042. /// See AbstractAttribute::initialize(...).
  2043. void initialize(Attributor &A) override {
  2044. AANoAliasImpl::initialize(A);
  2045. Value *Val = &getAssociatedValue();
  2046. do {
  2047. CastInst *CI = dyn_cast<CastInst>(Val);
  2048. if (!CI)
  2049. break;
  2050. Value *Base = CI->getOperand(0);
  2051. if (!Base->hasOneUse())
  2052. break;
  2053. Val = Base;
  2054. } while (true);
  2055. if (!Val->getType()->isPointerTy()) {
  2056. indicatePessimisticFixpoint();
  2057. return;
  2058. }
  2059. if (isa<AllocaInst>(Val))
  2060. indicateOptimisticFixpoint();
  2061. else if (isa<ConstantPointerNull>(Val) &&
  2062. !NullPointerIsDefined(getAnchorScope(),
  2063. Val->getType()->getPointerAddressSpace()))
  2064. indicateOptimisticFixpoint();
  2065. else if (Val != &getAssociatedValue()) {
  2066. const auto &ValNoAliasAA =
  2067. A.getAAFor<AANoAlias>(*this, IRPosition::value(*Val));
  2068. if (ValNoAliasAA.isKnownNoAlias())
  2069. indicateOptimisticFixpoint();
  2070. }
  2071. }
  2072. /// See AbstractAttribute::updateImpl(...).
  2073. ChangeStatus updateImpl(Attributor &A) override {
  2074. // TODO: Implement this.
  2075. return indicatePessimisticFixpoint();
  2076. }
  2077. /// See AbstractAttribute::trackStatistics()
  2078. void trackStatistics() const override {
  2079. STATS_DECLTRACK_FLOATING_ATTR(noalias)
  2080. }
  2081. };
  2082. /// NoAlias attribute for an argument.
  2083. struct AANoAliasArgument final
  2084. : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
  2085. using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
  2086. AANoAliasArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
  2087. /// See AbstractAttribute::initialize(...).
  2088. void initialize(Attributor &A) override {
  2089. Base::initialize(A);
  2090. // See callsite argument attribute and callee argument attribute.
  2091. if (hasAttr({Attribute::ByVal}))
  2092. indicateOptimisticFixpoint();
  2093. }
  2094. /// See AbstractAttribute::update(...).
  2095. ChangeStatus updateImpl(Attributor &A) override {
  2096. // We have to make sure no-alias on the argument does not break
  2097. // synchronization when this is a callback argument, see also [1] below.
  2098. // If synchronization cannot be affected, we delegate to the base updateImpl
  2099. // function, otherwise we give up for now.
  2100. // If the function is no-sync, no-alias cannot break synchronization.
  2101. const auto &NoSyncAA = A.getAAFor<AANoSync>(
  2102. *this, IRPosition::function_scope(getIRPosition()));
  2103. if (NoSyncAA.isAssumedNoSync())
  2104. return Base::updateImpl(A);
  2105. // If the argument is read-only, no-alias cannot break synchronization.
  2106. const auto &MemBehaviorAA =
  2107. A.getAAFor<AAMemoryBehavior>(*this, getIRPosition());
  2108. if (MemBehaviorAA.isAssumedReadOnly())
  2109. return Base::updateImpl(A);
  2110. // If the argument is never passed through callbacks, no-alias cannot break
  2111. // synchronization.
  2112. bool AllCallSitesKnown;
  2113. if (A.checkForAllCallSites(
  2114. [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this,
  2115. true, AllCallSitesKnown))
  2116. return Base::updateImpl(A);
  2117. // TODO: add no-alias but make sure it doesn't break synchronization by
  2118. // introducing fake uses. See:
  2119. // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel,
  2120. // International Workshop on OpenMP 2018,
  2121. // http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf
  2122. return indicatePessimisticFixpoint();
  2123. }
  2124. /// See AbstractAttribute::trackStatistics()
  2125. void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
  2126. };
  2127. struct AANoAliasCallSiteArgument final : AANoAliasImpl {
  2128. AANoAliasCallSiteArgument(const IRPosition &IRP, Attributor &A)
  2129. : AANoAliasImpl(IRP, A) {}
  2130. /// See AbstractAttribute::initialize(...).
  2131. void initialize(Attributor &A) override {
  2132. // See callsite argument attribute and callee argument attribute.
  2133. const auto &CB = cast<CallBase>(getAnchorValue());
  2134. if (CB.paramHasAttr(getCallSiteArgNo(), Attribute::NoAlias))
  2135. indicateOptimisticFixpoint();
  2136. Value &Val = getAssociatedValue();
  2137. if (isa<ConstantPointerNull>(Val) &&
  2138. !NullPointerIsDefined(getAnchorScope(),
  2139. Val.getType()->getPointerAddressSpace()))
  2140. indicateOptimisticFixpoint();
  2141. }
  2142. /// Determine if the underlying value may alias with the call site argument
  2143. /// \p OtherArgNo of \p ICS (= the underlying call site).
  2144. bool mayAliasWithArgument(Attributor &A, AAResults *&AAR,
  2145. const AAMemoryBehavior &MemBehaviorAA,
  2146. const CallBase &CB, unsigned OtherArgNo) {
  2147. // We do not need to worry about aliasing with the underlying IRP.
  2148. if (this->getCalleeArgNo() == (int)OtherArgNo)
  2149. return false;
  2150. // If it is not a pointer or pointer vector we do not alias.
  2151. const Value *ArgOp = CB.getArgOperand(OtherArgNo);
  2152. if (!ArgOp->getType()->isPtrOrPtrVectorTy())
  2153. return false;
  2154. auto &CBArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
  2155. *this, IRPosition::callsite_argument(CB, OtherArgNo),
  2156. /* TrackDependence */ false);
  2157. // If the argument is readnone, there is no read-write aliasing.
  2158. if (CBArgMemBehaviorAA.isAssumedReadNone()) {
  2159. A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
  2160. return false;
  2161. }
  2162. // If the argument is readonly and the underlying value is readonly, there
  2163. // is no read-write aliasing.
  2164. bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly();
  2165. if (CBArgMemBehaviorAA.isAssumedReadOnly() && IsReadOnly) {
  2166. A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
  2167. A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
  2168. return false;
  2169. }
  2170. // We have to utilize actual alias analysis queries so we need the object.
  2171. if (!AAR)
  2172. AAR = A.getInfoCache().getAAResultsForFunction(*getAnchorScope());
  2173. // Try to rule it out at the call site.
  2174. bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp);
  2175. LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between "
  2176. "callsite arguments: "
  2177. << getAssociatedValue() << " " << *ArgOp << " => "
  2178. << (IsAliasing ? "" : "no-") << "alias \n");
  2179. return IsAliasing;
  2180. }
  2181. bool
  2182. isKnownNoAliasDueToNoAliasPreservation(Attributor &A, AAResults *&AAR,
  2183. const AAMemoryBehavior &MemBehaviorAA,
  2184. const AANoAlias &NoAliasAA) {
  2185. // We can deduce "noalias" if the following conditions hold.
  2186. // (i) Associated value is assumed to be noalias in the definition.
  2187. // (ii) Associated value is assumed to be no-capture in all the uses
  2188. // possibly executed before this callsite.
  2189. // (iii) There is no other pointer argument which could alias with the
  2190. // value.
  2191. bool AssociatedValueIsNoAliasAtDef = NoAliasAA.isAssumedNoAlias();
  2192. if (!AssociatedValueIsNoAliasAtDef) {
  2193. LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue()
  2194. << " is not no-alias at the definition\n");
  2195. return false;
  2196. }
  2197. A.recordDependence(NoAliasAA, *this, DepClassTy::OPTIONAL);
  2198. const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
  2199. const Function *ScopeFn = VIRP.getAnchorScope();
  2200. auto &NoCaptureAA =
  2201. A.getAAFor<AANoCapture>(*this, VIRP, /* TrackDependence */ false);
  2202. // Check whether the value is captured in the scope using AANoCapture.
  2203. // Look at CFG and check only uses possibly executed before this
  2204. // callsite.
  2205. auto UsePred = [&](const Use &U, bool &Follow) -> bool {
  2206. Instruction *UserI = cast<Instruction>(U.getUser());
  2207. // If UserI is the curr instruction and there is a single potential use of
  2208. // the value in UserI we allow the use.
  2209. // TODO: We should inspect the operands and allow those that cannot alias
  2210. // with the value.
  2211. if (UserI == getCtxI() && UserI->getNumOperands() == 1)
  2212. return true;
  2213. if (ScopeFn) {
  2214. const auto &ReachabilityAA =
  2215. A.getAAFor<AAReachability>(*this, IRPosition::function(*ScopeFn));
  2216. if (!ReachabilityAA.isAssumedReachable(A, *UserI, *getCtxI()))
  2217. return true;
  2218. if (auto *CB = dyn_cast<CallBase>(UserI)) {
  2219. if (CB->isArgOperand(&U)) {
  2220. unsigned ArgNo = CB->getArgOperandNo(&U);
  2221. const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
  2222. *this, IRPosition::callsite_argument(*CB, ArgNo));
  2223. if (NoCaptureAA.isAssumedNoCapture())
  2224. return true;
  2225. }
  2226. }
  2227. }
  2228. // For cases which can potentially have more users
  2229. if (isa<GetElementPtrInst>(U) || isa<BitCastInst>(U) || isa<PHINode>(U) ||
  2230. isa<SelectInst>(U)) {
  2231. Follow = true;
  2232. return true;
  2233. }
  2234. LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *U << "\n");
  2235. return false;
  2236. };
  2237. if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
  2238. if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) {
  2239. LLVM_DEBUG(
  2240. dbgs() << "[AANoAliasCSArg] " << getAssociatedValue()
  2241. << " cannot be noalias as it is potentially captured\n");
  2242. return false;
  2243. }
  2244. }
  2245. A.recordDependence(NoCaptureAA, *this, DepClassTy::OPTIONAL);
  2246. // Check there is no other pointer argument which could alias with the
  2247. // value passed at this call site.
  2248. // TODO: AbstractCallSite
  2249. const auto &CB = cast<CallBase>(getAnchorValue());
  2250. for (unsigned OtherArgNo = 0; OtherArgNo < CB.getNumArgOperands();
  2251. OtherArgNo++)
  2252. if (mayAliasWithArgument(A, AAR, MemBehaviorAA, CB, OtherArgNo))
  2253. return false;
  2254. return true;
  2255. }
  2256. /// See AbstractAttribute::updateImpl(...).
  2257. ChangeStatus updateImpl(Attributor &A) override {
  2258. // If the argument is readnone we are done as there are no accesses via the
  2259. // argument.
  2260. auto &MemBehaviorAA =
  2261. A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(),
  2262. /* TrackDependence */ false);
  2263. if (MemBehaviorAA.isAssumedReadNone()) {
  2264. A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
  2265. return ChangeStatus::UNCHANGED;
  2266. }
  2267. const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
  2268. const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, VIRP,
  2269. /* TrackDependence */ false);
  2270. AAResults *AAR = nullptr;
  2271. if (isKnownNoAliasDueToNoAliasPreservation(A, AAR, MemBehaviorAA,
  2272. NoAliasAA)) {
  2273. LLVM_DEBUG(
  2274. dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n");
  2275. return ChangeStatus::UNCHANGED;
  2276. }
  2277. return indicatePessimisticFixpoint();
  2278. }
  2279. /// See AbstractAttribute::trackStatistics()
  2280. void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) }
  2281. };
  2282. /// NoAlias attribute for function return value.
  2283. struct AANoAliasReturned final : AANoAliasImpl {
  2284. AANoAliasReturned(const IRPosition &IRP, Attributor &A)
  2285. : AANoAliasImpl(IRP, A) {}
  2286. /// See AbstractAttribute::initialize(...).
  2287. void initialize(Attributor &A) override {
  2288. AANoAliasImpl::initialize(A);
  2289. Function *F = getAssociatedFunction();
  2290. if (!F || F->isDeclaration())
  2291. indicatePessimisticFixpoint();
  2292. }
  2293. /// See AbstractAttribute::updateImpl(...).
  2294. virtual ChangeStatus updateImpl(Attributor &A) override {
  2295. auto CheckReturnValue = [&](Value &RV) -> bool {
  2296. if (Constant *C = dyn_cast<Constant>(&RV))
  2297. if (C->isNullValue() || isa<UndefValue>(C))
  2298. return true;
  2299. /// For now, we can only deduce noalias if we have call sites.
  2300. /// FIXME: add more support.
  2301. if (!isa<CallBase>(&RV))
  2302. return false;
  2303. const IRPosition &RVPos = IRPosition::value(RV);
  2304. const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, RVPos);
  2305. if (!NoAliasAA.isAssumedNoAlias())
  2306. return false;
  2307. const auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, RVPos);
  2308. return NoCaptureAA.isAssumedNoCaptureMaybeReturned();
  2309. };
  2310. if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
  2311. return indicatePessimisticFixpoint();
  2312. return ChangeStatus::UNCHANGED;
  2313. }
  2314. /// See AbstractAttribute::trackStatistics()
  2315. void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
  2316. };
  2317. /// NoAlias attribute deduction for a call site return value.
  2318. struct AANoAliasCallSiteReturned final : AANoAliasImpl {
  2319. AANoAliasCallSiteReturned(const IRPosition &IRP, Attributor &A)
  2320. : AANoAliasImpl(IRP, A) {}
  2321. /// See AbstractAttribute::initialize(...).
  2322. void initialize(Attributor &A) override {
  2323. AANoAliasImpl::initialize(A);
  2324. Function *F = getAssociatedFunction();
  2325. if (!F || F->isDeclaration())
  2326. indicatePessimisticFixpoint();
  2327. }
  2328. /// See AbstractAttribute::updateImpl(...).
  2329. ChangeStatus updateImpl(Attributor &A) override {
  2330. // TODO: Once we have call site specific value information we can provide
  2331. // call site specific liveness information and then it makes
  2332. // sense to specialize attributes for call sites arguments instead of
  2333. // redirecting requests to the callee argument.
  2334. Function *F = getAssociatedFunction();
  2335. const IRPosition &FnPos = IRPosition::returned(*F);
  2336. auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos);
  2337. return clampStateAndIndicateChange(getState(), FnAA.getState());
  2338. }
  2339. /// See AbstractAttribute::trackStatistics()
  2340. void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); }
  2341. };
  2342. /// -------------------AAIsDead Function Attribute-----------------------
  2343. struct AAIsDeadValueImpl : public AAIsDead {
  2344. AAIsDeadValueImpl(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
  2345. /// See AAIsDead::isAssumedDead().
  2346. bool isAssumedDead() const override { return getAssumed(); }
  2347. /// See AAIsDead::isKnownDead().
  2348. bool isKnownDead() const override { return getKnown(); }
  2349. /// See AAIsDead::isAssumedDead(BasicBlock *).
  2350. bool isAssumedDead(const BasicBlock *BB) const override { return false; }
  2351. /// See AAIsDead::isKnownDead(BasicBlock *).
  2352. bool isKnownDead(const BasicBlock *BB) const override { return false; }
  2353. /// See AAIsDead::isAssumedDead(Instruction *I).
  2354. bool isAssumedDead(const Instruction *I) const override {
  2355. return I == getCtxI() && isAssumedDead();
  2356. }
  2357. /// See AAIsDead::isKnownDead(Instruction *I).
  2358. bool isKnownDead(const Instruction *I) const override {
  2359. return isAssumedDead(I) && getKnown();
  2360. }
  2361. /// See AbstractAttribute::getAsStr().
  2362. const std::string getAsStr() const override {
  2363. return isAssumedDead() ? "assumed-dead" : "assumed-live";
  2364. }
  2365. /// Check if all uses are assumed dead.
  2366. bool areAllUsesAssumedDead(Attributor &A, Value &V) {
  2367. auto UsePred = [&](const Use &U, bool &Follow) { return false; };
  2368. // Explicitly set the dependence class to required because we want a long
  2369. // chain of N dependent instructions to be considered live as soon as one is
  2370. // without going through N update cycles. This is not required for
  2371. // correctness.
  2372. return A.checkForAllUses(UsePred, *this, V, DepClassTy::REQUIRED);
  2373. }
  2374. /// Determine if \p I is assumed to be side-effect free.
  2375. bool isAssumedSideEffectFree(Attributor &A, Instruction *I) {
  2376. if (!I || wouldInstructionBeTriviallyDead(I))
  2377. return true;
  2378. auto *CB = dyn_cast<CallBase>(I);
  2379. if (!CB || isa<IntrinsicInst>(CB))
  2380. return false;
  2381. const IRPosition &CallIRP = IRPosition::callsite_function(*CB);
  2382. const auto &NoUnwindAA = A.getAndUpdateAAFor<AANoUnwind>(
  2383. *this, CallIRP, /* TrackDependence */ false);
  2384. if (!NoUnwindAA.isAssumedNoUnwind())
  2385. return false;
  2386. if (!NoUnwindAA.isKnownNoUnwind())
  2387. A.recordDependence(NoUnwindAA, *this, DepClassTy::OPTIONAL);
  2388. const auto &MemBehaviorAA = A.getAndUpdateAAFor<AAMemoryBehavior>(
  2389. *this, CallIRP, /* TrackDependence */ false);
  2390. if (MemBehaviorAA.isAssumedReadOnly()) {
  2391. if (!MemBehaviorAA.isKnownReadOnly())
  2392. A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
  2393. return true;
  2394. }
  2395. return false;
  2396. }
  2397. };
  2398. struct AAIsDeadFloating : public AAIsDeadValueImpl {
  2399. AAIsDeadFloating(const IRPosition &IRP, Attributor &A)
  2400. : AAIsDeadValueImpl(IRP, A) {}
  2401. /// See AbstractAttribute::initialize(...).
  2402. void initialize(Attributor &A) override {
  2403. if (isa<UndefValue>(getAssociatedValue())) {
  2404. indicatePessimisticFixpoint();
  2405. return;
  2406. }
  2407. Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
  2408. if (!isAssumedSideEffectFree(A, I))
  2409. indicatePessimisticFixpoint();
  2410. }
  2411. /// See AbstractAttribute::updateImpl(...).
  2412. ChangeStatus updateImpl(Attributor &A) override {
  2413. Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
  2414. if (!isAssumedSideEffectFree(A, I))
  2415. return indicatePessimisticFixpoint();
  2416. if (!areAllUsesAssumedDead(A, getAssociatedValue()))
  2417. return indicatePessimisticFixpoint();
  2418. return ChangeStatus::UNCHANGED;
  2419. }
  2420. /// See AbstractAttribute::manifest(...).
  2421. ChangeStatus manifest(Attributor &A) override {
  2422. Value &V = getAssociatedValue();
  2423. if (auto *I = dyn_cast<Instruction>(&V)) {
  2424. // If we get here we basically know the users are all dead. We check if
  2425. // isAssumedSideEffectFree returns true here again because it might not be
  2426. // the case and only the users are dead but the instruction (=call) is
  2427. // still needed.
  2428. if (isAssumedSideEffectFree(A, I) && !isa<InvokeInst>(I)) {
  2429. A.deleteAfterManifest(*I);
  2430. return ChangeStatus::CHANGED;
  2431. }
  2432. }
  2433. if (V.use_empty())
  2434. return ChangeStatus::UNCHANGED;
  2435. bool UsedAssumedInformation = false;
  2436. Optional<Constant *> C =
  2437. A.getAssumedConstant(V, *this, UsedAssumedInformation);
  2438. if (C.hasValue() && C.getValue())
  2439. return ChangeStatus::UNCHANGED;
  2440. // Replace the value with undef as it is dead but keep droppable uses around
  2441. // as they provide information we don't want to give up on just yet.
  2442. UndefValue &UV = *UndefValue::get(V.getType());
  2443. bool AnyChange =
  2444. A.changeValueAfterManifest(V, UV, /* ChangeDropppable */ false);
  2445. return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
  2446. }
  2447. /// See AbstractAttribute::trackStatistics()
  2448. void trackStatistics() const override {
  2449. STATS_DECLTRACK_FLOATING_ATTR(IsDead)
  2450. }
  2451. };
  2452. struct AAIsDeadArgument : public AAIsDeadFloating {
  2453. AAIsDeadArgument(const IRPosition &IRP, Attributor &A)
  2454. : AAIsDeadFloating(IRP, A) {}
  2455. /// See AbstractAttribute::initialize(...).
  2456. void initialize(Attributor &A) override {
  2457. if (!A.isFunctionIPOAmendable(*getAnchorScope()))
  2458. indicatePessimisticFixpoint();
  2459. }
  2460. /// See AbstractAttribute::manifest(...).
  2461. ChangeStatus manifest(Attributor &A) override {
  2462. ChangeStatus Changed = AAIsDeadFloating::manifest(A);
  2463. Argument &Arg = *getAssociatedArgument();
  2464. if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {}))
  2465. if (A.registerFunctionSignatureRewrite(
  2466. Arg, /* ReplacementTypes */ {},
  2467. Attributor::ArgumentReplacementInfo::CalleeRepairCBTy{},
  2468. Attributor::ArgumentReplacementInfo::ACSRepairCBTy{})) {
  2469. Arg.dropDroppableUses();
  2470. return ChangeStatus::CHANGED;
  2471. }
  2472. return Changed;
  2473. }
  2474. /// See AbstractAttribute::trackStatistics()
  2475. void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) }
  2476. };
  2477. struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl {
  2478. AAIsDeadCallSiteArgument(const IRPosition &IRP, Attributor &A)
  2479. : AAIsDeadValueImpl(IRP, A) {}
  2480. /// See AbstractAttribute::initialize(...).
  2481. void initialize(Attributor &A) override {
  2482. if (isa<UndefValue>(getAssociatedValue()))
  2483. indicatePessimisticFixpoint();
  2484. }
  2485. /// See AbstractAttribute::updateImpl(...).
  2486. ChangeStatus updateImpl(Attributor &A) override {
  2487. // TODO: Once we have call site specific value information we can provide
  2488. // call site specific liveness information and then it makes
  2489. // sense to specialize attributes for call sites arguments instead of
  2490. // redirecting requests to the callee argument.
  2491. Argument *Arg = getAssociatedArgument();
  2492. if (!Arg)
  2493. return indicatePessimisticFixpoint();
  2494. const IRPosition &ArgPos = IRPosition::argument(*Arg);
  2495. auto &ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos);
  2496. return clampStateAndIndicateChange(getState(), ArgAA.getState());
  2497. }
  2498. /// See AbstractAttribute::manifest(...).
  2499. ChangeStatus manifest(Attributor &A) override {
  2500. CallBase &CB = cast<CallBase>(getAnchorValue());
  2501. Use &U = CB.getArgOperandUse(getCallSiteArgNo());
  2502. assert(!isa<UndefValue>(U.get()) &&
  2503. "Expected undef values to be filtered out!");
  2504. UndefValue &UV = *UndefValue::get(U->getType());
  2505. if (A.changeUseAfterManifest(U, UV))
  2506. return ChangeStatus::CHANGED;
  2507. return ChangeStatus::UNCHANGED;
  2508. }
  2509. /// See AbstractAttribute::trackStatistics()
  2510. void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) }
  2511. };
  2512. struct AAIsDeadCallSiteReturned : public AAIsDeadFloating {
  2513. AAIsDeadCallSiteReturned(const IRPosition &IRP, Attributor &A)
  2514. : AAIsDeadFloating(IRP, A), IsAssumedSideEffectFree(true) {}
  2515. /// See AAIsDead::isAssumedDead().
  2516. bool isAssumedDead() const override {
  2517. return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
  2518. }
  2519. /// See AbstractAttribute::initialize(...).
  2520. void initialize(Attributor &A) override {
  2521. if (isa<UndefValue>(getAssociatedValue())) {
  2522. indicatePessimisticFixpoint();
  2523. return;
  2524. }
  2525. // We track this separately as a secondary state.
  2526. IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI());
  2527. }
  2528. /// See AbstractAttribute::updateImpl(...).
  2529. ChangeStatus updateImpl(Attributor &A) override {
  2530. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  2531. if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) {
  2532. IsAssumedSideEffectFree = false;
  2533. Changed = ChangeStatus::CHANGED;
  2534. }
  2535. if (!areAllUsesAssumedDead(A, getAssociatedValue()))
  2536. return indicatePessimisticFixpoint();
  2537. return Changed;
  2538. }
  2539. /// See AbstractAttribute::trackStatistics()
  2540. void trackStatistics() const override {
  2541. if (IsAssumedSideEffectFree)
  2542. STATS_DECLTRACK_CSRET_ATTR(IsDead)
  2543. else
  2544. STATS_DECLTRACK_CSRET_ATTR(UnusedResult)
  2545. }
  2546. /// See AbstractAttribute::getAsStr().
  2547. const std::string getAsStr() const override {
  2548. return isAssumedDead()
  2549. ? "assumed-dead"
  2550. : (getAssumed() ? "assumed-dead-users" : "assumed-live");
  2551. }
  2552. private:
  2553. bool IsAssumedSideEffectFree;
  2554. };
  2555. struct AAIsDeadReturned : public AAIsDeadValueImpl {
  2556. AAIsDeadReturned(const IRPosition &IRP, Attributor &A)
  2557. : AAIsDeadValueImpl(IRP, A) {}
  2558. /// See AbstractAttribute::updateImpl(...).
  2559. ChangeStatus updateImpl(Attributor &A) override {
  2560. A.checkForAllInstructions([](Instruction &) { return true; }, *this,
  2561. {Instruction::Ret});
  2562. auto PredForCallSite = [&](AbstractCallSite ACS) {
  2563. if (ACS.isCallbackCall() || !ACS.getInstruction())
  2564. return false;
  2565. return areAllUsesAssumedDead(A, *ACS.getInstruction());
  2566. };
  2567. bool AllCallSitesKnown;
  2568. if (!A.checkForAllCallSites(PredForCallSite, *this, true,
  2569. AllCallSitesKnown))
  2570. return indicatePessimisticFixpoint();
  2571. return ChangeStatus::UNCHANGED;
  2572. }
  2573. /// See AbstractAttribute::manifest(...).
  2574. ChangeStatus manifest(Attributor &A) override {
  2575. // TODO: Rewrite the signature to return void?
  2576. bool AnyChange = false;
  2577. UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType());
  2578. auto RetInstPred = [&](Instruction &I) {
  2579. ReturnInst &RI = cast<ReturnInst>(I);
  2580. if (!isa<UndefValue>(RI.getReturnValue()))
  2581. AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV);
  2582. return true;
  2583. };
  2584. A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret});
  2585. return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
  2586. }
  2587. /// See AbstractAttribute::trackStatistics()
  2588. void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) }
  2589. };
  2590. struct AAIsDeadFunction : public AAIsDead {
  2591. AAIsDeadFunction(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
  2592. /// See AbstractAttribute::initialize(...).
  2593. void initialize(Attributor &A) override {
  2594. const Function *F = getAnchorScope();
  2595. if (F && !F->isDeclaration()) {
  2596. // We only want to compute liveness once. If the function is not part of
  2597. // the SCC, skip it.
  2598. if (A.isRunOn(*const_cast<Function *>(F))) {
  2599. ToBeExploredFrom.insert(&F->getEntryBlock().front());
  2600. assumeLive(A, F->getEntryBlock());
  2601. } else {
  2602. indicatePessimisticFixpoint();
  2603. }
  2604. }
  2605. }
  2606. /// See AbstractAttribute::getAsStr().
  2607. const std::string getAsStr() const override {
  2608. return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
  2609. std::to_string(getAnchorScope()->size()) + "][#TBEP " +
  2610. std::to_string(ToBeExploredFrom.size()) + "][#KDE " +
  2611. std::to_string(KnownDeadEnds.size()) + "]";
  2612. }
  2613. /// See AbstractAttribute::manifest(...).
  2614. ChangeStatus manifest(Attributor &A) override {
  2615. assert(getState().isValidState() &&
  2616. "Attempted to manifest an invalid state!");
  2617. ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
  2618. Function &F = *getAnchorScope();
  2619. if (AssumedLiveBlocks.empty()) {
  2620. A.deleteAfterManifest(F);
  2621. return ChangeStatus::CHANGED;
  2622. }
  2623. // Flag to determine if we can change an invoke to a call assuming the
  2624. // callee is nounwind. This is not possible if the personality of the
  2625. // function allows to catch asynchronous exceptions.
  2626. bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
  2627. KnownDeadEnds.set_union(ToBeExploredFrom);
  2628. for (const Instruction *DeadEndI : KnownDeadEnds) {
  2629. auto *CB = dyn_cast<CallBase>(DeadEndI);
  2630. if (!CB)
  2631. continue;
  2632. const auto &NoReturnAA = A.getAndUpdateAAFor<AANoReturn>(
  2633. *this, IRPosition::callsite_function(*CB), /* TrackDependence */ true,
  2634. DepClassTy::OPTIONAL);
  2635. bool MayReturn = !NoReturnAA.isAssumedNoReturn();
  2636. if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB)))
  2637. continue;
  2638. if (auto *II = dyn_cast<InvokeInst>(DeadEndI))
  2639. A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II));
  2640. else
  2641. A.changeToUnreachableAfterManifest(
  2642. const_cast<Instruction *>(DeadEndI->getNextNode()));
  2643. HasChanged = ChangeStatus::CHANGED;
  2644. }
  2645. STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted.");
  2646. for (BasicBlock &BB : F)
  2647. if (!AssumedLiveBlocks.count(&BB)) {
  2648. A.deleteAfterManifest(BB);
  2649. ++BUILD_STAT_NAME(AAIsDead, BasicBlock);
  2650. }
  2651. return HasChanged;
  2652. }
  2653. /// See AbstractAttribute::updateImpl(...).
  2654. ChangeStatus updateImpl(Attributor &A) override;
  2655. bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const override {
  2656. return !AssumedLiveEdges.count(std::make_pair(From, To));
  2657. }
  2658. /// See AbstractAttribute::trackStatistics()
  2659. void trackStatistics() const override {}
  2660. /// Returns true if the function is assumed dead.
  2661. bool isAssumedDead() const override { return false; }
  2662. /// See AAIsDead::isKnownDead().
  2663. bool isKnownDead() const override { return false; }
  2664. /// See AAIsDead::isAssumedDead(BasicBlock *).
  2665. bool isAssumedDead(const BasicBlock *BB) const override {
  2666. assert(BB->getParent() == getAnchorScope() &&
  2667. "BB must be in the same anchor scope function.");
  2668. if (!getAssumed())
  2669. return false;
  2670. return !AssumedLiveBlocks.count(BB);
  2671. }
  2672. /// See AAIsDead::isKnownDead(BasicBlock *).
  2673. bool isKnownDead(const BasicBlock *BB) const override {
  2674. return getKnown() && isAssumedDead(BB);
  2675. }
  2676. /// See AAIsDead::isAssumed(Instruction *I).
  2677. bool isAssumedDead(const Instruction *I) const override {
  2678. assert(I->getParent()->getParent() == getAnchorScope() &&
  2679. "Instruction must be in the same anchor scope function.");
  2680. if (!getAssumed())
  2681. return false;
  2682. // If it is not in AssumedLiveBlocks then it for sure dead.
  2683. // Otherwise, it can still be after noreturn call in a live block.
  2684. if (!AssumedLiveBlocks.count(I->getParent()))
  2685. return true;
  2686. // If it is not after a liveness barrier it is live.
  2687. const Instruction *PrevI = I->getPrevNode();
  2688. while (PrevI) {
  2689. if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
  2690. return true;
  2691. PrevI = PrevI->getPrevNode();
  2692. }
  2693. return false;
  2694. }
  2695. /// See AAIsDead::isKnownDead(Instruction *I).
  2696. bool isKnownDead(const Instruction *I) const override {
  2697. return getKnown() && isAssumedDead(I);
  2698. }
  2699. /// Assume \p BB is (partially) live now and indicate to the Attributor \p A
  2700. /// that internal function called from \p BB should now be looked at.
  2701. bool assumeLive(Attributor &A, const BasicBlock &BB) {
  2702. if (!AssumedLiveBlocks.insert(&BB).second)
  2703. return false;
  2704. // We assume that all of BB is (probably) live now and if there are calls to
  2705. // internal functions we will assume that those are now live as well. This
  2706. // is a performance optimization for blocks with calls to a lot of internal
  2707. // functions. It can however cause dead functions to be treated as live.
  2708. for (const Instruction &I : BB)
  2709. if (const auto *CB = dyn_cast<CallBase>(&I))
  2710. if (const Function *F = CB->getCalledFunction())
  2711. if (F->hasLocalLinkage())
  2712. A.markLiveInternalFunction(*F);
  2713. return true;
  2714. }
  2715. /// Collection of instructions that need to be explored again, e.g., we
  2716. /// did assume they do not transfer control to (one of their) successors.
  2717. SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
  2718. /// Collection of instructions that are known to not transfer control.
  2719. SmallSetVector<const Instruction *, 8> KnownDeadEnds;
  2720. /// Collection of all assumed live edges
  2721. DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> AssumedLiveEdges;
  2722. /// Collection of all assumed live BasicBlocks.
  2723. DenseSet<const BasicBlock *> AssumedLiveBlocks;
  2724. };
  2725. static bool
  2726. identifyAliveSuccessors(Attributor &A, const CallBase &CB,
  2727. AbstractAttribute &AA,
  2728. SmallVectorImpl<const Instruction *> &AliveSuccessors) {
  2729. const IRPosition &IPos = IRPosition::callsite_function(CB);
  2730. const auto &NoReturnAA = A.getAndUpdateAAFor<AANoReturn>(
  2731. AA, IPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
  2732. if (NoReturnAA.isAssumedNoReturn())
  2733. return !NoReturnAA.isKnownNoReturn();
  2734. if (CB.isTerminator())
  2735. AliveSuccessors.push_back(&CB.getSuccessor(0)->front());
  2736. else
  2737. AliveSuccessors.push_back(CB.getNextNode());
  2738. return false;
  2739. }
  2740. static bool
  2741. identifyAliveSuccessors(Attributor &A, const InvokeInst &II,
  2742. AbstractAttribute &AA,
  2743. SmallVectorImpl<const Instruction *> &AliveSuccessors) {
  2744. bool UsedAssumedInformation =
  2745. identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors);
  2746. // First, determine if we can change an invoke to a call assuming the
  2747. // callee is nounwind. This is not possible if the personality of the
  2748. // function allows to catch asynchronous exceptions.
  2749. if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) {
  2750. AliveSuccessors.push_back(&II.getUnwindDest()->front());
  2751. } else {
  2752. const IRPosition &IPos = IRPosition::callsite_function(II);
  2753. const auto &AANoUnw = A.getAndUpdateAAFor<AANoUnwind>(
  2754. AA, IPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
  2755. if (AANoUnw.isAssumedNoUnwind()) {
  2756. UsedAssumedInformation |= !AANoUnw.isKnownNoUnwind();
  2757. } else {
  2758. AliveSuccessors.push_back(&II.getUnwindDest()->front());
  2759. }
  2760. }
  2761. return UsedAssumedInformation;
  2762. }
  2763. static bool
  2764. identifyAliveSuccessors(Attributor &A, const BranchInst &BI,
  2765. AbstractAttribute &AA,
  2766. SmallVectorImpl<const Instruction *> &AliveSuccessors) {
  2767. bool UsedAssumedInformation = false;
  2768. if (BI.getNumSuccessors() == 1) {
  2769. AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
  2770. } else {
  2771. Optional<ConstantInt *> CI = getAssumedConstantInt(
  2772. A, *BI.getCondition(), AA, UsedAssumedInformation);
  2773. if (!CI.hasValue()) {
  2774. // No value yet, assume both edges are dead.
  2775. } else if (CI.getValue()) {
  2776. const BasicBlock *SuccBB =
  2777. BI.getSuccessor(1 - CI.getValue()->getZExtValue());
  2778. AliveSuccessors.push_back(&SuccBB->front());
  2779. } else {
  2780. AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
  2781. AliveSuccessors.push_back(&BI.getSuccessor(1)->front());
  2782. UsedAssumedInformation = false;
  2783. }
  2784. }
  2785. return UsedAssumedInformation;
  2786. }
  2787. static bool
  2788. identifyAliveSuccessors(Attributor &A, const SwitchInst &SI,
  2789. AbstractAttribute &AA,
  2790. SmallVectorImpl<const Instruction *> &AliveSuccessors) {
  2791. bool UsedAssumedInformation = false;
  2792. Optional<ConstantInt *> CI =
  2793. getAssumedConstantInt(A, *SI.getCondition(), AA, UsedAssumedInformation);
  2794. if (!CI.hasValue()) {
  2795. // No value yet, assume all edges are dead.
  2796. } else if (CI.getValue()) {
  2797. for (auto &CaseIt : SI.cases()) {
  2798. if (CaseIt.getCaseValue() == CI.getValue()) {
  2799. AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front());
  2800. return UsedAssumedInformation;
  2801. }
  2802. }
  2803. AliveSuccessors.push_back(&SI.getDefaultDest()->front());
  2804. return UsedAssumedInformation;
  2805. } else {
  2806. for (const BasicBlock *SuccBB : successors(SI.getParent()))
  2807. AliveSuccessors.push_back(&SuccBB->front());
  2808. }
  2809. return UsedAssumedInformation;
  2810. }
  2811. ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
  2812. ChangeStatus Change = ChangeStatus::UNCHANGED;
  2813. LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/"
  2814. << getAnchorScope()->size() << "] BBs and "
  2815. << ToBeExploredFrom.size() << " exploration points and "
  2816. << KnownDeadEnds.size() << " known dead ends\n");
  2817. // Copy and clear the list of instructions we need to explore from. It is
  2818. // refilled with instructions the next update has to look at.
  2819. SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(),
  2820. ToBeExploredFrom.end());
  2821. decltype(ToBeExploredFrom) NewToBeExploredFrom;
  2822. SmallVector<const Instruction *, 8> AliveSuccessors;
  2823. while (!Worklist.empty()) {
  2824. const Instruction *I = Worklist.pop_back_val();
  2825. LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n");
  2826. // Fast forward for uninteresting instructions. We could look for UB here
  2827. // though.
  2828. while (!I->isTerminator() && !isa<CallBase>(I)) {
  2829. Change = ChangeStatus::CHANGED;
  2830. I = I->getNextNode();
  2831. }
  2832. AliveSuccessors.clear();
  2833. bool UsedAssumedInformation = false;
  2834. switch (I->getOpcode()) {
  2835. // TODO: look for (assumed) UB to backwards propagate "deadness".
  2836. default:
  2837. assert(I->isTerminator() &&
  2838. "Expected non-terminators to be handled already!");
  2839. for (const BasicBlock *SuccBB : successors(I->getParent()))
  2840. AliveSuccessors.push_back(&SuccBB->front());
  2841. break;
  2842. case Instruction::Call:
  2843. UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I),
  2844. *this, AliveSuccessors);
  2845. break;
  2846. case Instruction::Invoke:
  2847. UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I),
  2848. *this, AliveSuccessors);
  2849. break;
  2850. case Instruction::Br:
  2851. UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I),
  2852. *this, AliveSuccessors);
  2853. break;
  2854. case Instruction::Switch:
  2855. UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I),
  2856. *this, AliveSuccessors);
  2857. break;
  2858. }
  2859. if (UsedAssumedInformation) {
  2860. NewToBeExploredFrom.insert(I);
  2861. } else {
  2862. Change = ChangeStatus::CHANGED;
  2863. if (AliveSuccessors.empty() ||
  2864. (I->isTerminator() && AliveSuccessors.size() < I->getNumSuccessors()))
  2865. KnownDeadEnds.insert(I);
  2866. }
  2867. LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: "
  2868. << AliveSuccessors.size() << " UsedAssumedInformation: "
  2869. << UsedAssumedInformation << "\n");
  2870. for (const Instruction *AliveSuccessor : AliveSuccessors) {
  2871. if (!I->isTerminator()) {
  2872. assert(AliveSuccessors.size() == 1 &&
  2873. "Non-terminator expected to have a single successor!");
  2874. Worklist.push_back(AliveSuccessor);
  2875. } else {
  2876. // record the assumed live edge
  2877. AssumedLiveEdges.insert(
  2878. std::make_pair(I->getParent(), AliveSuccessor->getParent()));
  2879. if (assumeLive(A, *AliveSuccessor->getParent()))
  2880. Worklist.push_back(AliveSuccessor);
  2881. }
  2882. }
  2883. }
  2884. ToBeExploredFrom = std::move(NewToBeExploredFrom);
  2885. // If we know everything is live there is no need to query for liveness.
  2886. // Instead, indicating a pessimistic fixpoint will cause the state to be
  2887. // "invalid" and all queries to be answered conservatively without lookups.
  2888. // To be in this state we have to (1) finished the exploration and (3) not
  2889. // discovered any non-trivial dead end and (2) not ruled unreachable code
  2890. // dead.
  2891. if (ToBeExploredFrom.empty() &&
  2892. getAnchorScope()->size() == AssumedLiveBlocks.size() &&
  2893. llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) {
  2894. return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
  2895. }))
  2896. return indicatePessimisticFixpoint();
  2897. return Change;
  2898. }
  2899. /// Liveness information for a call sites.
  2900. struct AAIsDeadCallSite final : AAIsDeadFunction {
  2901. AAIsDeadCallSite(const IRPosition &IRP, Attributor &A)
  2902. : AAIsDeadFunction(IRP, A) {}
  2903. /// See AbstractAttribute::initialize(...).
  2904. void initialize(Attributor &A) override {
  2905. // TODO: Once we have call site specific value information we can provide
  2906. // call site specific liveness information and then it makes
  2907. // sense to specialize attributes for call sites instead of
  2908. // redirecting requests to the callee.
  2909. llvm_unreachable("Abstract attributes for liveness are not "
  2910. "supported for call sites yet!");
  2911. }
  2912. /// See AbstractAttribute::updateImpl(...).
  2913. ChangeStatus updateImpl(Attributor &A) override {
  2914. return indicatePessimisticFixpoint();
  2915. }
  2916. /// See AbstractAttribute::trackStatistics()
  2917. void trackStatistics() const override {}
  2918. };
  2919. /// -------------------- Dereferenceable Argument Attribute --------------------
  2920. template <>
  2921. ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S,
  2922. const DerefState &R) {
  2923. ChangeStatus CS0 =
  2924. clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState);
  2925. ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState);
  2926. return CS0 | CS1;
  2927. }
  2928. struct AADereferenceableImpl : AADereferenceable {
  2929. AADereferenceableImpl(const IRPosition &IRP, Attributor &A)
  2930. : AADereferenceable(IRP, A) {}
  2931. using StateType = DerefState;
  2932. /// See AbstractAttribute::initialize(...).
  2933. void initialize(Attributor &A) override {
  2934. SmallVector<Attribute, 4> Attrs;
  2935. getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
  2936. Attrs, /* IgnoreSubsumingPositions */ false, &A);
  2937. for (const Attribute &Attr : Attrs)
  2938. takeKnownDerefBytesMaximum(Attr.getValueAsInt());
  2939. const IRPosition &IRP = this->getIRPosition();
  2940. NonNullAA = &A.getAAFor<AANonNull>(*this, IRP,
  2941. /* TrackDependence */ false);
  2942. bool CanBeNull;
  2943. takeKnownDerefBytesMaximum(
  2944. IRP.getAssociatedValue().getPointerDereferenceableBytes(
  2945. A.getDataLayout(), CanBeNull));
  2946. bool IsFnInterface = IRP.isFnInterfaceKind();
  2947. Function *FnScope = IRP.getAnchorScope();
  2948. if (IsFnInterface && (!FnScope || !A.isFunctionIPOAmendable(*FnScope))) {
  2949. indicatePessimisticFixpoint();
  2950. return;
  2951. }
  2952. if (Instruction *CtxI = getCtxI())
  2953. followUsesInMBEC(*this, A, getState(), *CtxI);
  2954. }
  2955. /// See AbstractAttribute::getState()
  2956. /// {
  2957. StateType &getState() override { return *this; }
  2958. const StateType &getState() const override { return *this; }
  2959. /// }
  2960. /// Helper function for collecting accessed bytes in must-be-executed-context
  2961. void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I,
  2962. DerefState &State) {
  2963. const Value *UseV = U->get();
  2964. if (!UseV->getType()->isPointerTy())
  2965. return;
  2966. Type *PtrTy = UseV->getType();
  2967. const DataLayout &DL = A.getDataLayout();
  2968. int64_t Offset;
  2969. if (const Value *Base = getBasePointerOfAccessPointerOperand(
  2970. I, Offset, DL, /*AllowNonInbounds*/ true)) {
  2971. if (Base == &getAssociatedValue() &&
  2972. getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
  2973. uint64_t Size = DL.getTypeStoreSize(PtrTy->getPointerElementType());
  2974. State.addAccessedBytes(Offset, Size);
  2975. }
  2976. }
  2977. }
  2978. /// See followUsesInMBEC
  2979. bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
  2980. AADereferenceable::StateType &State) {
  2981. bool IsNonNull = false;
  2982. bool TrackUse = false;
  2983. int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
  2984. A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse);
  2985. LLVM_DEBUG(dbgs() << "[AADereferenceable] Deref bytes: " << DerefBytes
  2986. << " for instruction " << *I << "\n");
  2987. addAccessedBytesForUse(A, U, I, State);
  2988. State.takeKnownDerefBytesMaximum(DerefBytes);
  2989. return TrackUse;
  2990. }
  2991. /// See AbstractAttribute::manifest(...).
  2992. ChangeStatus manifest(Attributor &A) override {
  2993. ChangeStatus Change = AADereferenceable::manifest(A);
  2994. if (isAssumedNonNull() && hasAttr(Attribute::DereferenceableOrNull)) {
  2995. removeAttrs({Attribute::DereferenceableOrNull});
  2996. return ChangeStatus::CHANGED;
  2997. }
  2998. return Change;
  2999. }
  3000. void getDeducedAttributes(LLVMContext &Ctx,
  3001. SmallVectorImpl<Attribute> &Attrs) const override {
  3002. // TODO: Add *_globally support
  3003. if (isAssumedNonNull())
  3004. Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
  3005. Ctx, getAssumedDereferenceableBytes()));
  3006. else
  3007. Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
  3008. Ctx, getAssumedDereferenceableBytes()));
  3009. }
  3010. /// See AbstractAttribute::getAsStr().
  3011. const std::string getAsStr() const override {
  3012. if (!getAssumedDereferenceableBytes())
  3013. return "unknown-dereferenceable";
  3014. return std::string("dereferenceable") +
  3015. (isAssumedNonNull() ? "" : "_or_null") +
  3016. (isAssumedGlobal() ? "_globally" : "") + "<" +
  3017. std::to_string(getKnownDereferenceableBytes()) + "-" +
  3018. std::to_string(getAssumedDereferenceableBytes()) + ">";
  3019. }
  3020. };
  3021. /// Dereferenceable attribute for a floating value.
  3022. struct AADereferenceableFloating : AADereferenceableImpl {
  3023. AADereferenceableFloating(const IRPosition &IRP, Attributor &A)
  3024. : AADereferenceableImpl(IRP, A) {}
  3025. /// See AbstractAttribute::updateImpl(...).
  3026. ChangeStatus updateImpl(Attributor &A) override {
  3027. const DataLayout &DL = A.getDataLayout();
  3028. auto VisitValueCB = [&](const Value &V, const Instruction *, DerefState &T,
  3029. bool Stripped) -> bool {
  3030. unsigned IdxWidth =
  3031. DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
  3032. APInt Offset(IdxWidth, 0);
  3033. const Value *Base =
  3034. stripAndAccumulateMinimalOffsets(A, *this, &V, DL, Offset, false);
  3035. const auto &AA =
  3036. A.getAAFor<AADereferenceable>(*this, IRPosition::value(*Base));
  3037. int64_t DerefBytes = 0;
  3038. if (!Stripped && this == &AA) {
  3039. // Use IR information if we did not strip anything.
  3040. // TODO: track globally.
  3041. bool CanBeNull;
  3042. DerefBytes = Base->getPointerDereferenceableBytes(DL, CanBeNull);
  3043. T.GlobalState.indicatePessimisticFixpoint();
  3044. } else {
  3045. const DerefState &DS = AA.getState();
  3046. DerefBytes = DS.DerefBytesState.getAssumed();
  3047. T.GlobalState &= DS.GlobalState;
  3048. }
  3049. // For now we do not try to "increase" dereferenceability due to negative
  3050. // indices as we first have to come up with code to deal with loops and
  3051. // for overflows of the dereferenceable bytes.
  3052. int64_t OffsetSExt = Offset.getSExtValue();
  3053. if (OffsetSExt < 0)
  3054. OffsetSExt = 0;
  3055. T.takeAssumedDerefBytesMinimum(
  3056. std::max(int64_t(0), DerefBytes - OffsetSExt));
  3057. if (this == &AA) {
  3058. if (!Stripped) {
  3059. // If nothing was stripped IR information is all we got.
  3060. T.takeKnownDerefBytesMaximum(
  3061. std::max(int64_t(0), DerefBytes - OffsetSExt));
  3062. T.indicatePessimisticFixpoint();
  3063. } else if (OffsetSExt > 0) {
  3064. // If something was stripped but there is circular reasoning we look
  3065. // for the offset. If it is positive we basically decrease the
  3066. // dereferenceable bytes in a circluar loop now, which will simply
  3067. // drive them down to the known value in a very slow way which we
  3068. // can accelerate.
  3069. T.indicatePessimisticFixpoint();
  3070. }
  3071. }
  3072. return T.isValidState();
  3073. };
  3074. DerefState T;
  3075. if (!genericValueTraversal<AADereferenceable, DerefState>(
  3076. A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
  3077. return indicatePessimisticFixpoint();
  3078. return clampStateAndIndicateChange(getState(), T);
  3079. }
  3080. /// See AbstractAttribute::trackStatistics()
  3081. void trackStatistics() const override {
  3082. STATS_DECLTRACK_FLOATING_ATTR(dereferenceable)
  3083. }
  3084. };
  3085. /// Dereferenceable attribute for a return value.
  3086. struct AADereferenceableReturned final
  3087. : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
  3088. AADereferenceableReturned(const IRPosition &IRP, Attributor &A)
  3089. : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>(
  3090. IRP, A) {}
  3091. /// See AbstractAttribute::trackStatistics()
  3092. void trackStatistics() const override {
  3093. STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
  3094. }
  3095. };
  3096. /// Dereferenceable attribute for an argument
  3097. struct AADereferenceableArgument final
  3098. : AAArgumentFromCallSiteArguments<AADereferenceable,
  3099. AADereferenceableImpl> {
  3100. using Base =
  3101. AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>;
  3102. AADereferenceableArgument(const IRPosition &IRP, Attributor &A)
  3103. : Base(IRP, A) {}
  3104. /// See AbstractAttribute::trackStatistics()
  3105. void trackStatistics() const override {
  3106. STATS_DECLTRACK_ARG_ATTR(dereferenceable)
  3107. }
  3108. };
  3109. /// Dereferenceable attribute for a call site argument.
  3110. struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
  3111. AADereferenceableCallSiteArgument(const IRPosition &IRP, Attributor &A)
  3112. : AADereferenceableFloating(IRP, A) {}
  3113. /// See AbstractAttribute::trackStatistics()
  3114. void trackStatistics() const override {
  3115. STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
  3116. }
  3117. };
  3118. /// Dereferenceable attribute deduction for a call site return value.
  3119. struct AADereferenceableCallSiteReturned final
  3120. : AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl> {
  3121. using Base =
  3122. AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl>;
  3123. AADereferenceableCallSiteReturned(const IRPosition &IRP, Attributor &A)
  3124. : Base(IRP, A) {}
  3125. /// See AbstractAttribute::trackStatistics()
  3126. void trackStatistics() const override {
  3127. STATS_DECLTRACK_CS_ATTR(dereferenceable);
  3128. }
  3129. };
  3130. // ------------------------ Align Argument Attribute ------------------------
  3131. static unsigned getKnownAlignForUse(Attributor &A,
  3132. AbstractAttribute &QueryingAA,
  3133. Value &AssociatedValue, const Use *U,
  3134. const Instruction *I, bool &TrackUse) {
  3135. // We need to follow common pointer manipulation uses to the accesses they
  3136. // feed into.
  3137. if (isa<CastInst>(I)) {
  3138. // Follow all but ptr2int casts.
  3139. TrackUse = !isa<PtrToIntInst>(I);
  3140. return 0;
  3141. }
  3142. if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
  3143. if (GEP->hasAllConstantIndices()) {
  3144. TrackUse = true;
  3145. return 0;
  3146. }
  3147. }
  3148. MaybeAlign MA;
  3149. if (const auto *CB = dyn_cast<CallBase>(I)) {
  3150. if (CB->isBundleOperand(U) || CB->isCallee(U))
  3151. return 0;
  3152. unsigned ArgNo = CB->getArgOperandNo(U);
  3153. IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
  3154. // As long as we only use known information there is no need to track
  3155. // dependences here.
  3156. auto &AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP,
  3157. /* TrackDependence */ false);
  3158. MA = MaybeAlign(AlignAA.getKnownAlign());
  3159. }
  3160. const DataLayout &DL = A.getDataLayout();
  3161. const Value *UseV = U->get();
  3162. if (auto *SI = dyn_cast<StoreInst>(I)) {
  3163. if (SI->getPointerOperand() == UseV)
  3164. MA = SI->getAlign();
  3165. } else if (auto *LI = dyn_cast<LoadInst>(I)) {
  3166. if (LI->getPointerOperand() == UseV)
  3167. MA = LI->getAlign();
  3168. }
  3169. if (!MA || *MA <= 1)
  3170. return 0;
  3171. unsigned Alignment = MA->value();
  3172. int64_t Offset;
  3173. if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) {
  3174. if (Base == &AssociatedValue) {
  3175. // BasePointerAddr + Offset = Alignment * Q for some integer Q.
  3176. // So we can say that the maximum power of two which is a divisor of
  3177. // gcd(Offset, Alignment) is an alignment.
  3178. uint32_t gcd =
  3179. greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), Alignment);
  3180. Alignment = llvm::PowerOf2Floor(gcd);
  3181. }
  3182. }
  3183. return Alignment;
  3184. }
  3185. struct AAAlignImpl : AAAlign {
  3186. AAAlignImpl(const IRPosition &IRP, Attributor &A) : AAAlign(IRP, A) {}
  3187. /// See AbstractAttribute::initialize(...).
  3188. void initialize(Attributor &A) override {
  3189. SmallVector<Attribute, 4> Attrs;
  3190. getAttrs({Attribute::Alignment}, Attrs);
  3191. for (const Attribute &Attr : Attrs)
  3192. takeKnownMaximum(Attr.getValueAsInt());
  3193. Value &V = getAssociatedValue();
  3194. // TODO: This is a HACK to avoid getPointerAlignment to introduce a ptr2int
  3195. // use of the function pointer. This was caused by D73131. We want to
  3196. // avoid this for function pointers especially because we iterate
  3197. // their uses and int2ptr is not handled. It is not a correctness
  3198. // problem though!
  3199. if (!V.getType()->getPointerElementType()->isFunctionTy())
  3200. takeKnownMaximum(V.getPointerAlignment(A.getDataLayout()).value());
  3201. if (getIRPosition().isFnInterfaceKind() &&
  3202. (!getAnchorScope() ||
  3203. !A.isFunctionIPOAmendable(*getAssociatedFunction()))) {
  3204. indicatePessimisticFixpoint();
  3205. return;
  3206. }
  3207. if (Instruction *CtxI = getCtxI())
  3208. followUsesInMBEC(*this, A, getState(), *CtxI);
  3209. }
  3210. /// See AbstractAttribute::manifest(...).
  3211. ChangeStatus manifest(Attributor &A) override {
  3212. ChangeStatus LoadStoreChanged = ChangeStatus::UNCHANGED;
  3213. // Check for users that allow alignment annotations.
  3214. Value &AssociatedValue = getAssociatedValue();
  3215. for (const Use &U : AssociatedValue.uses()) {
  3216. if (auto *SI = dyn_cast<StoreInst>(U.getUser())) {
  3217. if (SI->getPointerOperand() == &AssociatedValue)
  3218. if (SI->getAlignment() < getAssumedAlign()) {
  3219. STATS_DECLTRACK(AAAlign, Store,
  3220. "Number of times alignment added to a store");
  3221. SI->setAlignment(Align(getAssumedAlign()));
  3222. LoadStoreChanged = ChangeStatus::CHANGED;
  3223. }
  3224. } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) {
  3225. if (LI->getPointerOperand() == &AssociatedValue)
  3226. if (LI->getAlignment() < getAssumedAlign()) {
  3227. LI->setAlignment(Align(getAssumedAlign()));
  3228. STATS_DECLTRACK(AAAlign, Load,
  3229. "Number of times alignment added to a load");
  3230. LoadStoreChanged = ChangeStatus::CHANGED;
  3231. }
  3232. }
  3233. }
  3234. ChangeStatus Changed = AAAlign::manifest(A);
  3235. Align InheritAlign =
  3236. getAssociatedValue().getPointerAlignment(A.getDataLayout());
  3237. if (InheritAlign >= getAssumedAlign())
  3238. return LoadStoreChanged;
  3239. return Changed | LoadStoreChanged;
  3240. }
  3241. // TODO: Provide a helper to determine the implied ABI alignment and check in
  3242. // the existing manifest method and a new one for AAAlignImpl that value
  3243. // to avoid making the alignment explicit if it did not improve.
  3244. /// See AbstractAttribute::getDeducedAttributes
  3245. virtual void
  3246. getDeducedAttributes(LLVMContext &Ctx,
  3247. SmallVectorImpl<Attribute> &Attrs) const override {
  3248. if (getAssumedAlign() > 1)
  3249. Attrs.emplace_back(
  3250. Attribute::getWithAlignment(Ctx, Align(getAssumedAlign())));
  3251. }
  3252. /// See followUsesInMBEC
  3253. bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
  3254. AAAlign::StateType &State) {
  3255. bool TrackUse = false;
  3256. unsigned int KnownAlign =
  3257. getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse);
  3258. State.takeKnownMaximum(KnownAlign);
  3259. return TrackUse;
  3260. }
  3261. /// See AbstractAttribute::getAsStr().
  3262. const std::string getAsStr() const override {
  3263. return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) +
  3264. "-" + std::to_string(getAssumedAlign()) + ">")
  3265. : "unknown-align";
  3266. }
  3267. };
  3268. /// Align attribute for a floating value.
  3269. struct AAAlignFloating : AAAlignImpl {
  3270. AAAlignFloating(const IRPosition &IRP, Attributor &A) : AAAlignImpl(IRP, A) {}
  3271. /// See AbstractAttribute::updateImpl(...).
  3272. ChangeStatus updateImpl(Attributor &A) override {
  3273. const DataLayout &DL = A.getDataLayout();
  3274. auto VisitValueCB = [&](Value &V, const Instruction *,
  3275. AAAlign::StateType &T, bool Stripped) -> bool {
  3276. const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V));
  3277. if (!Stripped && this == &AA) {
  3278. int64_t Offset;
  3279. unsigned Alignment = 1;
  3280. if (const Value *Base =
  3281. GetPointerBaseWithConstantOffset(&V, Offset, DL)) {
  3282. Align PA = Base->getPointerAlignment(DL);
  3283. // BasePointerAddr + Offset = Alignment * Q for some integer Q.
  3284. // So we can say that the maximum power of two which is a divisor of
  3285. // gcd(Offset, Alignment) is an alignment.
  3286. uint32_t gcd = greatestCommonDivisor(uint32_t(abs((int32_t)Offset)),
  3287. uint32_t(PA.value()));
  3288. Alignment = llvm::PowerOf2Floor(gcd);
  3289. } else {
  3290. Alignment = V.getPointerAlignment(DL).value();
  3291. }
  3292. // Use only IR information if we did not strip anything.
  3293. T.takeKnownMaximum(Alignment);
  3294. T.indicatePessimisticFixpoint();
  3295. } else {
  3296. // Use abstract attribute information.
  3297. const AAAlign::StateType &DS = AA.getState();
  3298. T ^= DS;
  3299. }
  3300. return T.isValidState();
  3301. };
  3302. StateType T;
  3303. if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T,
  3304. VisitValueCB, getCtxI()))
  3305. return indicatePessimisticFixpoint();
  3306. // TODO: If we know we visited all incoming values, thus no are assumed
  3307. // dead, we can take the known information from the state T.
  3308. return clampStateAndIndicateChange(getState(), T);
  3309. }
  3310. /// See AbstractAttribute::trackStatistics()
  3311. void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
  3312. };
  3313. /// Align attribute for function return value.
  3314. struct AAAlignReturned final
  3315. : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
  3316. using Base = AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>;
  3317. AAAlignReturned(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
  3318. /// See AbstractAttribute::initialize(...).
  3319. void initialize(Attributor &A) override {
  3320. Base::initialize(A);
  3321. Function *F = getAssociatedFunction();
  3322. if (!F || F->isDeclaration())
  3323. indicatePessimisticFixpoint();
  3324. }
  3325. /// See AbstractAttribute::trackStatistics()
  3326. void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
  3327. };
  3328. /// Align attribute for function argument.
  3329. struct AAAlignArgument final
  3330. : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> {
  3331. using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>;
  3332. AAAlignArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
  3333. /// See AbstractAttribute::manifest(...).
  3334. ChangeStatus manifest(Attributor &A) override {
  3335. // If the associated argument is involved in a must-tail call we give up
  3336. // because we would need to keep the argument alignments of caller and
  3337. // callee in-sync. Just does not seem worth the trouble right now.
  3338. if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
  3339. return ChangeStatus::UNCHANGED;
  3340. return Base::manifest(A);
  3341. }
  3342. /// See AbstractAttribute::trackStatistics()
  3343. void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) }
  3344. };
  3345. struct AAAlignCallSiteArgument final : AAAlignFloating {
  3346. AAAlignCallSiteArgument(const IRPosition &IRP, Attributor &A)
  3347. : AAAlignFloating(IRP, A) {}
  3348. /// See AbstractAttribute::manifest(...).
  3349. ChangeStatus manifest(Attributor &A) override {
  3350. // If the associated argument is involved in a must-tail call we give up
  3351. // because we would need to keep the argument alignments of caller and
  3352. // callee in-sync. Just does not seem worth the trouble right now.
  3353. if (Argument *Arg = getAssociatedArgument())
  3354. if (A.getInfoCache().isInvolvedInMustTailCall(*Arg))
  3355. return ChangeStatus::UNCHANGED;
  3356. ChangeStatus Changed = AAAlignImpl::manifest(A);
  3357. Align InheritAlign =
  3358. getAssociatedValue().getPointerAlignment(A.getDataLayout());
  3359. if (InheritAlign >= getAssumedAlign())
  3360. Changed = ChangeStatus::UNCHANGED;
  3361. return Changed;
  3362. }
  3363. /// See AbstractAttribute::updateImpl(Attributor &A).
  3364. ChangeStatus updateImpl(Attributor &A) override {
  3365. ChangeStatus Changed = AAAlignFloating::updateImpl(A);
  3366. if (Argument *Arg = getAssociatedArgument()) {
  3367. // We only take known information from the argument
  3368. // so we do not need to track a dependence.
  3369. const auto &ArgAlignAA = A.getAAFor<AAAlign>(
  3370. *this, IRPosition::argument(*Arg), /* TrackDependence */ false);
  3371. takeKnownMaximum(ArgAlignAA.getKnownAlign());
  3372. }
  3373. return Changed;
  3374. }
  3375. /// See AbstractAttribute::trackStatistics()
  3376. void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
  3377. };
  3378. /// Align attribute deduction for a call site return value.
  3379. struct AAAlignCallSiteReturned final
  3380. : AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl> {
  3381. using Base = AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl>;
  3382. AAAlignCallSiteReturned(const IRPosition &IRP, Attributor &A)
  3383. : Base(IRP, A) {}
  3384. /// See AbstractAttribute::initialize(...).
  3385. void initialize(Attributor &A) override {
  3386. Base::initialize(A);
  3387. Function *F = getAssociatedFunction();
  3388. if (!F || F->isDeclaration())
  3389. indicatePessimisticFixpoint();
  3390. }
  3391. /// See AbstractAttribute::trackStatistics()
  3392. void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); }
  3393. };
  3394. /// ------------------ Function No-Return Attribute ----------------------------
  3395. struct AANoReturnImpl : public AANoReturn {
  3396. AANoReturnImpl(const IRPosition &IRP, Attributor &A) : AANoReturn(IRP, A) {}
  3397. /// See AbstractAttribute::initialize(...).
  3398. void initialize(Attributor &A) override {
  3399. AANoReturn::initialize(A);
  3400. Function *F = getAssociatedFunction();
  3401. if (!F || F->isDeclaration())
  3402. indicatePessimisticFixpoint();
  3403. }
  3404. /// See AbstractAttribute::getAsStr().
  3405. const std::string getAsStr() const override {
  3406. return getAssumed() ? "noreturn" : "may-return";
  3407. }
  3408. /// See AbstractAttribute::updateImpl(Attributor &A).
  3409. virtual ChangeStatus updateImpl(Attributor &A) override {
  3410. auto CheckForNoReturn = [](Instruction &) { return false; };
  3411. if (!A.checkForAllInstructions(CheckForNoReturn, *this,
  3412. {(unsigned)Instruction::Ret}))
  3413. return indicatePessimisticFixpoint();
  3414. return ChangeStatus::UNCHANGED;
  3415. }
  3416. };
  3417. struct AANoReturnFunction final : AANoReturnImpl {
  3418. AANoReturnFunction(const IRPosition &IRP, Attributor &A)
  3419. : AANoReturnImpl(IRP, A) {}
  3420. /// See AbstractAttribute::trackStatistics()
  3421. void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
  3422. };
  3423. /// NoReturn attribute deduction for a call sites.
  3424. struct AANoReturnCallSite final : AANoReturnImpl {
  3425. AANoReturnCallSite(const IRPosition &IRP, Attributor &A)
  3426. : AANoReturnImpl(IRP, A) {}
  3427. /// See AbstractAttribute::initialize(...).
  3428. void initialize(Attributor &A) override {
  3429. AANoReturnImpl::initialize(A);
  3430. if (Function *F = getAssociatedFunction()) {
  3431. const IRPosition &FnPos = IRPosition::function(*F);
  3432. auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos);
  3433. if (!FnAA.isAssumedNoReturn())
  3434. indicatePessimisticFixpoint();
  3435. }
  3436. }
  3437. /// See AbstractAttribute::updateImpl(...).
  3438. ChangeStatus updateImpl(Attributor &A) override {
  3439. // TODO: Once we have call site specific value information we can provide
  3440. // call site specific liveness information and then it makes
  3441. // sense to specialize attributes for call sites arguments instead of
  3442. // redirecting requests to the callee argument.
  3443. Function *F = getAssociatedFunction();
  3444. const IRPosition &FnPos = IRPosition::function(*F);
  3445. auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos);
  3446. return clampStateAndIndicateChange(getState(), FnAA.getState());
  3447. }
  3448. /// See AbstractAttribute::trackStatistics()
  3449. void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); }
  3450. };
  3451. /// ----------------------- Variable Capturing ---------------------------------
  3452. /// A class to hold the state of for no-capture attributes.
  3453. struct AANoCaptureImpl : public AANoCapture {
  3454. AANoCaptureImpl(const IRPosition &IRP, Attributor &A) : AANoCapture(IRP, A) {}
  3455. /// See AbstractAttribute::initialize(...).
  3456. void initialize(Attributor &A) override {
  3457. if (hasAttr(getAttrKind(), /* IgnoreSubsumingPositions */ true)) {
  3458. indicateOptimisticFixpoint();
  3459. return;
  3460. }
  3461. Function *AnchorScope = getAnchorScope();
  3462. if (isFnInterfaceKind() &&
  3463. (!AnchorScope || !A.isFunctionIPOAmendable(*AnchorScope))) {
  3464. indicatePessimisticFixpoint();
  3465. return;
  3466. }
  3467. // You cannot "capture" null in the default address space.
  3468. if (isa<ConstantPointerNull>(getAssociatedValue()) &&
  3469. getAssociatedValue().getType()->getPointerAddressSpace() == 0) {
  3470. indicateOptimisticFixpoint();
  3471. return;
  3472. }
  3473. const Function *F =
  3474. isArgumentPosition() ? getAssociatedFunction() : AnchorScope;
  3475. // Check what state the associated function can actually capture.
  3476. if (F)
  3477. determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
  3478. else
  3479. indicatePessimisticFixpoint();
  3480. }
  3481. /// See AbstractAttribute::updateImpl(...).
  3482. ChangeStatus updateImpl(Attributor &A) override;
  3483. /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...).
  3484. virtual void
  3485. getDeducedAttributes(LLVMContext &Ctx,
  3486. SmallVectorImpl<Attribute> &Attrs) const override {
  3487. if (!isAssumedNoCaptureMaybeReturned())
  3488. return;
  3489. if (isArgumentPosition()) {
  3490. if (isAssumedNoCapture())
  3491. Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture));
  3492. else if (ManifestInternal)
  3493. Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned"));
  3494. }
  3495. }
  3496. /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known
  3497. /// depending on the ability of the function associated with \p IRP to capture
  3498. /// state in memory and through "returning/throwing", respectively.
  3499. static void determineFunctionCaptureCapabilities(const IRPosition &IRP,
  3500. const Function &F,
  3501. BitIntegerState &State) {
  3502. // TODO: Once we have memory behavior attributes we should use them here.
  3503. // If we know we cannot communicate or write to memory, we do not care about
  3504. // ptr2int anymore.
  3505. if (F.onlyReadsMemory() && F.doesNotThrow() &&
  3506. F.getReturnType()->isVoidTy()) {
  3507. State.addKnownBits(NO_CAPTURE);
  3508. return;
  3509. }
  3510. // A function cannot capture state in memory if it only reads memory, it can
  3511. // however return/throw state and the state might be influenced by the
  3512. // pointer value, e.g., loading from a returned pointer might reveal a bit.
  3513. if (F.onlyReadsMemory())
  3514. State.addKnownBits(NOT_CAPTURED_IN_MEM);
  3515. // A function cannot communicate state back if it does not through
  3516. // exceptions and doesn not return values.
  3517. if (F.doesNotThrow() && F.getReturnType()->isVoidTy())
  3518. State.addKnownBits(NOT_CAPTURED_IN_RET);
  3519. // Check existing "returned" attributes.
  3520. int ArgNo = IRP.getCalleeArgNo();
  3521. if (F.doesNotThrow() && ArgNo >= 0) {
  3522. for (unsigned u = 0, e = F.arg_size(); u < e; ++u)
  3523. if (F.hasParamAttribute(u, Attribute::Returned)) {
  3524. if (u == unsigned(ArgNo))
  3525. State.removeAssumedBits(NOT_CAPTURED_IN_RET);
  3526. else if (F.onlyReadsMemory())
  3527. State.addKnownBits(NO_CAPTURE);
  3528. else
  3529. State.addKnownBits(NOT_CAPTURED_IN_RET);
  3530. break;
  3531. }
  3532. }
  3533. }
  3534. /// See AbstractState::getAsStr().
  3535. const std::string getAsStr() const override {
  3536. if (isKnownNoCapture())
  3537. return "known not-captured";
  3538. if (isAssumedNoCapture())
  3539. return "assumed not-captured";
  3540. if (isKnownNoCaptureMaybeReturned())
  3541. return "known not-captured-maybe-returned";
  3542. if (isAssumedNoCaptureMaybeReturned())
  3543. return "assumed not-captured-maybe-returned";
  3544. return "assumed-captured";
  3545. }
  3546. };
  3547. /// Attributor-aware capture tracker.
  3548. struct AACaptureUseTracker final : public CaptureTracker {
  3549. /// Create a capture tracker that can lookup in-flight abstract attributes
  3550. /// through the Attributor \p A.
  3551. ///
  3552. /// If a use leads to a potential capture, \p CapturedInMemory is set and the
  3553. /// search is stopped. If a use leads to a return instruction,
  3554. /// \p CommunicatedBack is set to true and \p CapturedInMemory is not changed.
  3555. /// If a use leads to a ptr2int which may capture the value,
  3556. /// \p CapturedInInteger is set. If a use is found that is currently assumed
  3557. /// "no-capture-maybe-returned", the user is added to the \p PotentialCopies
  3558. /// set. All values in \p PotentialCopies are later tracked as well. For every
  3559. /// explored use we decrement \p RemainingUsesToExplore. Once it reaches 0,
  3560. /// the search is stopped with \p CapturedInMemory and \p CapturedInInteger
  3561. /// conservatively set to true.
  3562. AACaptureUseTracker(Attributor &A, AANoCapture &NoCaptureAA,
  3563. const AAIsDead &IsDeadAA, AANoCapture::StateType &State,
  3564. SmallVectorImpl<const Value *> &PotentialCopies,
  3565. unsigned &RemainingUsesToExplore)
  3566. : A(A), NoCaptureAA(NoCaptureAA), IsDeadAA(IsDeadAA), State(State),
  3567. PotentialCopies(PotentialCopies),
  3568. RemainingUsesToExplore(RemainingUsesToExplore) {}
  3569. /// Determine if \p V maybe captured. *Also updates the state!*
  3570. bool valueMayBeCaptured(const Value *V) {
  3571. if (V->getType()->isPointerTy()) {
  3572. PointerMayBeCaptured(V, this);
  3573. } else {
  3574. State.indicatePessimisticFixpoint();
  3575. }
  3576. return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
  3577. }
  3578. /// See CaptureTracker::tooManyUses().
  3579. void tooManyUses() override {
  3580. State.removeAssumedBits(AANoCapture::NO_CAPTURE);
  3581. }
  3582. bool isDereferenceableOrNull(Value *O, const DataLayout &DL) override {
  3583. if (CaptureTracker::isDereferenceableOrNull(O, DL))
  3584. return true;
  3585. const auto &DerefAA = A.getAAFor<AADereferenceable>(
  3586. NoCaptureAA, IRPosition::value(*O), /* TrackDependence */ true,
  3587. DepClassTy::OPTIONAL);
  3588. return DerefAA.getAssumedDereferenceableBytes();
  3589. }
  3590. /// See CaptureTracker::captured(...).
  3591. bool captured(const Use *U) override {
  3592. Instruction *UInst = cast<Instruction>(U->getUser());
  3593. LLVM_DEBUG(dbgs() << "Check use: " << *U->get() << " in " << *UInst
  3594. << "\n");
  3595. // Because we may reuse the tracker multiple times we keep track of the
  3596. // number of explored uses ourselves as well.
  3597. if (RemainingUsesToExplore-- == 0) {
  3598. LLVM_DEBUG(dbgs() << " - too many uses to explore!\n");
  3599. return isCapturedIn(/* Memory */ true, /* Integer */ true,
  3600. /* Return */ true);
  3601. }
  3602. // Deal with ptr2int by following uses.
  3603. if (isa<PtrToIntInst>(UInst)) {
  3604. LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n");
  3605. return valueMayBeCaptured(UInst);
  3606. }
  3607. // Explicitly catch return instructions.
  3608. if (isa<ReturnInst>(UInst))
  3609. return isCapturedIn(/* Memory */ false, /* Integer */ false,
  3610. /* Return */ true);
  3611. // For now we only use special logic for call sites. However, the tracker
  3612. // itself knows about a lot of other non-capturing cases already.
  3613. auto *CB = dyn_cast<CallBase>(UInst);
  3614. if (!CB || !CB->isArgOperand(U))
  3615. return isCapturedIn(/* Memory */ true, /* Integer */ true,
  3616. /* Return */ true);
  3617. unsigned ArgNo = CB->getArgOperandNo(U);
  3618. const IRPosition &CSArgPos = IRPosition::callsite_argument(*CB, ArgNo);
  3619. // If we have a abstract no-capture attribute for the argument we can use
  3620. // it to justify a non-capture attribute here. This allows recursion!
  3621. auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(NoCaptureAA, CSArgPos);
  3622. if (ArgNoCaptureAA.isAssumedNoCapture())
  3623. return isCapturedIn(/* Memory */ false, /* Integer */ false,
  3624. /* Return */ false);
  3625. if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
  3626. addPotentialCopy(*CB);
  3627. return isCapturedIn(/* Memory */ false, /* Integer */ false,
  3628. /* Return */ false);
  3629. }
  3630. // Lastly, we could not find a reason no-capture can be assumed so we don't.
  3631. return isCapturedIn(/* Memory */ true, /* Integer */ true,
  3632. /* Return */ true);
  3633. }
  3634. /// Register \p CS as potential copy of the value we are checking.
  3635. void addPotentialCopy(CallBase &CB) { PotentialCopies.push_back(&CB); }
  3636. /// See CaptureTracker::shouldExplore(...).
  3637. bool shouldExplore(const Use *U) override {
  3638. // Check liveness and ignore droppable users.
  3639. return !U->getUser()->isDroppable() &&
  3640. !A.isAssumedDead(*U, &NoCaptureAA, &IsDeadAA);
  3641. }
  3642. /// Update the state according to \p CapturedInMem, \p CapturedInInt, and
  3643. /// \p CapturedInRet, then return the appropriate value for use in the
  3644. /// CaptureTracker::captured() interface.
  3645. bool isCapturedIn(bool CapturedInMem, bool CapturedInInt,
  3646. bool CapturedInRet) {
  3647. LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int "
  3648. << CapturedInInt << "|Ret " << CapturedInRet << "]\n");
  3649. if (CapturedInMem)
  3650. State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM);
  3651. if (CapturedInInt)
  3652. State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT);
  3653. if (CapturedInRet)
  3654. State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET);
  3655. return !State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
  3656. }
  3657. private:
  3658. /// The attributor providing in-flight abstract attributes.
  3659. Attributor &A;
  3660. /// The abstract attribute currently updated.
  3661. AANoCapture &NoCaptureAA;
  3662. /// The abstract liveness state.
  3663. const AAIsDead &IsDeadAA;
  3664. /// The state currently updated.
  3665. AANoCapture::StateType &State;
  3666. /// Set of potential copies of the tracked value.
  3667. SmallVectorImpl<const Value *> &PotentialCopies;
  3668. /// Global counter to limit the number of explored uses.
  3669. unsigned &RemainingUsesToExplore;
  3670. };
  3671. ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) {
  3672. const IRPosition &IRP = getIRPosition();
  3673. const Value *V = isArgumentPosition() ? IRP.getAssociatedArgument()
  3674. : &IRP.getAssociatedValue();
  3675. if (!V)
  3676. return indicatePessimisticFixpoint();
  3677. const Function *F =
  3678. isArgumentPosition() ? IRP.getAssociatedFunction() : IRP.getAnchorScope();
  3679. assert(F && "Expected a function!");
  3680. const IRPosition &FnPos = IRPosition::function(*F);
  3681. const auto &IsDeadAA =
  3682. A.getAAFor<AAIsDead>(*this, FnPos, /* TrackDependence */ false);
  3683. AANoCapture::StateType T;
  3684. // Readonly means we cannot capture through memory.
  3685. const auto &FnMemAA =
  3686. A.getAAFor<AAMemoryBehavior>(*this, FnPos, /* TrackDependence */ false);
  3687. if (FnMemAA.isAssumedReadOnly()) {
  3688. T.addKnownBits(NOT_CAPTURED_IN_MEM);
  3689. if (FnMemAA.isKnownReadOnly())
  3690. addKnownBits(NOT_CAPTURED_IN_MEM);
  3691. else
  3692. A.recordDependence(FnMemAA, *this, DepClassTy::OPTIONAL);
  3693. }
  3694. // Make sure all returned values are different than the underlying value.
  3695. // TODO: we could do this in a more sophisticated way inside
  3696. // AAReturnedValues, e.g., track all values that escape through returns
  3697. // directly somehow.
  3698. auto CheckReturnedArgs = [&](const AAReturnedValues &RVAA) {
  3699. bool SeenConstant = false;
  3700. for (auto &It : RVAA.returned_values()) {
  3701. if (isa<Constant>(It.first)) {
  3702. if (SeenConstant)
  3703. return false;
  3704. SeenConstant = true;
  3705. } else if (!isa<Argument>(It.first) ||
  3706. It.first == getAssociatedArgument())
  3707. return false;
  3708. }
  3709. return true;
  3710. };
  3711. const auto &NoUnwindAA = A.getAAFor<AANoUnwind>(
  3712. *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
  3713. if (NoUnwindAA.isAssumedNoUnwind()) {
  3714. bool IsVoidTy = F->getReturnType()->isVoidTy();
  3715. const AAReturnedValues *RVAA =
  3716. IsVoidTy ? nullptr
  3717. : &A.getAAFor<AAReturnedValues>(*this, FnPos,
  3718. /* TrackDependence */ true,
  3719. DepClassTy::OPTIONAL);
  3720. if (IsVoidTy || CheckReturnedArgs(*RVAA)) {
  3721. T.addKnownBits(NOT_CAPTURED_IN_RET);
  3722. if (T.isKnown(NOT_CAPTURED_IN_MEM))
  3723. return ChangeStatus::UNCHANGED;
  3724. if (NoUnwindAA.isKnownNoUnwind() &&
  3725. (IsVoidTy || RVAA->getState().isAtFixpoint())) {
  3726. addKnownBits(NOT_CAPTURED_IN_RET);
  3727. if (isKnown(NOT_CAPTURED_IN_MEM))
  3728. return indicateOptimisticFixpoint();
  3729. }
  3730. }
  3731. }
  3732. // Use the CaptureTracker interface and logic with the specialized tracker,
  3733. // defined in AACaptureUseTracker, that can look at in-flight abstract
  3734. // attributes and directly updates the assumed state.
  3735. SmallVector<const Value *, 4> PotentialCopies;
  3736. unsigned RemainingUsesToExplore =
  3737. getDefaultMaxUsesToExploreForCaptureTracking();
  3738. AACaptureUseTracker Tracker(A, *this, IsDeadAA, T, PotentialCopies,
  3739. RemainingUsesToExplore);
  3740. // Check all potential copies of the associated value until we can assume
  3741. // none will be captured or we have to assume at least one might be.
  3742. unsigned Idx = 0;
  3743. PotentialCopies.push_back(V);
  3744. while (T.isAssumed(NO_CAPTURE_MAYBE_RETURNED) && Idx < PotentialCopies.size())
  3745. Tracker.valueMayBeCaptured(PotentialCopies[Idx++]);
  3746. AANoCapture::StateType &S = getState();
  3747. auto Assumed = S.getAssumed();
  3748. S.intersectAssumedBits(T.getAssumed());
  3749. if (!isAssumedNoCaptureMaybeReturned())
  3750. return indicatePessimisticFixpoint();
  3751. return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
  3752. : ChangeStatus::CHANGED;
  3753. }
  3754. /// NoCapture attribute for function arguments.
  3755. struct AANoCaptureArgument final : AANoCaptureImpl {
  3756. AANoCaptureArgument(const IRPosition &IRP, Attributor &A)
  3757. : AANoCaptureImpl(IRP, A) {}
  3758. /// See AbstractAttribute::trackStatistics()
  3759. void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) }
  3760. };
  3761. /// NoCapture attribute for call site arguments.
  3762. struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
  3763. AANoCaptureCallSiteArgument(const IRPosition &IRP, Attributor &A)
  3764. : AANoCaptureImpl(IRP, A) {}
  3765. /// See AbstractAttribute::initialize(...).
  3766. void initialize(Attributor &A) override {
  3767. if (Argument *Arg = getAssociatedArgument())
  3768. if (Arg->hasByValAttr())
  3769. indicateOptimisticFixpoint();
  3770. AANoCaptureImpl::initialize(A);
  3771. }
  3772. /// See AbstractAttribute::updateImpl(...).
  3773. ChangeStatus updateImpl(Attributor &A) override {
  3774. // TODO: Once we have call site specific value information we can provide
  3775. // call site specific liveness information and then it makes
  3776. // sense to specialize attributes for call sites arguments instead of
  3777. // redirecting requests to the callee argument.
  3778. Argument *Arg = getAssociatedArgument();
  3779. if (!Arg)
  3780. return indicatePessimisticFixpoint();
  3781. const IRPosition &ArgPos = IRPosition::argument(*Arg);
  3782. auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos);
  3783. return clampStateAndIndicateChange(getState(), ArgAA.getState());
  3784. }
  3785. /// See AbstractAttribute::trackStatistics()
  3786. void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)};
  3787. };
  3788. /// NoCapture attribute for floating values.
  3789. struct AANoCaptureFloating final : AANoCaptureImpl {
  3790. AANoCaptureFloating(const IRPosition &IRP, Attributor &A)
  3791. : AANoCaptureImpl(IRP, A) {}
  3792. /// See AbstractAttribute::trackStatistics()
  3793. void trackStatistics() const override {
  3794. STATS_DECLTRACK_FLOATING_ATTR(nocapture)
  3795. }
  3796. };
  3797. /// NoCapture attribute for function return value.
  3798. struct AANoCaptureReturned final : AANoCaptureImpl {
  3799. AANoCaptureReturned(const IRPosition &IRP, Attributor &A)
  3800. : AANoCaptureImpl(IRP, A) {
  3801. llvm_unreachable("NoCapture is not applicable to function returns!");
  3802. }
  3803. /// See AbstractAttribute::initialize(...).
  3804. void initialize(Attributor &A) override {
  3805. llvm_unreachable("NoCapture is not applicable to function returns!");
  3806. }
  3807. /// See AbstractAttribute::updateImpl(...).
  3808. ChangeStatus updateImpl(Attributor &A) override {
  3809. llvm_unreachable("NoCapture is not applicable to function returns!");
  3810. }
  3811. /// See AbstractAttribute::trackStatistics()
  3812. void trackStatistics() const override {}
  3813. };
  3814. /// NoCapture attribute deduction for a call site return value.
  3815. struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
  3816. AANoCaptureCallSiteReturned(const IRPosition &IRP, Attributor &A)
  3817. : AANoCaptureImpl(IRP, A) {}
  3818. /// See AbstractAttribute::trackStatistics()
  3819. void trackStatistics() const override {
  3820. STATS_DECLTRACK_CSRET_ATTR(nocapture)
  3821. }
  3822. };
  3823. /// ------------------ Value Simplify Attribute ----------------------------
  3824. struct AAValueSimplifyImpl : AAValueSimplify {
  3825. AAValueSimplifyImpl(const IRPosition &IRP, Attributor &A)
  3826. : AAValueSimplify(IRP, A) {}
  3827. /// See AbstractAttribute::initialize(...).
  3828. void initialize(Attributor &A) override {
  3829. if (getAssociatedValue().getType()->isVoidTy())
  3830. indicatePessimisticFixpoint();
  3831. }
  3832. /// See AbstractAttribute::getAsStr().
  3833. const std::string getAsStr() const override {
  3834. return getAssumed() ? (getKnown() ? "simplified" : "maybe-simple")
  3835. : "not-simple";
  3836. }
  3837. /// See AbstractAttribute::trackStatistics()
  3838. void trackStatistics() const override {}
  3839. /// See AAValueSimplify::getAssumedSimplifiedValue()
  3840. Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override {
  3841. if (!getAssumed())
  3842. return const_cast<Value *>(&getAssociatedValue());
  3843. return SimplifiedAssociatedValue;
  3844. }
  3845. /// Helper function for querying AAValueSimplify and updating candicate.
  3846. /// \param QueryingValue Value trying to unify with SimplifiedValue
  3847. /// \param AccumulatedSimplifiedValue Current simplification result.
  3848. static bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA,
  3849. Value &QueryingValue,
  3850. Optional<Value *> &AccumulatedSimplifiedValue) {
  3851. // FIXME: Add a typecast support.
  3852. auto &ValueSimplifyAA = A.getAAFor<AAValueSimplify>(
  3853. QueryingAA, IRPosition::value(QueryingValue));
  3854. Optional<Value *> QueryingValueSimplified =
  3855. ValueSimplifyAA.getAssumedSimplifiedValue(A);
  3856. if (!QueryingValueSimplified.hasValue())
  3857. return true;
  3858. if (!QueryingValueSimplified.getValue())
  3859. return false;
  3860. Value &QueryingValueSimplifiedUnwrapped =
  3861. *QueryingValueSimplified.getValue();
  3862. if (AccumulatedSimplifiedValue.hasValue() &&
  3863. !isa<UndefValue>(AccumulatedSimplifiedValue.getValue()) &&
  3864. !isa<UndefValue>(QueryingValueSimplifiedUnwrapped))
  3865. return AccumulatedSimplifiedValue == QueryingValueSimplified;
  3866. if (AccumulatedSimplifiedValue.hasValue() &&
  3867. isa<UndefValue>(QueryingValueSimplifiedUnwrapped))
  3868. return true;
  3869. LLVM_DEBUG(dbgs() << "[ValueSimplify] " << QueryingValue
  3870. << " is assumed to be "
  3871. << QueryingValueSimplifiedUnwrapped << "\n");
  3872. AccumulatedSimplifiedValue = QueryingValueSimplified;
  3873. return true;
  3874. }
  3875. /// Returns a candidate is found or not
  3876. template <typename AAType> bool askSimplifiedValueFor(Attributor &A) {
  3877. if (!getAssociatedValue().getType()->isIntegerTy())
  3878. return false;
  3879. const auto &AA =
  3880. A.getAAFor<AAType>(*this, getIRPosition(), /* TrackDependence */ false);
  3881. Optional<ConstantInt *> COpt = AA.getAssumedConstantInt(A);
  3882. if (!COpt.hasValue()) {
  3883. SimplifiedAssociatedValue = llvm::None;
  3884. A.recordDependence(AA, *this, DepClassTy::OPTIONAL);
  3885. return true;
  3886. }
  3887. if (auto *C = COpt.getValue()) {
  3888. SimplifiedAssociatedValue = C;
  3889. A.recordDependence(AA, *this, DepClassTy::OPTIONAL);
  3890. return true;
  3891. }
  3892. return false;
  3893. }
  3894. bool askSimplifiedValueForOtherAAs(Attributor &A) {
  3895. if (askSimplifiedValueFor<AAValueConstantRange>(A))
  3896. return true;
  3897. if (askSimplifiedValueFor<AAPotentialValues>(A))
  3898. return true;
  3899. return false;
  3900. }
  3901. /// See AbstractAttribute::manifest(...).
  3902. ChangeStatus manifest(Attributor &A) override {
  3903. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  3904. if (SimplifiedAssociatedValue.hasValue() &&
  3905. !SimplifiedAssociatedValue.getValue())
  3906. return Changed;
  3907. Value &V = getAssociatedValue();
  3908. auto *C = SimplifiedAssociatedValue.hasValue()
  3909. ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
  3910. : UndefValue::get(V.getType());
  3911. if (C) {
  3912. // We can replace the AssociatedValue with the constant.
  3913. if (!V.user_empty() && &V != C && V.getType() == C->getType()) {
  3914. LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *C
  3915. << " :: " << *this << "\n");
  3916. if (A.changeValueAfterManifest(V, *C))
  3917. Changed = ChangeStatus::CHANGED;
  3918. }
  3919. }
  3920. return Changed | AAValueSimplify::manifest(A);
  3921. }
  3922. /// See AbstractState::indicatePessimisticFixpoint(...).
  3923. ChangeStatus indicatePessimisticFixpoint() override {
  3924. // NOTE: Associated value will be returned in a pessimistic fixpoint and is
  3925. // regarded as known. That's why`indicateOptimisticFixpoint` is called.
  3926. SimplifiedAssociatedValue = &getAssociatedValue();
  3927. indicateOptimisticFixpoint();
  3928. return ChangeStatus::CHANGED;
  3929. }
  3930. protected:
  3931. // An assumed simplified value. Initially, it is set to Optional::None, which
  3932. // means that the value is not clear under current assumption. If in the
  3933. // pessimistic state, getAssumedSimplifiedValue doesn't return this value but
  3934. // returns orignal associated value.
  3935. Optional<Value *> SimplifiedAssociatedValue;
  3936. };
  3937. struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
  3938. AAValueSimplifyArgument(const IRPosition &IRP, Attributor &A)
  3939. : AAValueSimplifyImpl(IRP, A) {}
  3940. void initialize(Attributor &A) override {
  3941. AAValueSimplifyImpl::initialize(A);
  3942. if (!getAnchorScope() || getAnchorScope()->isDeclaration())
  3943. indicatePessimisticFixpoint();
  3944. if (hasAttr({Attribute::InAlloca, Attribute::Preallocated,
  3945. Attribute::StructRet, Attribute::Nest},
  3946. /* IgnoreSubsumingPositions */ true))
  3947. indicatePessimisticFixpoint();
  3948. // FIXME: This is a hack to prevent us from propagating function poiner in
  3949. // the new pass manager CGSCC pass as it creates call edges the
  3950. // CallGraphUpdater cannot handle yet.
  3951. Value &V = getAssociatedValue();
  3952. if (V.getType()->isPointerTy() &&
  3953. V.getType()->getPointerElementType()->isFunctionTy() &&
  3954. !A.isModulePass())
  3955. indicatePessimisticFixpoint();
  3956. }
  3957. /// See AbstractAttribute::updateImpl(...).
  3958. ChangeStatus updateImpl(Attributor &A) override {
  3959. // Byval is only replacable if it is readonly otherwise we would write into
  3960. // the replaced value and not the copy that byval creates implicitly.
  3961. Argument *Arg = getAssociatedArgument();
  3962. if (Arg->hasByValAttr()) {
  3963. // TODO: We probably need to verify synchronization is not an issue, e.g.,
  3964. // there is no race by not copying a constant byval.
  3965. const auto &MemAA = A.getAAFor<AAMemoryBehavior>(*this, getIRPosition());
  3966. if (!MemAA.isAssumedReadOnly())
  3967. return indicatePessimisticFixpoint();
  3968. }
  3969. bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
  3970. auto PredForCallSite = [&](AbstractCallSite ACS) {
  3971. const IRPosition &ACSArgPos =
  3972. IRPosition::callsite_argument(ACS, getCallSiteArgNo());
  3973. // Check if a coresponding argument was found or if it is on not
  3974. // associated (which can happen for callback calls).
  3975. if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
  3976. return false;
  3977. // We can only propagate thread independent values through callbacks.
  3978. // This is different to direct/indirect call sites because for them we
  3979. // know the thread executing the caller and callee is the same. For
  3980. // callbacks this is not guaranteed, thus a thread dependent value could
  3981. // be different for the caller and callee, making it invalid to propagate.
  3982. Value &ArgOp = ACSArgPos.getAssociatedValue();
  3983. if (ACS.isCallbackCall())
  3984. if (auto *C = dyn_cast<Constant>(&ArgOp))
  3985. if (C->isThreadDependent())
  3986. return false;
  3987. return checkAndUpdate(A, *this, ArgOp, SimplifiedAssociatedValue);
  3988. };
  3989. bool AllCallSitesKnown;
  3990. if (!A.checkForAllCallSites(PredForCallSite, *this, true,
  3991. AllCallSitesKnown))
  3992. if (!askSimplifiedValueForOtherAAs(A))
  3993. return indicatePessimisticFixpoint();
  3994. // If a candicate was found in this update, return CHANGED.
  3995. return HasValueBefore == SimplifiedAssociatedValue.hasValue()
  3996. ? ChangeStatus::UNCHANGED
  3997. : ChangeStatus ::CHANGED;
  3998. }
  3999. /// See AbstractAttribute::trackStatistics()
  4000. void trackStatistics() const override {
  4001. STATS_DECLTRACK_ARG_ATTR(value_simplify)
  4002. }
  4003. };
  4004. struct AAValueSimplifyReturned : AAValueSimplifyImpl {
  4005. AAValueSimplifyReturned(const IRPosition &IRP, Attributor &A)
  4006. : AAValueSimplifyImpl(IRP, A) {}
  4007. /// See AbstractAttribute::updateImpl(...).
  4008. ChangeStatus updateImpl(Attributor &A) override {
  4009. bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
  4010. auto PredForReturned = [&](Value &V) {
  4011. return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue);
  4012. };
  4013. if (!A.checkForAllReturnedValues(PredForReturned, *this))
  4014. if (!askSimplifiedValueForOtherAAs(A))
  4015. return indicatePessimisticFixpoint();
  4016. // If a candicate was found in this update, return CHANGED.
  4017. return HasValueBefore == SimplifiedAssociatedValue.hasValue()
  4018. ? ChangeStatus::UNCHANGED
  4019. : ChangeStatus ::CHANGED;
  4020. }
  4021. ChangeStatus manifest(Attributor &A) override {
  4022. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  4023. if (SimplifiedAssociatedValue.hasValue() &&
  4024. !SimplifiedAssociatedValue.getValue())
  4025. return Changed;
  4026. Value &V = getAssociatedValue();
  4027. auto *C = SimplifiedAssociatedValue.hasValue()
  4028. ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
  4029. : UndefValue::get(V.getType());
  4030. if (C) {
  4031. auto PredForReturned =
  4032. [&](Value &V, const SmallSetVector<ReturnInst *, 4> &RetInsts) {
  4033. // We can replace the AssociatedValue with the constant.
  4034. if (&V == C || V.getType() != C->getType() || isa<UndefValue>(V))
  4035. return true;
  4036. for (ReturnInst *RI : RetInsts) {
  4037. if (RI->getFunction() != getAnchorScope())
  4038. continue;
  4039. auto *RC = C;
  4040. if (RC->getType() != RI->getReturnValue()->getType())
  4041. RC = ConstantExpr::getBitCast(RC,
  4042. RI->getReturnValue()->getType());
  4043. LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *RC
  4044. << " in " << *RI << " :: " << *this << "\n");
  4045. if (A.changeUseAfterManifest(RI->getOperandUse(0), *RC))
  4046. Changed = ChangeStatus::CHANGED;
  4047. }
  4048. return true;
  4049. };
  4050. A.checkForAllReturnedValuesAndReturnInsts(PredForReturned, *this);
  4051. }
  4052. return Changed | AAValueSimplify::manifest(A);
  4053. }
  4054. /// See AbstractAttribute::trackStatistics()
  4055. void trackStatistics() const override {
  4056. STATS_DECLTRACK_FNRET_ATTR(value_simplify)
  4057. }
  4058. };
  4059. struct AAValueSimplifyFloating : AAValueSimplifyImpl {
  4060. AAValueSimplifyFloating(const IRPosition &IRP, Attributor &A)
  4061. : AAValueSimplifyImpl(IRP, A) {}
  4062. /// See AbstractAttribute::initialize(...).
  4063. void initialize(Attributor &A) override {
  4064. // FIXME: This might have exposed a SCC iterator update bug in the old PM.
  4065. // Needs investigation.
  4066. // AAValueSimplifyImpl::initialize(A);
  4067. Value &V = getAnchorValue();
  4068. // TODO: add other stuffs
  4069. if (isa<Constant>(V))
  4070. indicatePessimisticFixpoint();
  4071. }
  4072. /// Check if \p ICmp is an equality comparison (==/!=) with at least one
  4073. /// nullptr. If so, try to simplify it using AANonNull on the other operand.
  4074. /// Return true if successful, in that case SimplifiedAssociatedValue will be
  4075. /// updated and \p Changed is set appropriately.
  4076. bool checkForNullPtrCompare(Attributor &A, ICmpInst *ICmp,
  4077. ChangeStatus &Changed) {
  4078. if (!ICmp)
  4079. return false;
  4080. if (!ICmp->isEquality())
  4081. return false;
  4082. // This is a comparison with == or !-. We check for nullptr now.
  4083. bool Op0IsNull = isa<ConstantPointerNull>(ICmp->getOperand(0));
  4084. bool Op1IsNull = isa<ConstantPointerNull>(ICmp->getOperand(1));
  4085. if (!Op0IsNull && !Op1IsNull)
  4086. return false;
  4087. LLVMContext &Ctx = ICmp->getContext();
  4088. // Check for `nullptr ==/!= nullptr` first:
  4089. if (Op0IsNull && Op1IsNull) {
  4090. Value *NewVal = ConstantInt::get(
  4091. Type::getInt1Ty(Ctx), ICmp->getPredicate() == CmpInst::ICMP_EQ);
  4092. assert(!SimplifiedAssociatedValue.hasValue() &&
  4093. "Did not expect non-fixed value for constant comparison");
  4094. SimplifiedAssociatedValue = NewVal;
  4095. indicateOptimisticFixpoint();
  4096. Changed = ChangeStatus::CHANGED;
  4097. return true;
  4098. }
  4099. // Left is the nullptr ==/!= non-nullptr case. We'll use AANonNull on the
  4100. // non-nullptr operand and if we assume it's non-null we can conclude the
  4101. // result of the comparison.
  4102. assert((Op0IsNull || Op1IsNull) &&
  4103. "Expected nullptr versus non-nullptr comparison at this point");
  4104. // The index is the operand that we assume is not null.
  4105. unsigned PtrIdx = Op0IsNull;
  4106. auto &PtrNonNullAA = A.getAAFor<AANonNull>(
  4107. *this, IRPosition::value(*ICmp->getOperand(PtrIdx)));
  4108. if (!PtrNonNullAA.isAssumedNonNull())
  4109. return false;
  4110. // The new value depends on the predicate, true for != and false for ==.
  4111. Value *NewVal = ConstantInt::get(Type::getInt1Ty(Ctx),
  4112. ICmp->getPredicate() == CmpInst::ICMP_NE);
  4113. assert((!SimplifiedAssociatedValue.hasValue() ||
  4114. SimplifiedAssociatedValue == NewVal) &&
  4115. "Did not expect to change value for zero-comparison");
  4116. bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
  4117. SimplifiedAssociatedValue = NewVal;
  4118. if (PtrNonNullAA.isKnownNonNull())
  4119. indicateOptimisticFixpoint();
  4120. Changed = HasValueBefore ? ChangeStatus::UNCHANGED : ChangeStatus ::CHANGED;
  4121. return true;
  4122. }
  4123. /// See AbstractAttribute::updateImpl(...).
  4124. ChangeStatus updateImpl(Attributor &A) override {
  4125. bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
  4126. ChangeStatus Changed;
  4127. if (checkForNullPtrCompare(A, dyn_cast<ICmpInst>(&getAnchorValue()),
  4128. Changed))
  4129. return Changed;
  4130. auto VisitValueCB = [&](Value &V, const Instruction *CtxI, bool &,
  4131. bool Stripped) -> bool {
  4132. auto &AA = A.getAAFor<AAValueSimplify>(*this, IRPosition::value(V));
  4133. if (!Stripped && this == &AA) {
  4134. // TODO: Look the instruction and check recursively.
  4135. LLVM_DEBUG(dbgs() << "[ValueSimplify] Can't be stripped more : " << V
  4136. << "\n");
  4137. return false;
  4138. }
  4139. return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue);
  4140. };
  4141. bool Dummy = false;
  4142. if (!genericValueTraversal<AAValueSimplify, bool>(
  4143. A, getIRPosition(), *this, Dummy, VisitValueCB, getCtxI(),
  4144. /* UseValueSimplify */ false))
  4145. if (!askSimplifiedValueForOtherAAs(A))
  4146. return indicatePessimisticFixpoint();
  4147. // If a candicate was found in this update, return CHANGED.
  4148. return HasValueBefore == SimplifiedAssociatedValue.hasValue()
  4149. ? ChangeStatus::UNCHANGED
  4150. : ChangeStatus ::CHANGED;
  4151. }
  4152. /// See AbstractAttribute::trackStatistics()
  4153. void trackStatistics() const override {
  4154. STATS_DECLTRACK_FLOATING_ATTR(value_simplify)
  4155. }
  4156. };
  4157. struct AAValueSimplifyFunction : AAValueSimplifyImpl {
  4158. AAValueSimplifyFunction(const IRPosition &IRP, Attributor &A)
  4159. : AAValueSimplifyImpl(IRP, A) {}
  4160. /// See AbstractAttribute::initialize(...).
  4161. void initialize(Attributor &A) override {
  4162. SimplifiedAssociatedValue = &getAnchorValue();
  4163. indicateOptimisticFixpoint();
  4164. }
  4165. /// See AbstractAttribute::initialize(...).
  4166. ChangeStatus updateImpl(Attributor &A) override {
  4167. llvm_unreachable(
  4168. "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
  4169. }
  4170. /// See AbstractAttribute::trackStatistics()
  4171. void trackStatistics() const override {
  4172. STATS_DECLTRACK_FN_ATTR(value_simplify)
  4173. }
  4174. };
  4175. struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
  4176. AAValueSimplifyCallSite(const IRPosition &IRP, Attributor &A)
  4177. : AAValueSimplifyFunction(IRP, A) {}
  4178. /// See AbstractAttribute::trackStatistics()
  4179. void trackStatistics() const override {
  4180. STATS_DECLTRACK_CS_ATTR(value_simplify)
  4181. }
  4182. };
  4183. struct AAValueSimplifyCallSiteReturned : AAValueSimplifyReturned {
  4184. AAValueSimplifyCallSiteReturned(const IRPosition &IRP, Attributor &A)
  4185. : AAValueSimplifyReturned(IRP, A) {}
  4186. /// See AbstractAttribute::manifest(...).
  4187. ChangeStatus manifest(Attributor &A) override {
  4188. return AAValueSimplifyImpl::manifest(A);
  4189. }
  4190. void trackStatistics() const override {
  4191. STATS_DECLTRACK_CSRET_ATTR(value_simplify)
  4192. }
  4193. };
  4194. struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
  4195. AAValueSimplifyCallSiteArgument(const IRPosition &IRP, Attributor &A)
  4196. : AAValueSimplifyFloating(IRP, A) {}
  4197. /// See AbstractAttribute::manifest(...).
  4198. ChangeStatus manifest(Attributor &A) override {
  4199. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  4200. if (SimplifiedAssociatedValue.hasValue() &&
  4201. !SimplifiedAssociatedValue.getValue())
  4202. return Changed;
  4203. Value &V = getAssociatedValue();
  4204. auto *C = SimplifiedAssociatedValue.hasValue()
  4205. ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
  4206. : UndefValue::get(V.getType());
  4207. if (C) {
  4208. Use &U = cast<CallBase>(&getAnchorValue())
  4209. ->getArgOperandUse(getCallSiteArgNo());
  4210. // We can replace the AssociatedValue with the constant.
  4211. if (&V != C && V.getType() == C->getType()) {
  4212. if (A.changeUseAfterManifest(U, *C))
  4213. Changed = ChangeStatus::CHANGED;
  4214. }
  4215. }
  4216. return Changed | AAValueSimplify::manifest(A);
  4217. }
  4218. void trackStatistics() const override {
  4219. STATS_DECLTRACK_CSARG_ATTR(value_simplify)
  4220. }
  4221. };
  4222. /// ----------------------- Heap-To-Stack Conversion ---------------------------
  4223. struct AAHeapToStackImpl : public AAHeapToStack {
  4224. AAHeapToStackImpl(const IRPosition &IRP, Attributor &A)
  4225. : AAHeapToStack(IRP, A) {}
  4226. const std::string getAsStr() const override {
  4227. return "[H2S] Mallocs: " + std::to_string(MallocCalls.size());
  4228. }
  4229. ChangeStatus manifest(Attributor &A) override {
  4230. assert(getState().isValidState() &&
  4231. "Attempted to manifest an invalid state!");
  4232. ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
  4233. Function *F = getAnchorScope();
  4234. const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
  4235. for (Instruction *MallocCall : MallocCalls) {
  4236. // This malloc cannot be replaced.
  4237. if (BadMallocCalls.count(MallocCall))
  4238. continue;
  4239. for (Instruction *FreeCall : FreesForMalloc[MallocCall]) {
  4240. LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n");
  4241. A.deleteAfterManifest(*FreeCall);
  4242. HasChanged = ChangeStatus::CHANGED;
  4243. }
  4244. LLVM_DEBUG(dbgs() << "H2S: Removing malloc call: " << *MallocCall
  4245. << "\n");
  4246. Align Alignment;
  4247. Constant *Size;
  4248. if (isCallocLikeFn(MallocCall, TLI)) {
  4249. auto *Num = cast<ConstantInt>(MallocCall->getOperand(0));
  4250. auto *SizeT = cast<ConstantInt>(MallocCall->getOperand(1));
  4251. APInt TotalSize = SizeT->getValue() * Num->getValue();
  4252. Size =
  4253. ConstantInt::get(MallocCall->getOperand(0)->getType(), TotalSize);
  4254. } else if (isAlignedAllocLikeFn(MallocCall, TLI)) {
  4255. Size = cast<ConstantInt>(MallocCall->getOperand(1));
  4256. Alignment = MaybeAlign(cast<ConstantInt>(MallocCall->getOperand(0))
  4257. ->getValue()
  4258. .getZExtValue())
  4259. .valueOrOne();
  4260. } else {
  4261. Size = cast<ConstantInt>(MallocCall->getOperand(0));
  4262. }
  4263. unsigned AS = cast<PointerType>(MallocCall->getType())->getAddressSpace();
  4264. Instruction *AI =
  4265. new AllocaInst(Type::getInt8Ty(F->getContext()), AS, Size, Alignment,
  4266. "", MallocCall->getNextNode());
  4267. if (AI->getType() != MallocCall->getType())
  4268. AI = new BitCastInst(AI, MallocCall->getType(), "malloc_bc",
  4269. AI->getNextNode());
  4270. A.changeValueAfterManifest(*MallocCall, *AI);
  4271. if (auto *II = dyn_cast<InvokeInst>(MallocCall)) {
  4272. auto *NBB = II->getNormalDest();
  4273. BranchInst::Create(NBB, MallocCall->getParent());
  4274. A.deleteAfterManifest(*MallocCall);
  4275. } else {
  4276. A.deleteAfterManifest(*MallocCall);
  4277. }
  4278. // Zero out the allocated memory if it was a calloc.
  4279. if (isCallocLikeFn(MallocCall, TLI)) {
  4280. auto *BI = new BitCastInst(AI, MallocCall->getType(), "calloc_bc",
  4281. AI->getNextNode());
  4282. Value *Ops[] = {
  4283. BI, ConstantInt::get(F->getContext(), APInt(8, 0, false)), Size,
  4284. ConstantInt::get(Type::getInt1Ty(F->getContext()), false)};
  4285. Type *Tys[] = {BI->getType(), MallocCall->getOperand(0)->getType()};
  4286. Module *M = F->getParent();
  4287. Function *Fn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
  4288. CallInst::Create(Fn, Ops, "", BI->getNextNode());
  4289. }
  4290. HasChanged = ChangeStatus::CHANGED;
  4291. }
  4292. return HasChanged;
  4293. }
  4294. /// Collection of all malloc calls in a function.
  4295. SmallSetVector<Instruction *, 4> MallocCalls;
  4296. /// Collection of malloc calls that cannot be converted.
  4297. DenseSet<const Instruction *> BadMallocCalls;
  4298. /// A map for each malloc call to the set of associated free calls.
  4299. DenseMap<Instruction *, SmallPtrSet<Instruction *, 4>> FreesForMalloc;
  4300. ChangeStatus updateImpl(Attributor &A) override;
  4301. };
  4302. ChangeStatus AAHeapToStackImpl::updateImpl(Attributor &A) {
  4303. const Function *F = getAnchorScope();
  4304. const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
  4305. MustBeExecutedContextExplorer &Explorer =
  4306. A.getInfoCache().getMustBeExecutedContextExplorer();
  4307. auto FreeCheck = [&](Instruction &I) {
  4308. const auto &Frees = FreesForMalloc.lookup(&I);
  4309. if (Frees.size() != 1)
  4310. return false;
  4311. Instruction *UniqueFree = *Frees.begin();
  4312. return Explorer.findInContextOf(UniqueFree, I.getNextNode());
  4313. };
  4314. auto UsesCheck = [&](Instruction &I) {
  4315. bool ValidUsesOnly = true;
  4316. bool MustUse = true;
  4317. auto Pred = [&](const Use &U, bool &Follow) -> bool {
  4318. Instruction *UserI = cast<Instruction>(U.getUser());
  4319. if (isa<LoadInst>(UserI))
  4320. return true;
  4321. if (auto *SI = dyn_cast<StoreInst>(UserI)) {
  4322. if (SI->getValueOperand() == U.get()) {
  4323. LLVM_DEBUG(dbgs()
  4324. << "[H2S] escaping store to memory: " << *UserI << "\n");
  4325. ValidUsesOnly = false;
  4326. } else {
  4327. // A store into the malloc'ed memory is fine.
  4328. }
  4329. return true;
  4330. }
  4331. if (auto *CB = dyn_cast<CallBase>(UserI)) {
  4332. if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd())
  4333. return true;
  4334. // Record malloc.
  4335. if (isFreeCall(UserI, TLI)) {
  4336. if (MustUse) {
  4337. FreesForMalloc[&I].insert(UserI);
  4338. } else {
  4339. LLVM_DEBUG(dbgs() << "[H2S] free potentially on different mallocs: "
  4340. << *UserI << "\n");
  4341. ValidUsesOnly = false;
  4342. }
  4343. return true;
  4344. }
  4345. unsigned ArgNo = CB->getArgOperandNo(&U);
  4346. const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
  4347. *this, IRPosition::callsite_argument(*CB, ArgNo));
  4348. // If a callsite argument use is nofree, we are fine.
  4349. const auto &ArgNoFreeAA = A.getAAFor<AANoFree>(
  4350. *this, IRPosition::callsite_argument(*CB, ArgNo));
  4351. if (!NoCaptureAA.isAssumedNoCapture() ||
  4352. !ArgNoFreeAA.isAssumedNoFree()) {
  4353. LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n");
  4354. ValidUsesOnly = false;
  4355. }
  4356. return true;
  4357. }
  4358. if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
  4359. isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
  4360. MustUse &= !(isa<PHINode>(UserI) || isa<SelectInst>(UserI));
  4361. Follow = true;
  4362. return true;
  4363. }
  4364. // Unknown user for which we can not track uses further (in a way that
  4365. // makes sense).
  4366. LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n");
  4367. ValidUsesOnly = false;
  4368. return true;
  4369. };
  4370. A.checkForAllUses(Pred, *this, I);
  4371. return ValidUsesOnly;
  4372. };
  4373. auto MallocCallocCheck = [&](Instruction &I) {
  4374. if (BadMallocCalls.count(&I))
  4375. return true;
  4376. bool IsMalloc = isMallocLikeFn(&I, TLI);
  4377. bool IsAlignedAllocLike = isAlignedAllocLikeFn(&I, TLI);
  4378. bool IsCalloc = !IsMalloc && isCallocLikeFn(&I, TLI);
  4379. if (!IsMalloc && !IsAlignedAllocLike && !IsCalloc) {
  4380. BadMallocCalls.insert(&I);
  4381. return true;
  4382. }
  4383. if (IsMalloc) {
  4384. if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(0)))
  4385. if (Size->getValue().ule(MaxHeapToStackSize))
  4386. if (UsesCheck(I) || FreeCheck(I)) {
  4387. MallocCalls.insert(&I);
  4388. return true;
  4389. }
  4390. } else if (IsAlignedAllocLike && isa<ConstantInt>(I.getOperand(0))) {
  4391. // Only if the alignment and sizes are constant.
  4392. if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1)))
  4393. if (Size->getValue().ule(MaxHeapToStackSize))
  4394. if (UsesCheck(I) || FreeCheck(I)) {
  4395. MallocCalls.insert(&I);
  4396. return true;
  4397. }
  4398. } else if (IsCalloc) {
  4399. bool Overflow = false;
  4400. if (auto *Num = dyn_cast<ConstantInt>(I.getOperand(0)))
  4401. if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1)))
  4402. if ((Size->getValue().umul_ov(Num->getValue(), Overflow))
  4403. .ule(MaxHeapToStackSize))
  4404. if (!Overflow && (UsesCheck(I) || FreeCheck(I))) {
  4405. MallocCalls.insert(&I);
  4406. return true;
  4407. }
  4408. }
  4409. BadMallocCalls.insert(&I);
  4410. return true;
  4411. };
  4412. size_t NumBadMallocs = BadMallocCalls.size();
  4413. A.checkForAllCallLikeInstructions(MallocCallocCheck, *this);
  4414. if (NumBadMallocs != BadMallocCalls.size())
  4415. return ChangeStatus::CHANGED;
  4416. return ChangeStatus::UNCHANGED;
  4417. }
  4418. struct AAHeapToStackFunction final : public AAHeapToStackImpl {
  4419. AAHeapToStackFunction(const IRPosition &IRP, Attributor &A)
  4420. : AAHeapToStackImpl(IRP, A) {}
  4421. /// See AbstractAttribute::trackStatistics().
  4422. void trackStatistics() const override {
  4423. STATS_DECL(
  4424. MallocCalls, Function,
  4425. "Number of malloc/calloc/aligned_alloc calls converted to allocas");
  4426. for (auto *C : MallocCalls)
  4427. if (!BadMallocCalls.count(C))
  4428. ++BUILD_STAT_NAME(MallocCalls, Function);
  4429. }
  4430. };
  4431. /// ----------------------- Privatizable Pointers ------------------------------
  4432. struct AAPrivatizablePtrImpl : public AAPrivatizablePtr {
  4433. AAPrivatizablePtrImpl(const IRPosition &IRP, Attributor &A)
  4434. : AAPrivatizablePtr(IRP, A), PrivatizableType(llvm::None) {}
  4435. ChangeStatus indicatePessimisticFixpoint() override {
  4436. AAPrivatizablePtr::indicatePessimisticFixpoint();
  4437. PrivatizableType = nullptr;
  4438. return ChangeStatus::CHANGED;
  4439. }
  4440. /// Identify the type we can chose for a private copy of the underlying
  4441. /// argument. None means it is not clear yet, nullptr means there is none.
  4442. virtual Optional<Type *> identifyPrivatizableType(Attributor &A) = 0;
  4443. /// Return a privatizable type that encloses both T0 and T1.
  4444. /// TODO: This is merely a stub for now as we should manage a mapping as well.
  4445. Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) {
  4446. if (!T0.hasValue())
  4447. return T1;
  4448. if (!T1.hasValue())
  4449. return T0;
  4450. if (T0 == T1)
  4451. return T0;
  4452. return nullptr;
  4453. }
  4454. Optional<Type *> getPrivatizableType() const override {
  4455. return PrivatizableType;
  4456. }
  4457. const std::string getAsStr() const override {
  4458. return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]";
  4459. }
  4460. protected:
  4461. Optional<Type *> PrivatizableType;
  4462. };
  4463. // TODO: Do this for call site arguments (probably also other values) as well.
  4464. struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
  4465. AAPrivatizablePtrArgument(const IRPosition &IRP, Attributor &A)
  4466. : AAPrivatizablePtrImpl(IRP, A) {}
  4467. /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
  4468. Optional<Type *> identifyPrivatizableType(Attributor &A) override {
  4469. // If this is a byval argument and we know all the call sites (so we can
  4470. // rewrite them), there is no need to check them explicitly.
  4471. bool AllCallSitesKnown;
  4472. if (getIRPosition().hasAttr(Attribute::ByVal) &&
  4473. A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this,
  4474. true, AllCallSitesKnown))
  4475. return getAssociatedValue().getType()->getPointerElementType();
  4476. Optional<Type *> Ty;
  4477. unsigned ArgNo = getIRPosition().getCallSiteArgNo();
  4478. // Make sure the associated call site argument has the same type at all call
  4479. // sites and it is an allocation we know is safe to privatize, for now that
  4480. // means we only allow alloca instructions.
  4481. // TODO: We can additionally analyze the accesses in the callee to create
  4482. // the type from that information instead. That is a little more
  4483. // involved and will be done in a follow up patch.
  4484. auto CallSiteCheck = [&](AbstractCallSite ACS) {
  4485. IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
  4486. // Check if a coresponding argument was found or if it is one not
  4487. // associated (which can happen for callback calls).
  4488. if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
  4489. return false;
  4490. // Check that all call sites agree on a type.
  4491. auto &PrivCSArgAA = A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos);
  4492. Optional<Type *> CSTy = PrivCSArgAA.getPrivatizableType();
  4493. LLVM_DEBUG({
  4494. dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: ";
  4495. if (CSTy.hasValue() && CSTy.getValue())
  4496. CSTy.getValue()->print(dbgs());
  4497. else if (CSTy.hasValue())
  4498. dbgs() << "<nullptr>";
  4499. else
  4500. dbgs() << "<none>";
  4501. });
  4502. Ty = combineTypes(Ty, CSTy);
  4503. LLVM_DEBUG({
  4504. dbgs() << " : New Type: ";
  4505. if (Ty.hasValue() && Ty.getValue())
  4506. Ty.getValue()->print(dbgs());
  4507. else if (Ty.hasValue())
  4508. dbgs() << "<nullptr>";
  4509. else
  4510. dbgs() << "<none>";
  4511. dbgs() << "\n";
  4512. });
  4513. return !Ty.hasValue() || Ty.getValue();
  4514. };
  4515. if (!A.checkForAllCallSites(CallSiteCheck, *this, true, AllCallSitesKnown))
  4516. return nullptr;
  4517. return Ty;
  4518. }
  4519. /// See AbstractAttribute::updateImpl(...).
  4520. ChangeStatus updateImpl(Attributor &A) override {
  4521. PrivatizableType = identifyPrivatizableType(A);
  4522. if (!PrivatizableType.hasValue())
  4523. return ChangeStatus::UNCHANGED;
  4524. if (!PrivatizableType.getValue())
  4525. return indicatePessimisticFixpoint();
  4526. // The dependence is optional so we don't give up once we give up on the
  4527. // alignment.
  4528. A.getAAFor<AAAlign>(*this, IRPosition::value(getAssociatedValue()),
  4529. /* TrackDependence */ true, DepClassTy::OPTIONAL);
  4530. // Avoid arguments with padding for now.
  4531. if (!getIRPosition().hasAttr(Attribute::ByVal) &&
  4532. !ArgumentPromotionPass::isDenselyPacked(PrivatizableType.getValue(),
  4533. A.getInfoCache().getDL())) {
  4534. LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n");
  4535. return indicatePessimisticFixpoint();
  4536. }
  4537. // Verify callee and caller agree on how the promoted argument would be
  4538. // passed.
  4539. // TODO: The use of the ArgumentPromotion interface here is ugly, we need a
  4540. // specialized form of TargetTransformInfo::areFunctionArgsABICompatible
  4541. // which doesn't require the arguments ArgumentPromotion wanted to pass.
  4542. Function &Fn = *getIRPosition().getAnchorScope();
  4543. SmallPtrSet<Argument *, 1> ArgsToPromote, Dummy;
  4544. ArgsToPromote.insert(getAssociatedArgument());
  4545. const auto *TTI =
  4546. A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
  4547. if (!TTI ||
  4548. !ArgumentPromotionPass::areFunctionArgsABICompatible(
  4549. Fn, *TTI, ArgsToPromote, Dummy) ||
  4550. ArgsToPromote.empty()) {
  4551. LLVM_DEBUG(
  4552. dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for "
  4553. << Fn.getName() << "\n");
  4554. return indicatePessimisticFixpoint();
  4555. }
  4556. // Collect the types that will replace the privatizable type in the function
  4557. // signature.
  4558. SmallVector<Type *, 16> ReplacementTypes;
  4559. identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
  4560. // Register a rewrite of the argument.
  4561. Argument *Arg = getAssociatedArgument();
  4562. if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
  4563. LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n");
  4564. return indicatePessimisticFixpoint();
  4565. }
  4566. unsigned ArgNo = Arg->getArgNo();
  4567. // Helper to check if for the given call site the associated argument is
  4568. // passed to a callback where the privatization would be different.
  4569. auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) {
  4570. SmallVector<const Use *, 4> CallbackUses;
  4571. AbstractCallSite::getCallbackUses(CB, CallbackUses);
  4572. for (const Use *U : CallbackUses) {
  4573. AbstractCallSite CBACS(U);
  4574. assert(CBACS && CBACS.isCallbackCall());
  4575. for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
  4576. int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
  4577. LLVM_DEBUG({
  4578. dbgs()
  4579. << "[AAPrivatizablePtr] Argument " << *Arg
  4580. << "check if can be privatized in the context of its parent ("
  4581. << Arg->getParent()->getName()
  4582. << ")\n[AAPrivatizablePtr] because it is an argument in a "
  4583. "callback ("
  4584. << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
  4585. << ")\n[AAPrivatizablePtr] " << CBArg << " : "
  4586. << CBACS.getCallArgOperand(CBArg) << " vs "
  4587. << CB.getArgOperand(ArgNo) << "\n"
  4588. << "[AAPrivatizablePtr] " << CBArg << " : "
  4589. << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n";
  4590. });
  4591. if (CBArgNo != int(ArgNo))
  4592. continue;
  4593. const auto &CBArgPrivAA =
  4594. A.getAAFor<AAPrivatizablePtr>(*this, IRPosition::argument(CBArg));
  4595. if (CBArgPrivAA.isValidState()) {
  4596. auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType();
  4597. if (!CBArgPrivTy.hasValue())
  4598. continue;
  4599. if (CBArgPrivTy.getValue() == PrivatizableType)
  4600. continue;
  4601. }
  4602. LLVM_DEBUG({
  4603. dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
  4604. << " cannot be privatized in the context of its parent ("
  4605. << Arg->getParent()->getName()
  4606. << ")\n[AAPrivatizablePtr] because it is an argument in a "
  4607. "callback ("
  4608. << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
  4609. << ").\n[AAPrivatizablePtr] for which the argument "
  4610. "privatization is not compatible.\n";
  4611. });
  4612. return false;
  4613. }
  4614. }
  4615. return true;
  4616. };
  4617. // Helper to check if for the given call site the associated argument is
  4618. // passed to a direct call where the privatization would be different.
  4619. auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
  4620. CallBase *DC = cast<CallBase>(ACS.getInstruction());
  4621. int DCArgNo = ACS.getCallArgOperandNo(ArgNo);
  4622. assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->getNumArgOperands() &&
  4623. "Expected a direct call operand for callback call operand");
  4624. LLVM_DEBUG({
  4625. dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
  4626. << " check if be privatized in the context of its parent ("
  4627. << Arg->getParent()->getName()
  4628. << ")\n[AAPrivatizablePtr] because it is an argument in a "
  4629. "direct call of ("
  4630. << DCArgNo << "@" << DC->getCalledFunction()->getName()
  4631. << ").\n";
  4632. });
  4633. Function *DCCallee = DC->getCalledFunction();
  4634. if (unsigned(DCArgNo) < DCCallee->arg_size()) {
  4635. const auto &DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
  4636. *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)));
  4637. if (DCArgPrivAA.isValidState()) {
  4638. auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType();
  4639. if (!DCArgPrivTy.hasValue())
  4640. return true;
  4641. if (DCArgPrivTy.getValue() == PrivatizableType)
  4642. return true;
  4643. }
  4644. }
  4645. LLVM_DEBUG({
  4646. dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
  4647. << " cannot be privatized in the context of its parent ("
  4648. << Arg->getParent()->getName()
  4649. << ")\n[AAPrivatizablePtr] because it is an argument in a "
  4650. "direct call of ("
  4651. << ACS.getInstruction()->getCalledFunction()->getName()
  4652. << ").\n[AAPrivatizablePtr] for which the argument "
  4653. "privatization is not compatible.\n";
  4654. });
  4655. return false;
  4656. };
  4657. // Helper to check if the associated argument is used at the given abstract
  4658. // call site in a way that is incompatible with the privatization assumed
  4659. // here.
  4660. auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
  4661. if (ACS.isDirectCall())
  4662. return IsCompatiblePrivArgOfCallback(*ACS.getInstruction());
  4663. if (ACS.isCallbackCall())
  4664. return IsCompatiblePrivArgOfDirectCS(ACS);
  4665. return false;
  4666. };
  4667. bool AllCallSitesKnown;
  4668. if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true,
  4669. AllCallSitesKnown))
  4670. return indicatePessimisticFixpoint();
  4671. return ChangeStatus::UNCHANGED;
  4672. }
  4673. /// Given a type to private \p PrivType, collect the constituates (which are
  4674. /// used) in \p ReplacementTypes.
  4675. static void
  4676. identifyReplacementTypes(Type *PrivType,
  4677. SmallVectorImpl<Type *> &ReplacementTypes) {
  4678. // TODO: For now we expand the privatization type to the fullest which can
  4679. // lead to dead arguments that need to be removed later.
  4680. assert(PrivType && "Expected privatizable type!");
  4681. // Traverse the type, extract constituate types on the outermost level.
  4682. if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
  4683. for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
  4684. ReplacementTypes.push_back(PrivStructType->getElementType(u));
  4685. } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
  4686. ReplacementTypes.append(PrivArrayType->getNumElements(),
  4687. PrivArrayType->getElementType());
  4688. } else {
  4689. ReplacementTypes.push_back(PrivType);
  4690. }
  4691. }
  4692. /// Initialize \p Base according to the type \p PrivType at position \p IP.
  4693. /// The values needed are taken from the arguments of \p F starting at
  4694. /// position \p ArgNo.
  4695. static void createInitialization(Type *PrivType, Value &Base, Function &F,
  4696. unsigned ArgNo, Instruction &IP) {
  4697. assert(PrivType && "Expected privatizable type!");
  4698. IRBuilder<NoFolder> IRB(&IP);
  4699. const DataLayout &DL = F.getParent()->getDataLayout();
  4700. // Traverse the type, build GEPs and stores.
  4701. if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
  4702. const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
  4703. for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
  4704. Type *PointeeTy = PrivStructType->getElementType(u)->getPointerTo();
  4705. Value *Ptr = constructPointer(
  4706. PointeeTy, &Base, PrivStructLayout->getElementOffset(u), IRB, DL);
  4707. new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
  4708. }
  4709. } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
  4710. Type *PointeeTy = PrivArrayType->getElementType();
  4711. Type *PointeePtrTy = PointeeTy->getPointerTo();
  4712. uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
  4713. for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
  4714. Value *Ptr =
  4715. constructPointer(PointeePtrTy, &Base, u * PointeeTySize, IRB, DL);
  4716. new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
  4717. }
  4718. } else {
  4719. new StoreInst(F.getArg(ArgNo), &Base, &IP);
  4720. }
  4721. }
  4722. /// Extract values from \p Base according to the type \p PrivType at the
  4723. /// call position \p ACS. The values are appended to \p ReplacementValues.
  4724. void createReplacementValues(Align Alignment, Type *PrivType,
  4725. AbstractCallSite ACS, Value *Base,
  4726. SmallVectorImpl<Value *> &ReplacementValues) {
  4727. assert(Base && "Expected base value!");
  4728. assert(PrivType && "Expected privatizable type!");
  4729. Instruction *IP = ACS.getInstruction();
  4730. IRBuilder<NoFolder> IRB(IP);
  4731. const DataLayout &DL = IP->getModule()->getDataLayout();
  4732. if (Base->getType()->getPointerElementType() != PrivType)
  4733. Base = BitCastInst::CreateBitOrPointerCast(Base, PrivType->getPointerTo(),
  4734. "", ACS.getInstruction());
  4735. // Traverse the type, build GEPs and loads.
  4736. if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
  4737. const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
  4738. for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
  4739. Type *PointeeTy = PrivStructType->getElementType(u);
  4740. Value *Ptr =
  4741. constructPointer(PointeeTy->getPointerTo(), Base,
  4742. PrivStructLayout->getElementOffset(u), IRB, DL);
  4743. LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP);
  4744. L->setAlignment(Alignment);
  4745. ReplacementValues.push_back(L);
  4746. }
  4747. } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
  4748. Type *PointeeTy = PrivArrayType->getElementType();
  4749. uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
  4750. Type *PointeePtrTy = PointeeTy->getPointerTo();
  4751. for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
  4752. Value *Ptr =
  4753. constructPointer(PointeePtrTy, Base, u * PointeeTySize, IRB, DL);
  4754. LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP);
  4755. L->setAlignment(Alignment);
  4756. ReplacementValues.push_back(L);
  4757. }
  4758. } else {
  4759. LoadInst *L = new LoadInst(PrivType, Base, "", IP);
  4760. L->setAlignment(Alignment);
  4761. ReplacementValues.push_back(L);
  4762. }
  4763. }
  4764. /// See AbstractAttribute::manifest(...)
  4765. ChangeStatus manifest(Attributor &A) override {
  4766. if (!PrivatizableType.hasValue())
  4767. return ChangeStatus::UNCHANGED;
  4768. assert(PrivatizableType.getValue() && "Expected privatizable type!");
  4769. // Collect all tail calls in the function as we cannot allow new allocas to
  4770. // escape into tail recursion.
  4771. // TODO: Be smarter about new allocas escaping into tail calls.
  4772. SmallVector<CallInst *, 16> TailCalls;
  4773. if (!A.checkForAllInstructions(
  4774. [&](Instruction &I) {
  4775. CallInst &CI = cast<CallInst>(I);
  4776. if (CI.isTailCall())
  4777. TailCalls.push_back(&CI);
  4778. return true;
  4779. },
  4780. *this, {Instruction::Call}))
  4781. return ChangeStatus::UNCHANGED;
  4782. Argument *Arg = getAssociatedArgument();
  4783. // Query AAAlign attribute for alignment of associated argument to
  4784. // determine the best alignment of loads.
  4785. const auto &AlignAA = A.getAAFor<AAAlign>(*this, IRPosition::value(*Arg));
  4786. // Callback to repair the associated function. A new alloca is placed at the
  4787. // beginning and initialized with the values passed through arguments. The
  4788. // new alloca replaces the use of the old pointer argument.
  4789. Attributor::ArgumentReplacementInfo::CalleeRepairCBTy FnRepairCB =
  4790. [=](const Attributor::ArgumentReplacementInfo &ARI,
  4791. Function &ReplacementFn, Function::arg_iterator ArgIt) {
  4792. BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
  4793. Instruction *IP = &*EntryBB.getFirstInsertionPt();
  4794. Instruction *AI = new AllocaInst(PrivatizableType.getValue(), 0,
  4795. Arg->getName() + ".priv", IP);
  4796. createInitialization(PrivatizableType.getValue(), *AI, ReplacementFn,
  4797. ArgIt->getArgNo(), *IP);
  4798. if (AI->getType() != Arg->getType())
  4799. AI =
  4800. BitCastInst::CreateBitOrPointerCast(AI, Arg->getType(), "", IP);
  4801. Arg->replaceAllUsesWith(AI);
  4802. for (CallInst *CI : TailCalls)
  4803. CI->setTailCall(false);
  4804. };
  4805. // Callback to repair a call site of the associated function. The elements
  4806. // of the privatizable type are loaded prior to the call and passed to the
  4807. // new function version.
  4808. Attributor::ArgumentReplacementInfo::ACSRepairCBTy ACSRepairCB =
  4809. [=, &AlignAA](const Attributor::ArgumentReplacementInfo &ARI,
  4810. AbstractCallSite ACS,
  4811. SmallVectorImpl<Value *> &NewArgOperands) {
  4812. // When no alignment is specified for the load instruction,
  4813. // natural alignment is assumed.
  4814. createReplacementValues(
  4815. assumeAligned(AlignAA.getAssumedAlign()),
  4816. PrivatizableType.getValue(), ACS,
  4817. ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()),
  4818. NewArgOperands);
  4819. };
  4820. // Collect the types that will replace the privatizable type in the function
  4821. // signature.
  4822. SmallVector<Type *, 16> ReplacementTypes;
  4823. identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
  4824. // Register a rewrite of the argument.
  4825. if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
  4826. std::move(FnRepairCB),
  4827. std::move(ACSRepairCB)))
  4828. return ChangeStatus::CHANGED;
  4829. return ChangeStatus::UNCHANGED;
  4830. }
  4831. /// See AbstractAttribute::trackStatistics()
  4832. void trackStatistics() const override {
  4833. STATS_DECLTRACK_ARG_ATTR(privatizable_ptr);
  4834. }
  4835. };
  4836. struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl {
  4837. AAPrivatizablePtrFloating(const IRPosition &IRP, Attributor &A)
  4838. : AAPrivatizablePtrImpl(IRP, A) {}
  4839. /// See AbstractAttribute::initialize(...).
  4840. virtual void initialize(Attributor &A) override {
  4841. // TODO: We can privatize more than arguments.
  4842. indicatePessimisticFixpoint();
  4843. }
  4844. ChangeStatus updateImpl(Attributor &A) override {
  4845. llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::"
  4846. "updateImpl will not be called");
  4847. }
  4848. /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
  4849. Optional<Type *> identifyPrivatizableType(Attributor &A) override {
  4850. Value *Obj = getUnderlyingObject(&getAssociatedValue());
  4851. if (!Obj) {
  4852. LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n");
  4853. return nullptr;
  4854. }
  4855. if (auto *AI = dyn_cast<AllocaInst>(Obj))
  4856. if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
  4857. if (CI->isOne())
  4858. return Obj->getType()->getPointerElementType();
  4859. if (auto *Arg = dyn_cast<Argument>(Obj)) {
  4860. auto &PrivArgAA =
  4861. A.getAAFor<AAPrivatizablePtr>(*this, IRPosition::argument(*Arg));
  4862. if (PrivArgAA.isAssumedPrivatizablePtr())
  4863. return Obj->getType()->getPointerElementType();
  4864. }
  4865. LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid "
  4866. "alloca nor privatizable argument: "
  4867. << *Obj << "!\n");
  4868. return nullptr;
  4869. }
  4870. /// See AbstractAttribute::trackStatistics()
  4871. void trackStatistics() const override {
  4872. STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr);
  4873. }
  4874. };
  4875. struct AAPrivatizablePtrCallSiteArgument final
  4876. : public AAPrivatizablePtrFloating {
  4877. AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP, Attributor &A)
  4878. : AAPrivatizablePtrFloating(IRP, A) {}
  4879. /// See AbstractAttribute::initialize(...).
  4880. void initialize(Attributor &A) override {
  4881. if (getIRPosition().hasAttr(Attribute::ByVal))
  4882. indicateOptimisticFixpoint();
  4883. }
  4884. /// See AbstractAttribute::updateImpl(...).
  4885. ChangeStatus updateImpl(Attributor &A) override {
  4886. PrivatizableType = identifyPrivatizableType(A);
  4887. if (!PrivatizableType.hasValue())
  4888. return ChangeStatus::UNCHANGED;
  4889. if (!PrivatizableType.getValue())
  4890. return indicatePessimisticFixpoint();
  4891. const IRPosition &IRP = getIRPosition();
  4892. auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, IRP);
  4893. if (!NoCaptureAA.isAssumedNoCapture()) {
  4894. LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n");
  4895. return indicatePessimisticFixpoint();
  4896. }
  4897. auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP);
  4898. if (!NoAliasAA.isAssumedNoAlias()) {
  4899. LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n");
  4900. return indicatePessimisticFixpoint();
  4901. }
  4902. const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(*this, IRP);
  4903. if (!MemBehaviorAA.isAssumedReadOnly()) {
  4904. LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n");
  4905. return indicatePessimisticFixpoint();
  4906. }
  4907. return ChangeStatus::UNCHANGED;
  4908. }
  4909. /// See AbstractAttribute::trackStatistics()
  4910. void trackStatistics() const override {
  4911. STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr);
  4912. }
  4913. };
  4914. struct AAPrivatizablePtrCallSiteReturned final
  4915. : public AAPrivatizablePtrFloating {
  4916. AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP, Attributor &A)
  4917. : AAPrivatizablePtrFloating(IRP, A) {}
  4918. /// See AbstractAttribute::initialize(...).
  4919. void initialize(Attributor &A) override {
  4920. // TODO: We can privatize more than arguments.
  4921. indicatePessimisticFixpoint();
  4922. }
  4923. /// See AbstractAttribute::trackStatistics()
  4924. void trackStatistics() const override {
  4925. STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr);
  4926. }
  4927. };
  4928. struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating {
  4929. AAPrivatizablePtrReturned(const IRPosition &IRP, Attributor &A)
  4930. : AAPrivatizablePtrFloating(IRP, A) {}
  4931. /// See AbstractAttribute::initialize(...).
  4932. void initialize(Attributor &A) override {
  4933. // TODO: We can privatize more than arguments.
  4934. indicatePessimisticFixpoint();
  4935. }
  4936. /// See AbstractAttribute::trackStatistics()
  4937. void trackStatistics() const override {
  4938. STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr);
  4939. }
  4940. };
  4941. /// -------------------- Memory Behavior Attributes ----------------------------
  4942. /// Includes read-none, read-only, and write-only.
  4943. /// ----------------------------------------------------------------------------
  4944. struct AAMemoryBehaviorImpl : public AAMemoryBehavior {
  4945. AAMemoryBehaviorImpl(const IRPosition &IRP, Attributor &A)
  4946. : AAMemoryBehavior(IRP, A) {}
  4947. /// See AbstractAttribute::initialize(...).
  4948. void initialize(Attributor &A) override {
  4949. intersectAssumedBits(BEST_STATE);
  4950. getKnownStateFromValue(getIRPosition(), getState());
  4951. AAMemoryBehavior::initialize(A);
  4952. }
  4953. /// Return the memory behavior information encoded in the IR for \p IRP.
  4954. static void getKnownStateFromValue(const IRPosition &IRP,
  4955. BitIntegerState &State,
  4956. bool IgnoreSubsumingPositions = false) {
  4957. SmallVector<Attribute, 2> Attrs;
  4958. IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
  4959. for (const Attribute &Attr : Attrs) {
  4960. switch (Attr.getKindAsEnum()) {
  4961. case Attribute::ReadNone:
  4962. State.addKnownBits(NO_ACCESSES);
  4963. break;
  4964. case Attribute::ReadOnly:
  4965. State.addKnownBits(NO_WRITES);
  4966. break;
  4967. case Attribute::WriteOnly:
  4968. State.addKnownBits(NO_READS);
  4969. break;
  4970. default:
  4971. llvm_unreachable("Unexpected attribute!");
  4972. }
  4973. }
  4974. if (auto *I = dyn_cast<Instruction>(&IRP.getAnchorValue())) {
  4975. if (!I->mayReadFromMemory())
  4976. State.addKnownBits(NO_READS);
  4977. if (!I->mayWriteToMemory())
  4978. State.addKnownBits(NO_WRITES);
  4979. }
  4980. }
  4981. /// See AbstractAttribute::getDeducedAttributes(...).
  4982. void getDeducedAttributes(LLVMContext &Ctx,
  4983. SmallVectorImpl<Attribute> &Attrs) const override {
  4984. assert(Attrs.size() == 0);
  4985. if (isAssumedReadNone())
  4986. Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
  4987. else if (isAssumedReadOnly())
  4988. Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
  4989. else if (isAssumedWriteOnly())
  4990. Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
  4991. assert(Attrs.size() <= 1);
  4992. }
  4993. /// See AbstractAttribute::manifest(...).
  4994. ChangeStatus manifest(Attributor &A) override {
  4995. if (hasAttr(Attribute::ReadNone, /* IgnoreSubsumingPositions */ true))
  4996. return ChangeStatus::UNCHANGED;
  4997. const IRPosition &IRP = getIRPosition();
  4998. // Check if we would improve the existing attributes first.
  4999. SmallVector<Attribute, 4> DeducedAttrs;
  5000. getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
  5001. if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
  5002. return IRP.hasAttr(Attr.getKindAsEnum(),
  5003. /* IgnoreSubsumingPositions */ true);
  5004. }))
  5005. return ChangeStatus::UNCHANGED;
  5006. // Clear existing attributes.
  5007. IRP.removeAttrs(AttrKinds);
  5008. // Use the generic manifest method.
  5009. return IRAttribute::manifest(A);
  5010. }
  5011. /// See AbstractState::getAsStr().
  5012. const std::string getAsStr() const override {
  5013. if (isAssumedReadNone())
  5014. return "readnone";
  5015. if (isAssumedReadOnly())
  5016. return "readonly";
  5017. if (isAssumedWriteOnly())
  5018. return "writeonly";
  5019. return "may-read/write";
  5020. }
  5021. /// The set of IR attributes AAMemoryBehavior deals with.
  5022. static const Attribute::AttrKind AttrKinds[3];
  5023. };
  5024. const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = {
  5025. Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
  5026. /// Memory behavior attribute for a floating value.
  5027. struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
  5028. AAMemoryBehaviorFloating(const IRPosition &IRP, Attributor &A)
  5029. : AAMemoryBehaviorImpl(IRP, A) {}
  5030. /// See AbstractAttribute::initialize(...).
  5031. void initialize(Attributor &A) override {
  5032. AAMemoryBehaviorImpl::initialize(A);
  5033. addUsesOf(A, getAssociatedValue());
  5034. }
  5035. /// See AbstractAttribute::updateImpl(...).
  5036. ChangeStatus updateImpl(Attributor &A) override;
  5037. /// See AbstractAttribute::trackStatistics()
  5038. void trackStatistics() const override {
  5039. if (isAssumedReadNone())
  5040. STATS_DECLTRACK_FLOATING_ATTR(readnone)
  5041. else if (isAssumedReadOnly())
  5042. STATS_DECLTRACK_FLOATING_ATTR(readonly)
  5043. else if (isAssumedWriteOnly())
  5044. STATS_DECLTRACK_FLOATING_ATTR(writeonly)
  5045. }
  5046. private:
  5047. /// Return true if users of \p UserI might access the underlying
  5048. /// variable/location described by \p U and should therefore be analyzed.
  5049. bool followUsersOfUseIn(Attributor &A, const Use *U,
  5050. const Instruction *UserI);
  5051. /// Update the state according to the effect of use \p U in \p UserI.
  5052. void analyzeUseIn(Attributor &A, const Use *U, const Instruction *UserI);
  5053. protected:
  5054. /// Add the uses of \p V to the `Uses` set we look at during the update step.
  5055. void addUsesOf(Attributor &A, const Value &V);
  5056. /// Container for (transitive) uses of the associated argument.
  5057. SmallVector<const Use *, 8> Uses;
  5058. /// Set to remember the uses we already traversed.
  5059. SmallPtrSet<const Use *, 8> Visited;
  5060. };
  5061. /// Memory behavior attribute for function argument.
  5062. struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
  5063. AAMemoryBehaviorArgument(const IRPosition &IRP, Attributor &A)
  5064. : AAMemoryBehaviorFloating(IRP, A) {}
  5065. /// See AbstractAttribute::initialize(...).
  5066. void initialize(Attributor &A) override {
  5067. intersectAssumedBits(BEST_STATE);
  5068. const IRPosition &IRP = getIRPosition();
  5069. // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we
  5070. // can query it when we use has/getAttr. That would allow us to reuse the
  5071. // initialize of the base class here.
  5072. bool HasByVal =
  5073. IRP.hasAttr({Attribute::ByVal}, /* IgnoreSubsumingPositions */ true);
  5074. getKnownStateFromValue(IRP, getState(),
  5075. /* IgnoreSubsumingPositions */ HasByVal);
  5076. // Initialize the use vector with all direct uses of the associated value.
  5077. Argument *Arg = getAssociatedArgument();
  5078. if (!Arg || !A.isFunctionIPOAmendable(*(Arg->getParent()))) {
  5079. indicatePessimisticFixpoint();
  5080. } else {
  5081. addUsesOf(A, *Arg);
  5082. }
  5083. }
  5084. ChangeStatus manifest(Attributor &A) override {
  5085. // TODO: Pointer arguments are not supported on vectors of pointers yet.
  5086. if (!getAssociatedValue().getType()->isPointerTy())
  5087. return ChangeStatus::UNCHANGED;
  5088. // TODO: From readattrs.ll: "inalloca parameters are always
  5089. // considered written"
  5090. if (hasAttr({Attribute::InAlloca, Attribute::Preallocated})) {
  5091. removeKnownBits(NO_WRITES);
  5092. removeAssumedBits(NO_WRITES);
  5093. }
  5094. return AAMemoryBehaviorFloating::manifest(A);
  5095. }
  5096. /// See AbstractAttribute::trackStatistics()
  5097. void trackStatistics() const override {
  5098. if (isAssumedReadNone())
  5099. STATS_DECLTRACK_ARG_ATTR(readnone)
  5100. else if (isAssumedReadOnly())
  5101. STATS_DECLTRACK_ARG_ATTR(readonly)
  5102. else if (isAssumedWriteOnly())
  5103. STATS_DECLTRACK_ARG_ATTR(writeonly)
  5104. }
  5105. };
  5106. struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
  5107. AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP, Attributor &A)
  5108. : AAMemoryBehaviorArgument(IRP, A) {}
  5109. /// See AbstractAttribute::initialize(...).
  5110. void initialize(Attributor &A) override {
  5111. // If we don't have an associated attribute this is either a variadic call
  5112. // or an indirect call, either way, nothing to do here.
  5113. Argument *Arg = getAssociatedArgument();
  5114. if (!Arg) {
  5115. indicatePessimisticFixpoint();
  5116. return;
  5117. }
  5118. if (Arg->hasByValAttr()) {
  5119. addKnownBits(NO_WRITES);
  5120. removeKnownBits(NO_READS);
  5121. removeAssumedBits(NO_READS);
  5122. }
  5123. AAMemoryBehaviorArgument::initialize(A);
  5124. if (getAssociatedFunction()->isDeclaration())
  5125. indicatePessimisticFixpoint();
  5126. }
  5127. /// See AbstractAttribute::updateImpl(...).
  5128. ChangeStatus updateImpl(Attributor &A) override {
  5129. // TODO: Once we have call site specific value information we can provide
  5130. // call site specific liveness liveness information and then it makes
  5131. // sense to specialize attributes for call sites arguments instead of
  5132. // redirecting requests to the callee argument.
  5133. Argument *Arg = getAssociatedArgument();
  5134. const IRPosition &ArgPos = IRPosition::argument(*Arg);
  5135. auto &ArgAA = A.getAAFor<AAMemoryBehavior>(*this, ArgPos);
  5136. return clampStateAndIndicateChange(getState(), ArgAA.getState());
  5137. }
  5138. /// See AbstractAttribute::trackStatistics()
  5139. void trackStatistics() const override {
  5140. if (isAssumedReadNone())
  5141. STATS_DECLTRACK_CSARG_ATTR(readnone)
  5142. else if (isAssumedReadOnly())
  5143. STATS_DECLTRACK_CSARG_ATTR(readonly)
  5144. else if (isAssumedWriteOnly())
  5145. STATS_DECLTRACK_CSARG_ATTR(writeonly)
  5146. }
  5147. };
  5148. /// Memory behavior attribute for a call site return position.
  5149. struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
  5150. AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP, Attributor &A)
  5151. : AAMemoryBehaviorFloating(IRP, A) {}
  5152. /// See AbstractAttribute::initialize(...).
  5153. void initialize(Attributor &A) override {
  5154. AAMemoryBehaviorImpl::initialize(A);
  5155. Function *F = getAssociatedFunction();
  5156. if (!F || F->isDeclaration())
  5157. indicatePessimisticFixpoint();
  5158. }
  5159. /// See AbstractAttribute::manifest(...).
  5160. ChangeStatus manifest(Attributor &A) override {
  5161. // We do not annotate returned values.
  5162. return ChangeStatus::UNCHANGED;
  5163. }
  5164. /// See AbstractAttribute::trackStatistics()
  5165. void trackStatistics() const override {}
  5166. };
  5167. /// An AA to represent the memory behavior function attributes.
  5168. struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl {
  5169. AAMemoryBehaviorFunction(const IRPosition &IRP, Attributor &A)
  5170. : AAMemoryBehaviorImpl(IRP, A) {}
  5171. /// See AbstractAttribute::updateImpl(Attributor &A).
  5172. virtual ChangeStatus updateImpl(Attributor &A) override;
  5173. /// See AbstractAttribute::manifest(...).
  5174. ChangeStatus manifest(Attributor &A) override {
  5175. Function &F = cast<Function>(getAnchorValue());
  5176. if (isAssumedReadNone()) {
  5177. F.removeFnAttr(Attribute::ArgMemOnly);
  5178. F.removeFnAttr(Attribute::InaccessibleMemOnly);
  5179. F.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
  5180. }
  5181. return AAMemoryBehaviorImpl::manifest(A);
  5182. }
  5183. /// See AbstractAttribute::trackStatistics()
  5184. void trackStatistics() const override {
  5185. if (isAssumedReadNone())
  5186. STATS_DECLTRACK_FN_ATTR(readnone)
  5187. else if (isAssumedReadOnly())
  5188. STATS_DECLTRACK_FN_ATTR(readonly)
  5189. else if (isAssumedWriteOnly())
  5190. STATS_DECLTRACK_FN_ATTR(writeonly)
  5191. }
  5192. };
  5193. /// AAMemoryBehavior attribute for call sites.
  5194. struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl {
  5195. AAMemoryBehaviorCallSite(const IRPosition &IRP, Attributor &A)
  5196. : AAMemoryBehaviorImpl(IRP, A) {}
  5197. /// See AbstractAttribute::initialize(...).
  5198. void initialize(Attributor &A) override {
  5199. AAMemoryBehaviorImpl::initialize(A);
  5200. Function *F = getAssociatedFunction();
  5201. if (!F || F->isDeclaration())
  5202. indicatePessimisticFixpoint();
  5203. }
  5204. /// See AbstractAttribute::updateImpl(...).
  5205. ChangeStatus updateImpl(Attributor &A) override {
  5206. // TODO: Once we have call site specific value information we can provide
  5207. // call site specific liveness liveness information and then it makes
  5208. // sense to specialize attributes for call sites arguments instead of
  5209. // redirecting requests to the callee argument.
  5210. Function *F = getAssociatedFunction();
  5211. const IRPosition &FnPos = IRPosition::function(*F);
  5212. auto &FnAA = A.getAAFor<AAMemoryBehavior>(*this, FnPos);
  5213. return clampStateAndIndicateChange(getState(), FnAA.getState());
  5214. }
  5215. /// See AbstractAttribute::trackStatistics()
  5216. void trackStatistics() const override {
  5217. if (isAssumedReadNone())
  5218. STATS_DECLTRACK_CS_ATTR(readnone)
  5219. else if (isAssumedReadOnly())
  5220. STATS_DECLTRACK_CS_ATTR(readonly)
  5221. else if (isAssumedWriteOnly())
  5222. STATS_DECLTRACK_CS_ATTR(writeonly)
  5223. }
  5224. };
  5225. ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) {
  5226. // The current assumed state used to determine a change.
  5227. auto AssumedState = getAssumed();
  5228. auto CheckRWInst = [&](Instruction &I) {
  5229. // If the instruction has an own memory behavior state, use it to restrict
  5230. // the local state. No further analysis is required as the other memory
  5231. // state is as optimistic as it gets.
  5232. if (const auto *CB = dyn_cast<CallBase>(&I)) {
  5233. const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
  5234. *this, IRPosition::callsite_function(*CB));
  5235. intersectAssumedBits(MemBehaviorAA.getAssumed());
  5236. return !isAtFixpoint();
  5237. }
  5238. // Remove access kind modifiers if necessary.
  5239. if (I.mayReadFromMemory())
  5240. removeAssumedBits(NO_READS);
  5241. if (I.mayWriteToMemory())
  5242. removeAssumedBits(NO_WRITES);
  5243. return !isAtFixpoint();
  5244. };
  5245. if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this))
  5246. return indicatePessimisticFixpoint();
  5247. return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
  5248. : ChangeStatus::UNCHANGED;
  5249. }
  5250. ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) {
  5251. const IRPosition &IRP = getIRPosition();
  5252. const IRPosition &FnPos = IRPosition::function_scope(IRP);
  5253. AAMemoryBehavior::StateType &S = getState();
  5254. // First, check the function scope. We take the known information and we avoid
  5255. // work if the assumed information implies the current assumed information for
  5256. // this attribute. This is a valid for all but byval arguments.
  5257. Argument *Arg = IRP.getAssociatedArgument();
  5258. AAMemoryBehavior::base_t FnMemAssumedState =
  5259. AAMemoryBehavior::StateType::getWorstState();
  5260. if (!Arg || !Arg->hasByValAttr()) {
  5261. const auto &FnMemAA = A.getAAFor<AAMemoryBehavior>(
  5262. *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
  5263. FnMemAssumedState = FnMemAA.getAssumed();
  5264. S.addKnownBits(FnMemAA.getKnown());
  5265. if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed())
  5266. return ChangeStatus::UNCHANGED;
  5267. }
  5268. // Make sure the value is not captured (except through "return"), if
  5269. // it is, any information derived would be irrelevant anyway as we cannot
  5270. // check the potential aliases introduced by the capture. However, no need
  5271. // to fall back to anythign less optimistic than the function state.
  5272. const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
  5273. *this, IRP, /* TrackDependence */ true, DepClassTy::OPTIONAL);
  5274. if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
  5275. S.intersectAssumedBits(FnMemAssumedState);
  5276. return ChangeStatus::CHANGED;
  5277. }
  5278. // The current assumed state used to determine a change.
  5279. auto AssumedState = S.getAssumed();
  5280. // Liveness information to exclude dead users.
  5281. // TODO: Take the FnPos once we have call site specific liveness information.
  5282. const auto &LivenessAA = A.getAAFor<AAIsDead>(
  5283. *this, IRPosition::function(*IRP.getAssociatedFunction()),
  5284. /* TrackDependence */ false);
  5285. // Visit and expand uses until all are analyzed or a fixpoint is reached.
  5286. for (unsigned i = 0; i < Uses.size() && !isAtFixpoint(); i++) {
  5287. const Use *U = Uses[i];
  5288. Instruction *UserI = cast<Instruction>(U->getUser());
  5289. LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << **U << " in " << *UserI
  5290. << " [Dead: " << (A.isAssumedDead(*U, this, &LivenessAA))
  5291. << "]\n");
  5292. if (A.isAssumedDead(*U, this, &LivenessAA))
  5293. continue;
  5294. // Droppable users, e.g., llvm::assume does not actually perform any action.
  5295. if (UserI->isDroppable())
  5296. continue;
  5297. // Check if the users of UserI should also be visited.
  5298. if (followUsersOfUseIn(A, U, UserI))
  5299. addUsesOf(A, *UserI);
  5300. // If UserI might touch memory we analyze the use in detail.
  5301. if (UserI->mayReadOrWriteMemory())
  5302. analyzeUseIn(A, U, UserI);
  5303. }
  5304. return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
  5305. : ChangeStatus::UNCHANGED;
  5306. }
  5307. void AAMemoryBehaviorFloating::addUsesOf(Attributor &A, const Value &V) {
  5308. SmallVector<const Use *, 8> WL;
  5309. for (const Use &U : V.uses())
  5310. WL.push_back(&U);
  5311. while (!WL.empty()) {
  5312. const Use *U = WL.pop_back_val();
  5313. if (!Visited.insert(U).second)
  5314. continue;
  5315. const Instruction *UserI = cast<Instruction>(U->getUser());
  5316. if (UserI->mayReadOrWriteMemory()) {
  5317. Uses.push_back(U);
  5318. continue;
  5319. }
  5320. if (!followUsersOfUseIn(A, U, UserI))
  5321. continue;
  5322. for (const Use &UU : UserI->uses())
  5323. WL.push_back(&UU);
  5324. }
  5325. }
  5326. bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use *U,
  5327. const Instruction *UserI) {
  5328. // The loaded value is unrelated to the pointer argument, no need to
  5329. // follow the users of the load.
  5330. if (isa<LoadInst>(UserI))
  5331. return false;
  5332. // By default we follow all uses assuming UserI might leak information on U,
  5333. // we have special handling for call sites operands though.
  5334. const auto *CB = dyn_cast<CallBase>(UserI);
  5335. if (!CB || !CB->isArgOperand(U))
  5336. return true;
  5337. // If the use is a call argument known not to be captured, the users of
  5338. // the call do not need to be visited because they have to be unrelated to
  5339. // the input. Note that this check is not trivial even though we disallow
  5340. // general capturing of the underlying argument. The reason is that the
  5341. // call might the argument "through return", which we allow and for which we
  5342. // need to check call users.
  5343. if (U->get()->getType()->isPointerTy()) {
  5344. unsigned ArgNo = CB->getArgOperandNo(U);
  5345. const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
  5346. *this, IRPosition::callsite_argument(*CB, ArgNo),
  5347. /* TrackDependence */ true, DepClassTy::OPTIONAL);
  5348. return !ArgNoCaptureAA.isAssumedNoCapture();
  5349. }
  5350. return true;
  5351. }
  5352. void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use *U,
  5353. const Instruction *UserI) {
  5354. assert(UserI->mayReadOrWriteMemory());
  5355. switch (UserI->getOpcode()) {
  5356. default:
  5357. // TODO: Handle all atomics and other side-effect operations we know of.
  5358. break;
  5359. case Instruction::Load:
  5360. // Loads cause the NO_READS property to disappear.
  5361. removeAssumedBits(NO_READS);
  5362. return;
  5363. case Instruction::Store:
  5364. // Stores cause the NO_WRITES property to disappear if the use is the
  5365. // pointer operand. Note that we do assume that capturing was taken care of
  5366. // somewhere else.
  5367. if (cast<StoreInst>(UserI)->getPointerOperand() == U->get())
  5368. removeAssumedBits(NO_WRITES);
  5369. return;
  5370. case Instruction::Call:
  5371. case Instruction::CallBr:
  5372. case Instruction::Invoke: {
  5373. // For call sites we look at the argument memory behavior attribute (this
  5374. // could be recursive!) in order to restrict our own state.
  5375. const auto *CB = cast<CallBase>(UserI);
  5376. // Give up on operand bundles.
  5377. if (CB->isBundleOperand(U)) {
  5378. indicatePessimisticFixpoint();
  5379. return;
  5380. }
  5381. // Calling a function does read the function pointer, maybe write it if the
  5382. // function is self-modifying.
  5383. if (CB->isCallee(U)) {
  5384. removeAssumedBits(NO_READS);
  5385. break;
  5386. }
  5387. // Adjust the possible access behavior based on the information on the
  5388. // argument.
  5389. IRPosition Pos;
  5390. if (U->get()->getType()->isPointerTy())
  5391. Pos = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(U));
  5392. else
  5393. Pos = IRPosition::callsite_function(*CB);
  5394. const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
  5395. *this, Pos,
  5396. /* TrackDependence */ true, DepClassTy::OPTIONAL);
  5397. // "assumed" has at most the same bits as the MemBehaviorAA assumed
  5398. // and at least "known".
  5399. intersectAssumedBits(MemBehaviorAA.getAssumed());
  5400. return;
  5401. }
  5402. };
  5403. // Generally, look at the "may-properties" and adjust the assumed state if we
  5404. // did not trigger special handling before.
  5405. if (UserI->mayReadFromMemory())
  5406. removeAssumedBits(NO_READS);
  5407. if (UserI->mayWriteToMemory())
  5408. removeAssumedBits(NO_WRITES);
  5409. }
  5410. } // namespace
  5411. /// -------------------- Memory Locations Attributes ---------------------------
  5412. /// Includes read-none, argmemonly, inaccessiblememonly,
  5413. /// inaccessiblememorargmemonly
  5414. /// ----------------------------------------------------------------------------
  5415. std::string AAMemoryLocation::getMemoryLocationsAsStr(
  5416. AAMemoryLocation::MemoryLocationsKind MLK) {
  5417. if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS))
  5418. return "all memory";
  5419. if (MLK == AAMemoryLocation::NO_LOCATIONS)
  5420. return "no memory";
  5421. std::string S = "memory:";
  5422. if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM))
  5423. S += "stack,";
  5424. if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM))
  5425. S += "constant,";
  5426. if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_INTERNAL_MEM))
  5427. S += "internal global,";
  5428. if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_EXTERNAL_MEM))
  5429. S += "external global,";
  5430. if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM))
  5431. S += "argument,";
  5432. if (0 == (MLK & AAMemoryLocation::NO_INACCESSIBLE_MEM))
  5433. S += "inaccessible,";
  5434. if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM))
  5435. S += "malloced,";
  5436. if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM))
  5437. S += "unknown,";
  5438. S.pop_back();
  5439. return S;
  5440. }
  5441. namespace {
  5442. struct AAMemoryLocationImpl : public AAMemoryLocation {
  5443. AAMemoryLocationImpl(const IRPosition &IRP, Attributor &A)
  5444. : AAMemoryLocation(IRP, A), Allocator(A.Allocator) {
  5445. for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u)
  5446. AccessKind2Accesses[u] = nullptr;
  5447. }
  5448. ~AAMemoryLocationImpl() {
  5449. // The AccessSets are allocated via a BumpPtrAllocator, we call
  5450. // the destructor manually.
  5451. for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u)
  5452. if (AccessKind2Accesses[u])
  5453. AccessKind2Accesses[u]->~AccessSet();
  5454. }
  5455. /// See AbstractAttribute::initialize(...).
  5456. void initialize(Attributor &A) override {
  5457. intersectAssumedBits(BEST_STATE);
  5458. getKnownStateFromValue(A, getIRPosition(), getState());
  5459. AAMemoryLocation::initialize(A);
  5460. }
  5461. /// Return the memory behavior information encoded in the IR for \p IRP.
  5462. static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP,
  5463. BitIntegerState &State,
  5464. bool IgnoreSubsumingPositions = false) {
  5465. // For internal functions we ignore `argmemonly` and
  5466. // `inaccessiblememorargmemonly` as we might break it via interprocedural
  5467. // constant propagation. It is unclear if this is the best way but it is
  5468. // unlikely this will cause real performance problems. If we are deriving
  5469. // attributes for the anchor function we even remove the attribute in
  5470. // addition to ignoring it.
  5471. bool UseArgMemOnly = true;
  5472. Function *AnchorFn = IRP.getAnchorScope();
  5473. if (AnchorFn && A.isRunOn(*AnchorFn))
  5474. UseArgMemOnly = !AnchorFn->hasLocalLinkage();
  5475. SmallVector<Attribute, 2> Attrs;
  5476. IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
  5477. for (const Attribute &Attr : Attrs) {
  5478. switch (Attr.getKindAsEnum()) {
  5479. case Attribute::ReadNone:
  5480. State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM);
  5481. break;
  5482. case Attribute::InaccessibleMemOnly:
  5483. State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
  5484. break;
  5485. case Attribute::ArgMemOnly:
  5486. if (UseArgMemOnly)
  5487. State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true));
  5488. else
  5489. IRP.removeAttrs({Attribute::ArgMemOnly});
  5490. break;
  5491. case Attribute::InaccessibleMemOrArgMemOnly:
  5492. if (UseArgMemOnly)
  5493. State.addKnownBits(inverseLocation(
  5494. NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true));
  5495. else
  5496. IRP.removeAttrs({Attribute::InaccessibleMemOrArgMemOnly});
  5497. break;
  5498. default:
  5499. llvm_unreachable("Unexpected attribute!");
  5500. }
  5501. }
  5502. }
  5503. /// See AbstractAttribute::getDeducedAttributes(...).
  5504. void getDeducedAttributes(LLVMContext &Ctx,
  5505. SmallVectorImpl<Attribute> &Attrs) const override {
  5506. assert(Attrs.size() == 0);
  5507. if (isAssumedReadNone()) {
  5508. Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
  5509. } else if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) {
  5510. if (isAssumedInaccessibleMemOnly())
  5511. Attrs.push_back(Attribute::get(Ctx, Attribute::InaccessibleMemOnly));
  5512. else if (isAssumedArgMemOnly())
  5513. Attrs.push_back(Attribute::get(Ctx, Attribute::ArgMemOnly));
  5514. else if (isAssumedInaccessibleOrArgMemOnly())
  5515. Attrs.push_back(
  5516. Attribute::get(Ctx, Attribute::InaccessibleMemOrArgMemOnly));
  5517. }
  5518. assert(Attrs.size() <= 1);
  5519. }
  5520. /// See AbstractAttribute::manifest(...).
  5521. ChangeStatus manifest(Attributor &A) override {
  5522. const IRPosition &IRP = getIRPosition();
  5523. // Check if we would improve the existing attributes first.
  5524. SmallVector<Attribute, 4> DeducedAttrs;
  5525. getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
  5526. if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
  5527. return IRP.hasAttr(Attr.getKindAsEnum(),
  5528. /* IgnoreSubsumingPositions */ true);
  5529. }))
  5530. return ChangeStatus::UNCHANGED;
  5531. // Clear existing attributes.
  5532. IRP.removeAttrs(AttrKinds);
  5533. if (isAssumedReadNone())
  5534. IRP.removeAttrs(AAMemoryBehaviorImpl::AttrKinds);
  5535. // Use the generic manifest method.
  5536. return IRAttribute::manifest(A);
  5537. }
  5538. /// See AAMemoryLocation::checkForAllAccessesToMemoryKind(...).
  5539. bool checkForAllAccessesToMemoryKind(
  5540. function_ref<bool(const Instruction *, const Value *, AccessKind,
  5541. MemoryLocationsKind)>
  5542. Pred,
  5543. MemoryLocationsKind RequestedMLK) const override {
  5544. if (!isValidState())
  5545. return false;
  5546. MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
  5547. if (AssumedMLK == NO_LOCATIONS)
  5548. return true;
  5549. unsigned Idx = 0;
  5550. for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS;
  5551. CurMLK *= 2, ++Idx) {
  5552. if (CurMLK & RequestedMLK)
  5553. continue;
  5554. if (const AccessSet *Accesses = AccessKind2Accesses[Idx])
  5555. for (const AccessInfo &AI : *Accesses)
  5556. if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
  5557. return false;
  5558. }
  5559. return true;
  5560. }
  5561. ChangeStatus indicatePessimisticFixpoint() override {
  5562. // If we give up and indicate a pessimistic fixpoint this instruction will
  5563. // become an access for all potential access kinds:
  5564. // TODO: Add pointers for argmemonly and globals to improve the results of
  5565. // checkForAllAccessesToMemoryKind.
  5566. bool Changed = false;
  5567. MemoryLocationsKind KnownMLK = getKnown();
  5568. Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
  5569. for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
  5570. if (!(CurMLK & KnownMLK))
  5571. updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed,
  5572. getAccessKindFromInst(I));
  5573. return AAMemoryLocation::indicatePessimisticFixpoint();
  5574. }
  5575. protected:
  5576. /// Helper struct to tie together an instruction that has a read or write
  5577. /// effect with the pointer it accesses (if any).
  5578. struct AccessInfo {
  5579. /// The instruction that caused the access.
  5580. const Instruction *I;
  5581. /// The base pointer that is accessed, or null if unknown.
  5582. const Value *Ptr;
  5583. /// The kind of access (read/write/read+write).
  5584. AccessKind Kind;
  5585. bool operator==(const AccessInfo &RHS) const {
  5586. return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind;
  5587. }
  5588. bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const {
  5589. if (LHS.I != RHS.I)
  5590. return LHS.I < RHS.I;
  5591. if (LHS.Ptr != RHS.Ptr)
  5592. return LHS.Ptr < RHS.Ptr;
  5593. if (LHS.Kind != RHS.Kind)
  5594. return LHS.Kind < RHS.Kind;
  5595. return false;
  5596. }
  5597. };
  5598. /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the
  5599. /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind.
  5600. using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>;
  5601. AccessSet *AccessKind2Accesses[llvm::CTLog2<VALID_STATE>()];
  5602. /// Categorize the pointer arguments of CB that might access memory in
  5603. /// AccessedLoc and update the state and access map accordingly.
  5604. void
  5605. categorizeArgumentPointerLocations(Attributor &A, CallBase &CB,
  5606. AAMemoryLocation::StateType &AccessedLocs,
  5607. bool &Changed);
  5608. /// Return the kind(s) of location that may be accessed by \p V.
  5609. AAMemoryLocation::MemoryLocationsKind
  5610. categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed);
  5611. /// Return the access kind as determined by \p I.
  5612. AccessKind getAccessKindFromInst(const Instruction *I) {
  5613. AccessKind AK = READ_WRITE;
  5614. if (I) {
  5615. AK = I->mayReadFromMemory() ? READ : NONE;
  5616. AK = AccessKind(AK | (I->mayWriteToMemory() ? WRITE : NONE));
  5617. }
  5618. return AK;
  5619. }
  5620. /// Update the state \p State and the AccessKind2Accesses given that \p I is
  5621. /// an access of kind \p AK to a \p MLK memory location with the access
  5622. /// pointer \p Ptr.
  5623. void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
  5624. MemoryLocationsKind MLK, const Instruction *I,
  5625. const Value *Ptr, bool &Changed,
  5626. AccessKind AK = READ_WRITE) {
  5627. assert(isPowerOf2_32(MLK) && "Expected a single location set!");
  5628. auto *&Accesses = AccessKind2Accesses[llvm::Log2_32(MLK)];
  5629. if (!Accesses)
  5630. Accesses = new (Allocator) AccessSet();
  5631. Changed |= Accesses->insert(AccessInfo{I, Ptr, AK}).second;
  5632. State.removeAssumedBits(MLK);
  5633. }
  5634. /// Determine the underlying locations kinds for \p Ptr, e.g., globals or
  5635. /// arguments, and update the state and access map accordingly.
  5636. void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr,
  5637. AAMemoryLocation::StateType &State, bool &Changed);
  5638. /// Used to allocate access sets.
  5639. BumpPtrAllocator &Allocator;
  5640. /// The set of IR attributes AAMemoryLocation deals with.
  5641. static const Attribute::AttrKind AttrKinds[4];
  5642. };
  5643. const Attribute::AttrKind AAMemoryLocationImpl::AttrKinds[] = {
  5644. Attribute::ReadNone, Attribute::InaccessibleMemOnly, Attribute::ArgMemOnly,
  5645. Attribute::InaccessibleMemOrArgMemOnly};
  5646. void AAMemoryLocationImpl::categorizePtrValue(
  5647. Attributor &A, const Instruction &I, const Value &Ptr,
  5648. AAMemoryLocation::StateType &State, bool &Changed) {
  5649. LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for "
  5650. << Ptr << " ["
  5651. << getMemoryLocationsAsStr(State.getAssumed()) << "]\n");
  5652. auto StripGEPCB = [](Value *V) -> Value * {
  5653. auto *GEP = dyn_cast<GEPOperator>(V);
  5654. while (GEP) {
  5655. V = GEP->getPointerOperand();
  5656. GEP = dyn_cast<GEPOperator>(V);
  5657. }
  5658. return V;
  5659. };
  5660. auto VisitValueCB = [&](Value &V, const Instruction *,
  5661. AAMemoryLocation::StateType &T,
  5662. bool Stripped) -> bool {
  5663. // TODO: recognize the TBAA used for constant accesses.
  5664. MemoryLocationsKind MLK = NO_LOCATIONS;
  5665. assert(!isa<GEPOperator>(V) && "GEPs should have been stripped.");
  5666. if (isa<UndefValue>(V))
  5667. return true;
  5668. if (auto *Arg = dyn_cast<Argument>(&V)) {
  5669. if (Arg->hasByValAttr())
  5670. MLK = NO_LOCAL_MEM;
  5671. else
  5672. MLK = NO_ARGUMENT_MEM;
  5673. } else if (auto *GV = dyn_cast<GlobalValue>(&V)) {
  5674. // Reading constant memory is not treated as a read "effect" by the
  5675. // function attr pass so we won't neither. Constants defined by TBAA are
  5676. // similar. (We know we do not write it because it is constant.)
  5677. if (auto *GVar = dyn_cast<GlobalVariable>(GV))
  5678. if (GVar->isConstant())
  5679. return true;
  5680. if (GV->hasLocalLinkage())
  5681. MLK = NO_GLOBAL_INTERNAL_MEM;
  5682. else
  5683. MLK = NO_GLOBAL_EXTERNAL_MEM;
  5684. } else if (isa<ConstantPointerNull>(V) &&
  5685. !NullPointerIsDefined(getAssociatedFunction(),
  5686. V.getType()->getPointerAddressSpace())) {
  5687. return true;
  5688. } else if (isa<AllocaInst>(V)) {
  5689. MLK = NO_LOCAL_MEM;
  5690. } else if (const auto *CB = dyn_cast<CallBase>(&V)) {
  5691. const auto &NoAliasAA =
  5692. A.getAAFor<AANoAlias>(*this, IRPosition::callsite_returned(*CB));
  5693. if (NoAliasAA.isAssumedNoAlias())
  5694. MLK = NO_MALLOCED_MEM;
  5695. else
  5696. MLK = NO_UNKOWN_MEM;
  5697. } else {
  5698. MLK = NO_UNKOWN_MEM;
  5699. }
  5700. assert(MLK != NO_LOCATIONS && "No location specified!");
  5701. updateStateAndAccessesMap(T, MLK, &I, &V, Changed,
  5702. getAccessKindFromInst(&I));
  5703. LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value cannot be categorized: "
  5704. << V << " -> " << getMemoryLocationsAsStr(T.getAssumed())
  5705. << "\n");
  5706. return true;
  5707. };
  5708. if (!genericValueTraversal<AAMemoryLocation, AAMemoryLocation::StateType>(
  5709. A, IRPosition::value(Ptr), *this, State, VisitValueCB, getCtxI(),
  5710. /* UseValueSimplify */ true,
  5711. /* MaxValues */ 32, StripGEPCB)) {
  5712. LLVM_DEBUG(
  5713. dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n");
  5714. updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed,
  5715. getAccessKindFromInst(&I));
  5716. } else {
  5717. LLVM_DEBUG(
  5718. dbgs()
  5719. << "[AAMemoryLocation] Accessed locations with pointer locations: "
  5720. << getMemoryLocationsAsStr(State.getAssumed()) << "\n");
  5721. }
  5722. }
  5723. void AAMemoryLocationImpl::categorizeArgumentPointerLocations(
  5724. Attributor &A, CallBase &CB, AAMemoryLocation::StateType &AccessedLocs,
  5725. bool &Changed) {
  5726. for (unsigned ArgNo = 0, E = CB.getNumArgOperands(); ArgNo < E; ++ArgNo) {
  5727. // Skip non-pointer arguments.
  5728. const Value *ArgOp = CB.getArgOperand(ArgNo);
  5729. if (!ArgOp->getType()->isPtrOrPtrVectorTy())
  5730. continue;
  5731. // Skip readnone arguments.
  5732. const IRPosition &ArgOpIRP = IRPosition::callsite_argument(CB, ArgNo);
  5733. const auto &ArgOpMemLocationAA = A.getAAFor<AAMemoryBehavior>(
  5734. *this, ArgOpIRP, /* TrackDependence */ true, DepClassTy::OPTIONAL);
  5735. if (ArgOpMemLocationAA.isAssumedReadNone())
  5736. continue;
  5737. // Categorize potentially accessed pointer arguments as if there was an
  5738. // access instruction with them as pointer.
  5739. categorizePtrValue(A, CB, *ArgOp, AccessedLocs, Changed);
  5740. }
  5741. }
  5742. AAMemoryLocation::MemoryLocationsKind
  5743. AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I,
  5744. bool &Changed) {
  5745. LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for "
  5746. << I << "\n");
  5747. AAMemoryLocation::StateType AccessedLocs;
  5748. AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
  5749. if (auto *CB = dyn_cast<CallBase>(&I)) {
  5750. // First check if we assume any memory is access is visible.
  5751. const auto &CBMemLocationAA =
  5752. A.getAAFor<AAMemoryLocation>(*this, IRPosition::callsite_function(*CB));
  5753. LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I
  5754. << " [" << CBMemLocationAA << "]\n");
  5755. if (CBMemLocationAA.isAssumedReadNone())
  5756. return NO_LOCATIONS;
  5757. if (CBMemLocationAA.isAssumedInaccessibleMemOnly()) {
  5758. updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr,
  5759. Changed, getAccessKindFromInst(&I));
  5760. return AccessedLocs.getAssumed();
  5761. }
  5762. uint32_t CBAssumedNotAccessedLocs =
  5763. CBMemLocationAA.getAssumedNotAccessedLocation();
  5764. // Set the argmemonly and global bit as we handle them separately below.
  5765. uint32_t CBAssumedNotAccessedLocsNoArgMem =
  5766. CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
  5767. for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
  5768. if (CBAssumedNotAccessedLocsNoArgMem & CurMLK)
  5769. continue;
  5770. updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed,
  5771. getAccessKindFromInst(&I));
  5772. }
  5773. // Now handle global memory if it might be accessed. This is slightly tricky
  5774. // as NO_GLOBAL_MEM has multiple bits set.
  5775. bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
  5776. if (HasGlobalAccesses) {
  5777. auto AccessPred = [&](const Instruction *, const Value *Ptr,
  5778. AccessKind Kind, MemoryLocationsKind MLK) {
  5779. updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed,
  5780. getAccessKindFromInst(&I));
  5781. return true;
  5782. };
  5783. if (!CBMemLocationAA.checkForAllAccessesToMemoryKind(
  5784. AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false)))
  5785. return AccessedLocs.getWorstState();
  5786. }
  5787. LLVM_DEBUG(
  5788. dbgs() << "[AAMemoryLocation] Accessed state before argument handling: "
  5789. << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
  5790. // Now handle argument memory if it might be accessed.
  5791. bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
  5792. if (HasArgAccesses)
  5793. categorizeArgumentPointerLocations(A, *CB, AccessedLocs, Changed);
  5794. LLVM_DEBUG(
  5795. dbgs() << "[AAMemoryLocation] Accessed state after argument handling: "
  5796. << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
  5797. return AccessedLocs.getAssumed();
  5798. }
  5799. if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) {
  5800. LLVM_DEBUG(
  5801. dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: "
  5802. << I << " [" << *Ptr << "]\n");
  5803. categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed);
  5804. return AccessedLocs.getAssumed();
  5805. }
  5806. LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: "
  5807. << I << "\n");
  5808. updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed,
  5809. getAccessKindFromInst(&I));
  5810. return AccessedLocs.getAssumed();
  5811. }
  5812. /// An AA to represent the memory behavior function attributes.
  5813. struct AAMemoryLocationFunction final : public AAMemoryLocationImpl {
  5814. AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A)
  5815. : AAMemoryLocationImpl(IRP, A) {}
  5816. /// See AbstractAttribute::updateImpl(Attributor &A).
  5817. virtual ChangeStatus updateImpl(Attributor &A) override {
  5818. const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
  5819. *this, getIRPosition(), /* TrackDependence */ false);
  5820. if (MemBehaviorAA.isAssumedReadNone()) {
  5821. if (MemBehaviorAA.isKnownReadNone())
  5822. return indicateOptimisticFixpoint();
  5823. assert(isAssumedReadNone() &&
  5824. "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
  5825. A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
  5826. return ChangeStatus::UNCHANGED;
  5827. }
  5828. // The current assumed state used to determine a change.
  5829. auto AssumedState = getAssumed();
  5830. bool Changed = false;
  5831. auto CheckRWInst = [&](Instruction &I) {
  5832. MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed);
  5833. LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I
  5834. << ": " << getMemoryLocationsAsStr(MLK) << "\n");
  5835. removeAssumedBits(inverseLocation(MLK, false, false));
  5836. // Stop once only the valid bit set in the *not assumed location*, thus
  5837. // once we don't actually exclude any memory locations in the state.
  5838. return getAssumedNotAccessedLocation() != VALID_STATE;
  5839. };
  5840. if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this))
  5841. return indicatePessimisticFixpoint();
  5842. Changed |= AssumedState != getAssumed();
  5843. return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
  5844. }
  5845. /// See AbstractAttribute::trackStatistics()
  5846. void trackStatistics() const override {
  5847. if (isAssumedReadNone())
  5848. STATS_DECLTRACK_FN_ATTR(readnone)
  5849. else if (isAssumedArgMemOnly())
  5850. STATS_DECLTRACK_FN_ATTR(argmemonly)
  5851. else if (isAssumedInaccessibleMemOnly())
  5852. STATS_DECLTRACK_FN_ATTR(inaccessiblememonly)
  5853. else if (isAssumedInaccessibleOrArgMemOnly())
  5854. STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly)
  5855. }
  5856. };
  5857. /// AAMemoryLocation attribute for call sites.
  5858. struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
  5859. AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A)
  5860. : AAMemoryLocationImpl(IRP, A) {}
  5861. /// See AbstractAttribute::initialize(...).
  5862. void initialize(Attributor &A) override {
  5863. AAMemoryLocationImpl::initialize(A);
  5864. Function *F = getAssociatedFunction();
  5865. if (!F || F->isDeclaration())
  5866. indicatePessimisticFixpoint();
  5867. }
  5868. /// See AbstractAttribute::updateImpl(...).
  5869. ChangeStatus updateImpl(Attributor &A) override {
  5870. // TODO: Once we have call site specific value information we can provide
  5871. // call site specific liveness liveness information and then it makes
  5872. // sense to specialize attributes for call sites arguments instead of
  5873. // redirecting requests to the callee argument.
  5874. Function *F = getAssociatedFunction();
  5875. const IRPosition &FnPos = IRPosition::function(*F);
  5876. auto &FnAA = A.getAAFor<AAMemoryLocation>(*this, FnPos);
  5877. bool Changed = false;
  5878. auto AccessPred = [&](const Instruction *I, const Value *Ptr,
  5879. AccessKind Kind, MemoryLocationsKind MLK) {
  5880. updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed,
  5881. getAccessKindFromInst(I));
  5882. return true;
  5883. };
  5884. if (!FnAA.checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
  5885. return indicatePessimisticFixpoint();
  5886. return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
  5887. }
  5888. /// See AbstractAttribute::trackStatistics()
  5889. void trackStatistics() const override {
  5890. if (isAssumedReadNone())
  5891. STATS_DECLTRACK_CS_ATTR(readnone)
  5892. }
  5893. };
  5894. /// ------------------ Value Constant Range Attribute -------------------------
  5895. struct AAValueConstantRangeImpl : AAValueConstantRange {
  5896. using StateType = IntegerRangeState;
  5897. AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A)
  5898. : AAValueConstantRange(IRP, A) {}
  5899. /// See AbstractAttribute::getAsStr().
  5900. const std::string getAsStr() const override {
  5901. std::string Str;
  5902. llvm::raw_string_ostream OS(Str);
  5903. OS << "range(" << getBitWidth() << ")<";
  5904. getKnown().print(OS);
  5905. OS << " / ";
  5906. getAssumed().print(OS);
  5907. OS << ">";
  5908. return OS.str();
  5909. }
  5910. /// Helper function to get a SCEV expr for the associated value at program
  5911. /// point \p I.
  5912. const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const {
  5913. if (!getAnchorScope())
  5914. return nullptr;
  5915. ScalarEvolution *SE =
  5916. A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
  5917. *getAnchorScope());
  5918. LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
  5919. *getAnchorScope());
  5920. if (!SE || !LI)
  5921. return nullptr;
  5922. const SCEV *S = SE->getSCEV(&getAssociatedValue());
  5923. if (!I)
  5924. return S;
  5925. return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent()));
  5926. }
  5927. /// Helper function to get a range from SCEV for the associated value at
  5928. /// program point \p I.
  5929. ConstantRange getConstantRangeFromSCEV(Attributor &A,
  5930. const Instruction *I = nullptr) const {
  5931. if (!getAnchorScope())
  5932. return getWorstState(getBitWidth());
  5933. ScalarEvolution *SE =
  5934. A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
  5935. *getAnchorScope());
  5936. const SCEV *S = getSCEV(A, I);
  5937. if (!SE || !S)
  5938. return getWorstState(getBitWidth());
  5939. return SE->getUnsignedRange(S);
  5940. }
  5941. /// Helper function to get a range from LVI for the associated value at
  5942. /// program point \p I.
  5943. ConstantRange
  5944. getConstantRangeFromLVI(Attributor &A,
  5945. const Instruction *CtxI = nullptr) const {
  5946. if (!getAnchorScope())
  5947. return getWorstState(getBitWidth());
  5948. LazyValueInfo *LVI =
  5949. A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
  5950. *getAnchorScope());
  5951. if (!LVI || !CtxI)
  5952. return getWorstState(getBitWidth());
  5953. return LVI->getConstantRange(&getAssociatedValue(),
  5954. const_cast<Instruction *>(CtxI));
  5955. }
  5956. /// See AAValueConstantRange::getKnownConstantRange(..).
  5957. ConstantRange
  5958. getKnownConstantRange(Attributor &A,
  5959. const Instruction *CtxI = nullptr) const override {
  5960. if (!CtxI || CtxI == getCtxI())
  5961. return getKnown();
  5962. ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
  5963. ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
  5964. return getKnown().intersectWith(SCEVR).intersectWith(LVIR);
  5965. }
  5966. /// See AAValueConstantRange::getAssumedConstantRange(..).
  5967. ConstantRange
  5968. getAssumedConstantRange(Attributor &A,
  5969. const Instruction *CtxI = nullptr) const override {
  5970. // TODO: Make SCEV use Attributor assumption.
  5971. // We may be able to bound a variable range via assumptions in
  5972. // Attributor. ex.) If x is assumed to be in [1, 3] and y is known to
  5973. // evolve to x^2 + x, then we can say that y is in [2, 12].
  5974. if (!CtxI || CtxI == getCtxI())
  5975. return getAssumed();
  5976. ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
  5977. ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
  5978. return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
  5979. }
  5980. /// See AbstractAttribute::initialize(..).
  5981. void initialize(Attributor &A) override {
  5982. // Intersect a range given by SCEV.
  5983. intersectKnown(getConstantRangeFromSCEV(A, getCtxI()));
  5984. // Intersect a range given by LVI.
  5985. intersectKnown(getConstantRangeFromLVI(A, getCtxI()));
  5986. }
  5987. /// Helper function to create MDNode for range metadata.
  5988. static MDNode *
  5989. getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx,
  5990. const ConstantRange &AssumedConstantRange) {
  5991. Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get(
  5992. Ty, AssumedConstantRange.getLower())),
  5993. ConstantAsMetadata::get(ConstantInt::get(
  5994. Ty, AssumedConstantRange.getUpper()))};
  5995. return MDNode::get(Ctx, LowAndHigh);
  5996. }
  5997. /// Return true if \p Assumed is included in \p KnownRanges.
  5998. static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges) {
  5999. if (Assumed.isFullSet())
  6000. return false;
  6001. if (!KnownRanges)
  6002. return true;
  6003. // If multiple ranges are annotated in IR, we give up to annotate assumed
  6004. // range for now.
  6005. // TODO: If there exists a known range which containts assumed range, we
  6006. // can say assumed range is better.
  6007. if (KnownRanges->getNumOperands() > 2)
  6008. return false;
  6009. ConstantInt *Lower =
  6010. mdconst::extract<ConstantInt>(KnownRanges->getOperand(0));
  6011. ConstantInt *Upper =
  6012. mdconst::extract<ConstantInt>(KnownRanges->getOperand(1));
  6013. ConstantRange Known(Lower->getValue(), Upper->getValue());
  6014. return Known.contains(Assumed) && Known != Assumed;
  6015. }
  6016. /// Helper function to set range metadata.
  6017. static bool
  6018. setRangeMetadataIfisBetterRange(Instruction *I,
  6019. const ConstantRange &AssumedConstantRange) {
  6020. auto *OldRangeMD = I->getMetadata(LLVMContext::MD_range);
  6021. if (isBetterRange(AssumedConstantRange, OldRangeMD)) {
  6022. if (!AssumedConstantRange.isEmptySet()) {
  6023. I->setMetadata(LLVMContext::MD_range,
  6024. getMDNodeForConstantRange(I->getType(), I->getContext(),
  6025. AssumedConstantRange));
  6026. return true;
  6027. }
  6028. }
  6029. return false;
  6030. }
  6031. /// See AbstractAttribute::manifest()
  6032. ChangeStatus manifest(Attributor &A) override {
  6033. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  6034. ConstantRange AssumedConstantRange = getAssumedConstantRange(A);
  6035. assert(!AssumedConstantRange.isFullSet() && "Invalid state");
  6036. auto &V = getAssociatedValue();
  6037. if (!AssumedConstantRange.isEmptySet() &&
  6038. !AssumedConstantRange.isSingleElement()) {
  6039. if (Instruction *I = dyn_cast<Instruction>(&V)) {
  6040. assert(I == getCtxI() && "Should not annotate an instruction which is "
  6041. "not the context instruction");
  6042. if (isa<CallInst>(I) || isa<LoadInst>(I))
  6043. if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange))
  6044. Changed = ChangeStatus::CHANGED;
  6045. }
  6046. }
  6047. return Changed;
  6048. }
  6049. };
  6050. struct AAValueConstantRangeArgument final
  6051. : AAArgumentFromCallSiteArguments<
  6052. AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState> {
  6053. using Base = AAArgumentFromCallSiteArguments<
  6054. AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState>;
  6055. AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A)
  6056. : Base(IRP, A) {}
  6057. /// See AbstractAttribute::initialize(..).
  6058. void initialize(Attributor &A) override {
  6059. if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
  6060. indicatePessimisticFixpoint();
  6061. } else {
  6062. Base::initialize(A);
  6063. }
  6064. }
  6065. /// See AbstractAttribute::trackStatistics()
  6066. void trackStatistics() const override {
  6067. STATS_DECLTRACK_ARG_ATTR(value_range)
  6068. }
  6069. };
  6070. struct AAValueConstantRangeReturned
  6071. : AAReturnedFromReturnedValues<AAValueConstantRange,
  6072. AAValueConstantRangeImpl> {
  6073. using Base = AAReturnedFromReturnedValues<AAValueConstantRange,
  6074. AAValueConstantRangeImpl>;
  6075. AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A)
  6076. : Base(IRP, A) {}
  6077. /// See AbstractAttribute::initialize(...).
  6078. void initialize(Attributor &A) override {}
  6079. /// See AbstractAttribute::trackStatistics()
  6080. void trackStatistics() const override {
  6081. STATS_DECLTRACK_FNRET_ATTR(value_range)
  6082. }
  6083. };
  6084. struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
  6085. AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A)
  6086. : AAValueConstantRangeImpl(IRP, A) {}
  6087. /// See AbstractAttribute::initialize(...).
  6088. void initialize(Attributor &A) override {
  6089. AAValueConstantRangeImpl::initialize(A);
  6090. Value &V = getAssociatedValue();
  6091. if (auto *C = dyn_cast<ConstantInt>(&V)) {
  6092. unionAssumed(ConstantRange(C->getValue()));
  6093. indicateOptimisticFixpoint();
  6094. return;
  6095. }
  6096. if (isa<UndefValue>(&V)) {
  6097. // Collapse the undef state to 0.
  6098. unionAssumed(ConstantRange(APInt(getBitWidth(), 0)));
  6099. indicateOptimisticFixpoint();
  6100. return;
  6101. }
  6102. if (isa<CallBase>(&V))
  6103. return;
  6104. if (isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<CastInst>(&V))
  6105. return;
  6106. // If it is a load instruction with range metadata, use it.
  6107. if (LoadInst *LI = dyn_cast<LoadInst>(&V))
  6108. if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
  6109. intersectKnown(getConstantRangeFromMetadata(*RangeMD));
  6110. return;
  6111. }
  6112. // We can work with PHI and select instruction as we traverse their operands
  6113. // during update.
  6114. if (isa<SelectInst>(V) || isa<PHINode>(V))
  6115. return;
  6116. // Otherwise we give up.
  6117. indicatePessimisticFixpoint();
  6118. LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: "
  6119. << getAssociatedValue() << "\n");
  6120. }
  6121. bool calculateBinaryOperator(
  6122. Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T,
  6123. const Instruction *CtxI,
  6124. SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
  6125. Value *LHS = BinOp->getOperand(0);
  6126. Value *RHS = BinOp->getOperand(1);
  6127. // TODO: Allow non integers as well.
  6128. if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
  6129. return false;
  6130. auto &LHSAA =
  6131. A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*LHS));
  6132. QuerriedAAs.push_back(&LHSAA);
  6133. auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
  6134. auto &RHSAA =
  6135. A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*RHS));
  6136. QuerriedAAs.push_back(&RHSAA);
  6137. auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
  6138. auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange);
  6139. T.unionAssumed(AssumedRange);
  6140. // TODO: Track a known state too.
  6141. return T.isValidState();
  6142. }
  6143. bool calculateCastInst(
  6144. Attributor &A, CastInst *CastI, IntegerRangeState &T,
  6145. const Instruction *CtxI,
  6146. SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
  6147. assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!");
  6148. // TODO: Allow non integers as well.
  6149. Value &OpV = *CastI->getOperand(0);
  6150. if (!OpV.getType()->isIntegerTy())
  6151. return false;
  6152. auto &OpAA =
  6153. A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(OpV));
  6154. QuerriedAAs.push_back(&OpAA);
  6155. T.unionAssumed(
  6156. OpAA.getAssumed().castOp(CastI->getOpcode(), getState().getBitWidth()));
  6157. return T.isValidState();
  6158. }
  6159. bool
  6160. calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T,
  6161. const Instruction *CtxI,
  6162. SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
  6163. Value *LHS = CmpI->getOperand(0);
  6164. Value *RHS = CmpI->getOperand(1);
  6165. // TODO: Allow non integers as well.
  6166. if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
  6167. return false;
  6168. auto &LHSAA =
  6169. A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*LHS));
  6170. QuerriedAAs.push_back(&LHSAA);
  6171. auto &RHSAA =
  6172. A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*RHS));
  6173. QuerriedAAs.push_back(&RHSAA);
  6174. auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
  6175. auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
  6176. // If one of them is empty set, we can't decide.
  6177. if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
  6178. return true;
  6179. bool MustTrue = false, MustFalse = false;
  6180. auto AllowedRegion =
  6181. ConstantRange::makeAllowedICmpRegion(CmpI->getPredicate(), RHSAARange);
  6182. auto SatisfyingRegion = ConstantRange::makeSatisfyingICmpRegion(
  6183. CmpI->getPredicate(), RHSAARange);
  6184. if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
  6185. MustFalse = true;
  6186. if (SatisfyingRegion.contains(LHSAARange))
  6187. MustTrue = true;
  6188. assert((!MustTrue || !MustFalse) &&
  6189. "Either MustTrue or MustFalse should be false!");
  6190. if (MustTrue)
  6191. T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1)));
  6192. else if (MustFalse)
  6193. T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0)));
  6194. else
  6195. T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true));
  6196. LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " " << LHSAA
  6197. << " " << RHSAA << "\n");
  6198. // TODO: Track a known state too.
  6199. return T.isValidState();
  6200. }
  6201. /// See AbstractAttribute::updateImpl(...).
  6202. ChangeStatus updateImpl(Attributor &A) override {
  6203. auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
  6204. IntegerRangeState &T, bool Stripped) -> bool {
  6205. Instruction *I = dyn_cast<Instruction>(&V);
  6206. if (!I || isa<CallBase>(I)) {
  6207. // If the value is not instruction, we query AA to Attributor.
  6208. const auto &AA =
  6209. A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(V));
  6210. // Clamp operator is not used to utilize a program point CtxI.
  6211. T.unionAssumed(AA.getAssumedConstantRange(A, CtxI));
  6212. return T.isValidState();
  6213. }
  6214. SmallVector<const AAValueConstantRange *, 4> QuerriedAAs;
  6215. if (auto *BinOp = dyn_cast<BinaryOperator>(I)) {
  6216. if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs))
  6217. return false;
  6218. } else if (auto *CmpI = dyn_cast<CmpInst>(I)) {
  6219. if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs))
  6220. return false;
  6221. } else if (auto *CastI = dyn_cast<CastInst>(I)) {
  6222. if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs))
  6223. return false;
  6224. } else {
  6225. // Give up with other instructions.
  6226. // TODO: Add other instructions
  6227. T.indicatePessimisticFixpoint();
  6228. return false;
  6229. }
  6230. // Catch circular reasoning in a pessimistic way for now.
  6231. // TODO: Check how the range evolves and if we stripped anything, see also
  6232. // AADereferenceable or AAAlign for similar situations.
  6233. for (const AAValueConstantRange *QueriedAA : QuerriedAAs) {
  6234. if (QueriedAA != this)
  6235. continue;
  6236. // If we are in a stady state we do not need to worry.
  6237. if (T.getAssumed() == getState().getAssumed())
  6238. continue;
  6239. T.indicatePessimisticFixpoint();
  6240. }
  6241. return T.isValidState();
  6242. };
  6243. IntegerRangeState T(getBitWidth());
  6244. if (!genericValueTraversal<AAValueConstantRange, IntegerRangeState>(
  6245. A, getIRPosition(), *this, T, VisitValueCB, getCtxI(),
  6246. /* UseValueSimplify */ false))
  6247. return indicatePessimisticFixpoint();
  6248. return clampStateAndIndicateChange(getState(), T);
  6249. }
  6250. /// See AbstractAttribute::trackStatistics()
  6251. void trackStatistics() const override {
  6252. STATS_DECLTRACK_FLOATING_ATTR(value_range)
  6253. }
  6254. };
  6255. struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
  6256. AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A)
  6257. : AAValueConstantRangeImpl(IRP, A) {}
  6258. /// See AbstractAttribute::initialize(...).
  6259. ChangeStatus updateImpl(Attributor &A) override {
  6260. llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will "
  6261. "not be called");
  6262. }
  6263. /// See AbstractAttribute::trackStatistics()
  6264. void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) }
  6265. };
  6266. struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
  6267. AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A)
  6268. : AAValueConstantRangeFunction(IRP, A) {}
  6269. /// See AbstractAttribute::trackStatistics()
  6270. void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) }
  6271. };
  6272. struct AAValueConstantRangeCallSiteReturned
  6273. : AACallSiteReturnedFromReturned<AAValueConstantRange,
  6274. AAValueConstantRangeImpl> {
  6275. AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A)
  6276. : AACallSiteReturnedFromReturned<AAValueConstantRange,
  6277. AAValueConstantRangeImpl>(IRP, A) {}
  6278. /// See AbstractAttribute::initialize(...).
  6279. void initialize(Attributor &A) override {
  6280. // If it is a load instruction with range metadata, use the metadata.
  6281. if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue()))
  6282. if (auto *RangeMD = CI->getMetadata(LLVMContext::MD_range))
  6283. intersectKnown(getConstantRangeFromMetadata(*RangeMD));
  6284. AAValueConstantRangeImpl::initialize(A);
  6285. }
  6286. /// See AbstractAttribute::trackStatistics()
  6287. void trackStatistics() const override {
  6288. STATS_DECLTRACK_CSRET_ATTR(value_range)
  6289. }
  6290. };
  6291. struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
  6292. AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A)
  6293. : AAValueConstantRangeFloating(IRP, A) {}
  6294. /// See AbstractAttribute::manifest()
  6295. ChangeStatus manifest(Attributor &A) override {
  6296. return ChangeStatus::UNCHANGED;
  6297. }
  6298. /// See AbstractAttribute::trackStatistics()
  6299. void trackStatistics() const override {
  6300. STATS_DECLTRACK_CSARG_ATTR(value_range)
  6301. }
  6302. };
  6303. /// ------------------ Potential Values Attribute -------------------------
  6304. struct AAPotentialValuesImpl : AAPotentialValues {
  6305. using StateType = PotentialConstantIntValuesState;
  6306. AAPotentialValuesImpl(const IRPosition &IRP, Attributor &A)
  6307. : AAPotentialValues(IRP, A) {}
  6308. /// See AbstractAttribute::getAsStr().
  6309. const std::string getAsStr() const override {
  6310. std::string Str;
  6311. llvm::raw_string_ostream OS(Str);
  6312. OS << getState();
  6313. return OS.str();
  6314. }
  6315. /// See AbstractAttribute::updateImpl(...).
  6316. ChangeStatus updateImpl(Attributor &A) override {
  6317. return indicatePessimisticFixpoint();
  6318. }
  6319. };
  6320. struct AAPotentialValuesArgument final
  6321. : AAArgumentFromCallSiteArguments<AAPotentialValues, AAPotentialValuesImpl,
  6322. PotentialConstantIntValuesState> {
  6323. using Base =
  6324. AAArgumentFromCallSiteArguments<AAPotentialValues, AAPotentialValuesImpl,
  6325. PotentialConstantIntValuesState>;
  6326. AAPotentialValuesArgument(const IRPosition &IRP, Attributor &A)
  6327. : Base(IRP, A) {}
  6328. /// See AbstractAttribute::initialize(..).
  6329. void initialize(Attributor &A) override {
  6330. if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
  6331. indicatePessimisticFixpoint();
  6332. } else {
  6333. Base::initialize(A);
  6334. }
  6335. }
  6336. /// See AbstractAttribute::trackStatistics()
  6337. void trackStatistics() const override {
  6338. STATS_DECLTRACK_ARG_ATTR(potential_values)
  6339. }
  6340. };
  6341. struct AAPotentialValuesReturned
  6342. : AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl> {
  6343. using Base =
  6344. AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl>;
  6345. AAPotentialValuesReturned(const IRPosition &IRP, Attributor &A)
  6346. : Base(IRP, A) {}
  6347. /// See AbstractAttribute::trackStatistics()
  6348. void trackStatistics() const override {
  6349. STATS_DECLTRACK_FNRET_ATTR(potential_values)
  6350. }
  6351. };
  6352. struct AAPotentialValuesFloating : AAPotentialValuesImpl {
  6353. AAPotentialValuesFloating(const IRPosition &IRP, Attributor &A)
  6354. : AAPotentialValuesImpl(IRP, A) {}
  6355. /// See AbstractAttribute::initialize(..).
  6356. void initialize(Attributor &A) override {
  6357. Value &V = getAssociatedValue();
  6358. if (auto *C = dyn_cast<ConstantInt>(&V)) {
  6359. unionAssumed(C->getValue());
  6360. indicateOptimisticFixpoint();
  6361. return;
  6362. }
  6363. if (isa<UndefValue>(&V)) {
  6364. unionAssumedWithUndef();
  6365. indicateOptimisticFixpoint();
  6366. return;
  6367. }
  6368. if (isa<BinaryOperator>(&V) || isa<ICmpInst>(&V) || isa<CastInst>(&V))
  6369. return;
  6370. if (isa<SelectInst>(V) || isa<PHINode>(V))
  6371. return;
  6372. indicatePessimisticFixpoint();
  6373. LLVM_DEBUG(dbgs() << "[AAPotentialValues] We give up: "
  6374. << getAssociatedValue() << "\n");
  6375. }
  6376. static bool calculateICmpInst(const ICmpInst *ICI, const APInt &LHS,
  6377. const APInt &RHS) {
  6378. ICmpInst::Predicate Pred = ICI->getPredicate();
  6379. switch (Pred) {
  6380. case ICmpInst::ICMP_UGT:
  6381. return LHS.ugt(RHS);
  6382. case ICmpInst::ICMP_SGT:
  6383. return LHS.sgt(RHS);
  6384. case ICmpInst::ICMP_EQ:
  6385. return LHS.eq(RHS);
  6386. case ICmpInst::ICMP_UGE:
  6387. return LHS.uge(RHS);
  6388. case ICmpInst::ICMP_SGE:
  6389. return LHS.sge(RHS);
  6390. case ICmpInst::ICMP_ULT:
  6391. return LHS.ult(RHS);
  6392. case ICmpInst::ICMP_SLT:
  6393. return LHS.slt(RHS);
  6394. case ICmpInst::ICMP_NE:
  6395. return LHS.ne(RHS);
  6396. case ICmpInst::ICMP_ULE:
  6397. return LHS.ule(RHS);
  6398. case ICmpInst::ICMP_SLE:
  6399. return LHS.sle(RHS);
  6400. default:
  6401. llvm_unreachable("Invalid ICmp predicate!");
  6402. }
  6403. }
  6404. static APInt calculateCastInst(const CastInst *CI, const APInt &Src,
  6405. uint32_t ResultBitWidth) {
  6406. Instruction::CastOps CastOp = CI->getOpcode();
  6407. switch (CastOp) {
  6408. default:
  6409. llvm_unreachable("unsupported or not integer cast");
  6410. case Instruction::Trunc:
  6411. return Src.trunc(ResultBitWidth);
  6412. case Instruction::SExt:
  6413. return Src.sext(ResultBitWidth);
  6414. case Instruction::ZExt:
  6415. return Src.zext(ResultBitWidth);
  6416. case Instruction::BitCast:
  6417. return Src;
  6418. }
  6419. }
  6420. static APInt calculateBinaryOperator(const BinaryOperator *BinOp,
  6421. const APInt &LHS, const APInt &RHS,
  6422. bool &SkipOperation, bool &Unsupported) {
  6423. Instruction::BinaryOps BinOpcode = BinOp->getOpcode();
  6424. // Unsupported is set to true when the binary operator is not supported.
  6425. // SkipOperation is set to true when UB occur with the given operand pair
  6426. // (LHS, RHS).
  6427. // TODO: we should look at nsw and nuw keywords to handle operations
  6428. // that create poison or undef value.
  6429. switch (BinOpcode) {
  6430. default:
  6431. Unsupported = true;
  6432. return LHS;
  6433. case Instruction::Add:
  6434. return LHS + RHS;
  6435. case Instruction::Sub:
  6436. return LHS - RHS;
  6437. case Instruction::Mul:
  6438. return LHS * RHS;
  6439. case Instruction::UDiv:
  6440. if (RHS.isNullValue()) {
  6441. SkipOperation = true;
  6442. return LHS;
  6443. }
  6444. return LHS.udiv(RHS);
  6445. case Instruction::SDiv:
  6446. if (RHS.isNullValue()) {
  6447. SkipOperation = true;
  6448. return LHS;
  6449. }
  6450. return LHS.sdiv(RHS);
  6451. case Instruction::URem:
  6452. if (RHS.isNullValue()) {
  6453. SkipOperation = true;
  6454. return LHS;
  6455. }
  6456. return LHS.urem(RHS);
  6457. case Instruction::SRem:
  6458. if (RHS.isNullValue()) {
  6459. SkipOperation = true;
  6460. return LHS;
  6461. }
  6462. return LHS.srem(RHS);
  6463. case Instruction::Shl:
  6464. return LHS.shl(RHS);
  6465. case Instruction::LShr:
  6466. return LHS.lshr(RHS);
  6467. case Instruction::AShr:
  6468. return LHS.ashr(RHS);
  6469. case Instruction::And:
  6470. return LHS & RHS;
  6471. case Instruction::Or:
  6472. return LHS | RHS;
  6473. case Instruction::Xor:
  6474. return LHS ^ RHS;
  6475. }
  6476. }
  6477. bool calculateBinaryOperatorAndTakeUnion(const BinaryOperator *BinOp,
  6478. const APInt &LHS, const APInt &RHS) {
  6479. bool SkipOperation = false;
  6480. bool Unsupported = false;
  6481. APInt Result =
  6482. calculateBinaryOperator(BinOp, LHS, RHS, SkipOperation, Unsupported);
  6483. if (Unsupported)
  6484. return false;
  6485. // If SkipOperation is true, we can ignore this operand pair (L, R).
  6486. if (!SkipOperation)
  6487. unionAssumed(Result);
  6488. return isValidState();
  6489. }
  6490. ChangeStatus updateWithICmpInst(Attributor &A, ICmpInst *ICI) {
  6491. auto AssumedBefore = getAssumed();
  6492. Value *LHS = ICI->getOperand(0);
  6493. Value *RHS = ICI->getOperand(1);
  6494. if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
  6495. return indicatePessimisticFixpoint();
  6496. auto &LHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*LHS));
  6497. if (!LHSAA.isValidState())
  6498. return indicatePessimisticFixpoint();
  6499. auto &RHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*RHS));
  6500. if (!RHSAA.isValidState())
  6501. return indicatePessimisticFixpoint();
  6502. const DenseSet<APInt> &LHSAAPVS = LHSAA.getAssumedSet();
  6503. const DenseSet<APInt> &RHSAAPVS = RHSAA.getAssumedSet();
  6504. // TODO: make use of undef flag to limit potential values aggressively.
  6505. bool MaybeTrue = false, MaybeFalse = false;
  6506. const APInt Zero(RHS->getType()->getIntegerBitWidth(), 0);
  6507. if (LHSAA.undefIsContained() && RHSAA.undefIsContained()) {
  6508. // The result of any comparison between undefs can be soundly replaced
  6509. // with undef.
  6510. unionAssumedWithUndef();
  6511. } else if (LHSAA.undefIsContained()) {
  6512. bool MaybeTrue = false, MaybeFalse = false;
  6513. for (const APInt &R : RHSAAPVS) {
  6514. bool CmpResult = calculateICmpInst(ICI, Zero, R);
  6515. MaybeTrue |= CmpResult;
  6516. MaybeFalse |= !CmpResult;
  6517. if (MaybeTrue & MaybeFalse)
  6518. return indicatePessimisticFixpoint();
  6519. }
  6520. } else if (RHSAA.undefIsContained()) {
  6521. for (const APInt &L : LHSAAPVS) {
  6522. bool CmpResult = calculateICmpInst(ICI, L, Zero);
  6523. MaybeTrue |= CmpResult;
  6524. MaybeFalse |= !CmpResult;
  6525. if (MaybeTrue & MaybeFalse)
  6526. return indicatePessimisticFixpoint();
  6527. }
  6528. } else {
  6529. for (const APInt &L : LHSAAPVS) {
  6530. for (const APInt &R : RHSAAPVS) {
  6531. bool CmpResult = calculateICmpInst(ICI, L, R);
  6532. MaybeTrue |= CmpResult;
  6533. MaybeFalse |= !CmpResult;
  6534. if (MaybeTrue & MaybeFalse)
  6535. return indicatePessimisticFixpoint();
  6536. }
  6537. }
  6538. }
  6539. if (MaybeTrue)
  6540. unionAssumed(APInt(/* numBits */ 1, /* val */ 1));
  6541. if (MaybeFalse)
  6542. unionAssumed(APInt(/* numBits */ 1, /* val */ 0));
  6543. return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
  6544. : ChangeStatus::CHANGED;
  6545. }
  6546. ChangeStatus updateWithSelectInst(Attributor &A, SelectInst *SI) {
  6547. auto AssumedBefore = getAssumed();
  6548. Value *LHS = SI->getTrueValue();
  6549. Value *RHS = SI->getFalseValue();
  6550. if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
  6551. return indicatePessimisticFixpoint();
  6552. // TODO: Use assumed simplified condition value
  6553. auto &LHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*LHS));
  6554. if (!LHSAA.isValidState())
  6555. return indicatePessimisticFixpoint();
  6556. auto &RHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*RHS));
  6557. if (!RHSAA.isValidState())
  6558. return indicatePessimisticFixpoint();
  6559. if (LHSAA.undefIsContained() && RHSAA.undefIsContained())
  6560. // select i1 *, undef , undef => undef
  6561. unionAssumedWithUndef();
  6562. else {
  6563. unionAssumed(LHSAA);
  6564. unionAssumed(RHSAA);
  6565. }
  6566. return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
  6567. : ChangeStatus::CHANGED;
  6568. }
  6569. ChangeStatus updateWithCastInst(Attributor &A, CastInst *CI) {
  6570. auto AssumedBefore = getAssumed();
  6571. if (!CI->isIntegerCast())
  6572. return indicatePessimisticFixpoint();
  6573. assert(CI->getNumOperands() == 1 && "Expected cast to be unary!");
  6574. uint32_t ResultBitWidth = CI->getDestTy()->getIntegerBitWidth();
  6575. Value *Src = CI->getOperand(0);
  6576. auto &SrcAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*Src));
  6577. if (!SrcAA.isValidState())
  6578. return indicatePessimisticFixpoint();
  6579. const DenseSet<APInt> &SrcAAPVS = SrcAA.getAssumedSet();
  6580. if (SrcAA.undefIsContained())
  6581. unionAssumedWithUndef();
  6582. else {
  6583. for (const APInt &S : SrcAAPVS) {
  6584. APInt T = calculateCastInst(CI, S, ResultBitWidth);
  6585. unionAssumed(T);
  6586. }
  6587. }
  6588. return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
  6589. : ChangeStatus::CHANGED;
  6590. }
  6591. ChangeStatus updateWithBinaryOperator(Attributor &A, BinaryOperator *BinOp) {
  6592. auto AssumedBefore = getAssumed();
  6593. Value *LHS = BinOp->getOperand(0);
  6594. Value *RHS = BinOp->getOperand(1);
  6595. if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
  6596. return indicatePessimisticFixpoint();
  6597. auto &LHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*LHS));
  6598. if (!LHSAA.isValidState())
  6599. return indicatePessimisticFixpoint();
  6600. auto &RHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*RHS));
  6601. if (!RHSAA.isValidState())
  6602. return indicatePessimisticFixpoint();
  6603. const DenseSet<APInt> &LHSAAPVS = LHSAA.getAssumedSet();
  6604. const DenseSet<APInt> &RHSAAPVS = RHSAA.getAssumedSet();
  6605. const APInt Zero = APInt(LHS->getType()->getIntegerBitWidth(), 0);
  6606. // TODO: make use of undef flag to limit potential values aggressively.
  6607. if (LHSAA.undefIsContained() && RHSAA.undefIsContained()) {
  6608. if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, Zero))
  6609. return indicatePessimisticFixpoint();
  6610. } else if (LHSAA.undefIsContained()) {
  6611. for (const APInt &R : RHSAAPVS) {
  6612. if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, R))
  6613. return indicatePessimisticFixpoint();
  6614. }
  6615. } else if (RHSAA.undefIsContained()) {
  6616. for (const APInt &L : LHSAAPVS) {
  6617. if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, Zero))
  6618. return indicatePessimisticFixpoint();
  6619. }
  6620. } else {
  6621. for (const APInt &L : LHSAAPVS) {
  6622. for (const APInt &R : RHSAAPVS) {
  6623. if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R))
  6624. return indicatePessimisticFixpoint();
  6625. }
  6626. }
  6627. }
  6628. return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
  6629. : ChangeStatus::CHANGED;
  6630. }
  6631. ChangeStatus updateWithPHINode(Attributor &A, PHINode *PHI) {
  6632. auto AssumedBefore = getAssumed();
  6633. for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
  6634. Value *IncomingValue = PHI->getIncomingValue(u);
  6635. auto &PotentialValuesAA = A.getAAFor<AAPotentialValues>(
  6636. *this, IRPosition::value(*IncomingValue));
  6637. if (!PotentialValuesAA.isValidState())
  6638. return indicatePessimisticFixpoint();
  6639. if (PotentialValuesAA.undefIsContained())
  6640. unionAssumedWithUndef();
  6641. else
  6642. unionAssumed(PotentialValuesAA.getAssumed());
  6643. }
  6644. return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
  6645. : ChangeStatus::CHANGED;
  6646. }
  6647. /// See AbstractAttribute::updateImpl(...).
  6648. ChangeStatus updateImpl(Attributor &A) override {
  6649. Value &V = getAssociatedValue();
  6650. Instruction *I = dyn_cast<Instruction>(&V);
  6651. if (auto *ICI = dyn_cast<ICmpInst>(I))
  6652. return updateWithICmpInst(A, ICI);
  6653. if (auto *SI = dyn_cast<SelectInst>(I))
  6654. return updateWithSelectInst(A, SI);
  6655. if (auto *CI = dyn_cast<CastInst>(I))
  6656. return updateWithCastInst(A, CI);
  6657. if (auto *BinOp = dyn_cast<BinaryOperator>(I))
  6658. return updateWithBinaryOperator(A, BinOp);
  6659. if (auto *PHI = dyn_cast<PHINode>(I))
  6660. return updateWithPHINode(A, PHI);
  6661. return indicatePessimisticFixpoint();
  6662. }
  6663. /// See AbstractAttribute::trackStatistics()
  6664. void trackStatistics() const override {
  6665. STATS_DECLTRACK_FLOATING_ATTR(potential_values)
  6666. }
  6667. };
  6668. struct AAPotentialValuesFunction : AAPotentialValuesImpl {
  6669. AAPotentialValuesFunction(const IRPosition &IRP, Attributor &A)
  6670. : AAPotentialValuesImpl(IRP, A) {}
  6671. /// See AbstractAttribute::initialize(...).
  6672. ChangeStatus updateImpl(Attributor &A) override {
  6673. llvm_unreachable("AAPotentialValues(Function|CallSite)::updateImpl will "
  6674. "not be called");
  6675. }
  6676. /// See AbstractAttribute::trackStatistics()
  6677. void trackStatistics() const override {
  6678. STATS_DECLTRACK_FN_ATTR(potential_values)
  6679. }
  6680. };
  6681. struct AAPotentialValuesCallSite : AAPotentialValuesFunction {
  6682. AAPotentialValuesCallSite(const IRPosition &IRP, Attributor &A)
  6683. : AAPotentialValuesFunction(IRP, A) {}
  6684. /// See AbstractAttribute::trackStatistics()
  6685. void trackStatistics() const override {
  6686. STATS_DECLTRACK_CS_ATTR(potential_values)
  6687. }
  6688. };
  6689. struct AAPotentialValuesCallSiteReturned
  6690. : AACallSiteReturnedFromReturned<AAPotentialValues, AAPotentialValuesImpl> {
  6691. AAPotentialValuesCallSiteReturned(const IRPosition &IRP, Attributor &A)
  6692. : AACallSiteReturnedFromReturned<AAPotentialValues,
  6693. AAPotentialValuesImpl>(IRP, A) {}
  6694. /// See AbstractAttribute::trackStatistics()
  6695. void trackStatistics() const override {
  6696. STATS_DECLTRACK_CSRET_ATTR(potential_values)
  6697. }
  6698. };
  6699. struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating {
  6700. AAPotentialValuesCallSiteArgument(const IRPosition &IRP, Attributor &A)
  6701. : AAPotentialValuesFloating(IRP, A) {}
  6702. /// See AbstractAttribute::initialize(..).
  6703. void initialize(Attributor &A) override {
  6704. Value &V = getAssociatedValue();
  6705. if (auto *C = dyn_cast<ConstantInt>(&V)) {
  6706. unionAssumed(C->getValue());
  6707. indicateOptimisticFixpoint();
  6708. return;
  6709. }
  6710. if (isa<UndefValue>(&V)) {
  6711. unionAssumedWithUndef();
  6712. indicateOptimisticFixpoint();
  6713. return;
  6714. }
  6715. }
  6716. /// See AbstractAttribute::updateImpl(...).
  6717. ChangeStatus updateImpl(Attributor &A) override {
  6718. Value &V = getAssociatedValue();
  6719. auto AssumedBefore = getAssumed();
  6720. auto &AA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(V));
  6721. const auto &S = AA.getAssumed();
  6722. unionAssumed(S);
  6723. return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
  6724. : ChangeStatus::CHANGED;
  6725. }
  6726. /// See AbstractAttribute::trackStatistics()
  6727. void trackStatistics() const override {
  6728. STATS_DECLTRACK_CSARG_ATTR(potential_values)
  6729. }
  6730. };
  6731. /// ------------------------ NoUndef Attribute ---------------------------------
  6732. struct AANoUndefImpl : AANoUndef {
  6733. AANoUndefImpl(const IRPosition &IRP, Attributor &A) : AANoUndef(IRP, A) {}
  6734. /// See AbstractAttribute::initialize(...).
  6735. void initialize(Attributor &A) override {
  6736. if (getIRPosition().hasAttr({Attribute::NoUndef})) {
  6737. indicateOptimisticFixpoint();
  6738. return;
  6739. }
  6740. Value &V = getAssociatedValue();
  6741. if (isa<UndefValue>(V))
  6742. indicatePessimisticFixpoint();
  6743. else if (isa<FreezeInst>(V))
  6744. indicateOptimisticFixpoint();
  6745. else if (getPositionKind() != IRPosition::IRP_RETURNED &&
  6746. isGuaranteedNotToBeUndefOrPoison(&V))
  6747. indicateOptimisticFixpoint();
  6748. else
  6749. AANoUndef::initialize(A);
  6750. }
  6751. /// See followUsesInMBEC
  6752. bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
  6753. AANoUndef::StateType &State) {
  6754. const Value *UseV = U->get();
  6755. const DominatorTree *DT = nullptr;
  6756. AssumptionCache *AC = nullptr;
  6757. InformationCache &InfoCache = A.getInfoCache();
  6758. if (Function *F = getAnchorScope()) {
  6759. DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
  6760. AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
  6761. }
  6762. State.setKnown(isGuaranteedNotToBeUndefOrPoison(UseV, AC, I, DT));
  6763. bool TrackUse = false;
  6764. // Track use for instructions which must produce undef or poison bits when
  6765. // at least one operand contains such bits.
  6766. if (isa<CastInst>(*I) || isa<GetElementPtrInst>(*I))
  6767. TrackUse = true;
  6768. return TrackUse;
  6769. }
  6770. /// See AbstractAttribute::getAsStr().
  6771. const std::string getAsStr() const override {
  6772. return getAssumed() ? "noundef" : "may-undef-or-poison";
  6773. }
  6774. ChangeStatus manifest(Attributor &A) override {
  6775. // We don't manifest noundef attribute for dead positions because the
  6776. // associated values with dead positions would be replaced with undef
  6777. // values.
  6778. if (A.isAssumedDead(getIRPosition(), nullptr, nullptr))
  6779. return ChangeStatus::UNCHANGED;
  6780. // A position whose simplified value does not have any value is
  6781. // considered to be dead. We don't manifest noundef in such positions for
  6782. // the same reason above.
  6783. auto &ValueSimplifyAA = A.getAAFor<AAValueSimplify>(
  6784. *this, getIRPosition(), /* TrackDependence */ false);
  6785. if (!ValueSimplifyAA.getAssumedSimplifiedValue(A).hasValue())
  6786. return ChangeStatus::UNCHANGED;
  6787. return AANoUndef::manifest(A);
  6788. }
  6789. };
  6790. struct AANoUndefFloating : public AANoUndefImpl {
  6791. AANoUndefFloating(const IRPosition &IRP, Attributor &A)
  6792. : AANoUndefImpl(IRP, A) {}
  6793. /// See AbstractAttribute::initialize(...).
  6794. void initialize(Attributor &A) override {
  6795. AANoUndefImpl::initialize(A);
  6796. if (!getState().isAtFixpoint())
  6797. if (Instruction *CtxI = getCtxI())
  6798. followUsesInMBEC(*this, A, getState(), *CtxI);
  6799. }
  6800. /// See AbstractAttribute::updateImpl(...).
  6801. ChangeStatus updateImpl(Attributor &A) override {
  6802. auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
  6803. AANoUndef::StateType &T, bool Stripped) -> bool {
  6804. const auto &AA = A.getAAFor<AANoUndef>(*this, IRPosition::value(V));
  6805. if (!Stripped && this == &AA) {
  6806. T.indicatePessimisticFixpoint();
  6807. } else {
  6808. const AANoUndef::StateType &S =
  6809. static_cast<const AANoUndef::StateType &>(AA.getState());
  6810. T ^= S;
  6811. }
  6812. return T.isValidState();
  6813. };
  6814. StateType T;
  6815. if (!genericValueTraversal<AANoUndef, StateType>(
  6816. A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
  6817. return indicatePessimisticFixpoint();
  6818. return clampStateAndIndicateChange(getState(), T);
  6819. }
  6820. /// See AbstractAttribute::trackStatistics()
  6821. void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
  6822. };
  6823. struct AANoUndefReturned final
  6824. : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> {
  6825. AANoUndefReturned(const IRPosition &IRP, Attributor &A)
  6826. : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>(IRP, A) {}
  6827. /// See AbstractAttribute::trackStatistics()
  6828. void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
  6829. };
  6830. struct AANoUndefArgument final
  6831. : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> {
  6832. AANoUndefArgument(const IRPosition &IRP, Attributor &A)
  6833. : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP, A) {}
  6834. /// See AbstractAttribute::trackStatistics()
  6835. void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noundef) }
  6836. };
  6837. struct AANoUndefCallSiteArgument final : AANoUndefFloating {
  6838. AANoUndefCallSiteArgument(const IRPosition &IRP, Attributor &A)
  6839. : AANoUndefFloating(IRP, A) {}
  6840. /// See AbstractAttribute::trackStatistics()
  6841. void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noundef) }
  6842. };
  6843. struct AANoUndefCallSiteReturned final
  6844. : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl> {
  6845. AANoUndefCallSiteReturned(const IRPosition &IRP, Attributor &A)
  6846. : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl>(IRP, A) {}
  6847. /// See AbstractAttribute::trackStatistics()
  6848. void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noundef) }
  6849. };
  6850. } // namespace
  6851. const char AAReturnedValues::ID = 0;
  6852. const char AANoUnwind::ID = 0;
  6853. const char AANoSync::ID = 0;
  6854. const char AANoFree::ID = 0;
  6855. const char AANonNull::ID = 0;
  6856. const char AANoRecurse::ID = 0;
  6857. const char AAWillReturn::ID = 0;
  6858. const char AAUndefinedBehavior::ID = 0;
  6859. const char AANoAlias::ID = 0;
  6860. const char AAReachability::ID = 0;
  6861. const char AANoReturn::ID = 0;
  6862. const char AAIsDead::ID = 0;
  6863. const char AADereferenceable::ID = 0;
  6864. const char AAAlign::ID = 0;
  6865. const char AANoCapture::ID = 0;
  6866. const char AAValueSimplify::ID = 0;
  6867. const char AAHeapToStack::ID = 0;
  6868. const char AAPrivatizablePtr::ID = 0;
  6869. const char AAMemoryBehavior::ID = 0;
  6870. const char AAMemoryLocation::ID = 0;
  6871. const char AAValueConstantRange::ID = 0;
  6872. const char AAPotentialValues::ID = 0;
  6873. const char AANoUndef::ID = 0;
  6874. // Macro magic to create the static generator function for attributes that
  6875. // follow the naming scheme.
  6876. #define SWITCH_PK_INV(CLASS, PK, POS_NAME) \
  6877. case IRPosition::PK: \
  6878. llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
  6879. #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \
  6880. case IRPosition::PK: \
  6881. AA = new (A.Allocator) CLASS##SUFFIX(IRP, A); \
  6882. ++NumAAs; \
  6883. break;
  6884. #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
  6885. CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
  6886. CLASS *AA = nullptr; \
  6887. switch (IRP.getPositionKind()) { \
  6888. SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
  6889. SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
  6890. SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
  6891. SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
  6892. SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
  6893. SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
  6894. SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
  6895. SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
  6896. } \
  6897. return *AA; \
  6898. }
  6899. #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
  6900. CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
  6901. CLASS *AA = nullptr; \
  6902. switch (IRP.getPositionKind()) { \
  6903. SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
  6904. SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \
  6905. SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
  6906. SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
  6907. SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
  6908. SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
  6909. SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
  6910. SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
  6911. } \
  6912. return *AA; \
  6913. }
  6914. #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
  6915. CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
  6916. CLASS *AA = nullptr; \
  6917. switch (IRP.getPositionKind()) { \
  6918. SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
  6919. SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
  6920. SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
  6921. SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
  6922. SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
  6923. SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
  6924. SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
  6925. SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
  6926. } \
  6927. return *AA; \
  6928. }
  6929. #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
  6930. CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
  6931. CLASS *AA = nullptr; \
  6932. switch (IRP.getPositionKind()) { \
  6933. SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
  6934. SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
  6935. SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
  6936. SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
  6937. SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
  6938. SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
  6939. SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
  6940. SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
  6941. } \
  6942. return *AA; \
  6943. }
  6944. #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
  6945. CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
  6946. CLASS *AA = nullptr; \
  6947. switch (IRP.getPositionKind()) { \
  6948. SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
  6949. SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
  6950. SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
  6951. SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
  6952. SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
  6953. SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
  6954. SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
  6955. SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
  6956. } \
  6957. return *AA; \
  6958. }
  6959. CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind)
  6960. CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync)
  6961. CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse)
  6962. CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn)
  6963. CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn)
  6964. CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues)
  6965. CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryLocation)
  6966. CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull)
  6967. CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias)
  6968. CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPrivatizablePtr)
  6969. CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable)
  6970. CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign)
  6971. CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture)
  6972. CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueConstantRange)
  6973. CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialValues)
  6974. CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUndef)
  6975. CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify)
  6976. CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead)
  6977. CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree)
  6978. CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack)
  6979. CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReachability)
  6980. CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAUndefinedBehavior)
  6981. CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior)
  6982. #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
  6983. #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
  6984. #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
  6985. #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
  6986. #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
  6987. #undef SWITCH_PK_CREATE
  6988. #undef SWITCH_PK_INV