Verifier.cpp 260 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815
  1. //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the function verifier interface, that can be used for some
  10. // basic correctness checking of input to the system.
  11. //
  12. // Note that this does not provide full `Java style' security and verifications,
  13. // instead it just tries to ensure that code is well-formed.
  14. //
  15. // * Both of a binary operator's parameters are of the same type
  16. // * Verify that the indices of mem access instructions match other operands
  17. // * Verify that arithmetic and other things are only performed on first-class
  18. // types. Verify that shifts & logicals only happen on integrals f.e.
  19. // * All of the constants in a switch statement are of the correct type
  20. // * The code is in valid SSA form
  21. // * It should be illegal to put a label into any other type (like a structure)
  22. // or to return one. [except constant arrays!]
  23. // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
  24. // * PHI nodes must have an entry for each predecessor, with no extras.
  25. // * PHI nodes must be the first thing in a basic block, all grouped together
  26. // * All basic blocks should only end with terminator insts, not contain them
  27. // * The entry node to a function must not have predecessors
  28. // * All Instructions must be embedded into a basic block
  29. // * Functions cannot take a void-typed parameter
  30. // * Verify that a function's argument list agrees with it's declared type.
  31. // * It is illegal to specify a name for a void value.
  32. // * It is illegal to have a internal global value with no initializer
  33. // * It is illegal to have a ret instruction that returns a value that does not
  34. // agree with the function return value type.
  35. // * Function call argument types match the function prototype
  36. // * A landing pad is defined by a landingpad instruction, and can be jumped to
  37. // only by the unwind edge of an invoke instruction.
  38. // * A landingpad instruction must be the first non-PHI instruction in the
  39. // block.
  40. // * Landingpad instructions must be in a function with a personality function.
  41. // * All other things that are tested by asserts spread about the code...
  42. //
  43. //===----------------------------------------------------------------------===//
  44. #include "llvm/IR/Verifier.h"
  45. #include "llvm/ADT/APFloat.h"
  46. #include "llvm/ADT/APInt.h"
  47. #include "llvm/ADT/ArrayRef.h"
  48. #include "llvm/ADT/DenseMap.h"
  49. #include "llvm/ADT/MapVector.h"
  50. #include "llvm/ADT/STLExtras.h"
  51. #include "llvm/ADT/SmallPtrSet.h"
  52. #include "llvm/ADT/SmallSet.h"
  53. #include "llvm/ADT/SmallVector.h"
  54. #include "llvm/ADT/StringExtras.h"
  55. #include "llvm/ADT/StringMap.h"
  56. #include "llvm/ADT/StringRef.h"
  57. #include "llvm/ADT/Twine.h"
  58. #include "llvm/BinaryFormat/Dwarf.h"
  59. #include "llvm/IR/Argument.h"
  60. #include "llvm/IR/Attributes.h"
  61. #include "llvm/IR/BasicBlock.h"
  62. #include "llvm/IR/CFG.h"
  63. #include "llvm/IR/CallingConv.h"
  64. #include "llvm/IR/Comdat.h"
  65. #include "llvm/IR/Constant.h"
  66. #include "llvm/IR/ConstantRange.h"
  67. #include "llvm/IR/Constants.h"
  68. #include "llvm/IR/DataLayout.h"
  69. #include "llvm/IR/DebugInfo.h"
  70. #include "llvm/IR/DebugInfoMetadata.h"
  71. #include "llvm/IR/DebugLoc.h"
  72. #include "llvm/IR/DerivedTypes.h"
  73. #include "llvm/IR/Dominators.h"
  74. #include "llvm/IR/Function.h"
  75. #include "llvm/IR/GCStrategy.h"
  76. #include "llvm/IR/GlobalAlias.h"
  77. #include "llvm/IR/GlobalValue.h"
  78. #include "llvm/IR/GlobalVariable.h"
  79. #include "llvm/IR/InlineAsm.h"
  80. #include "llvm/IR/InstVisitor.h"
  81. #include "llvm/IR/InstrTypes.h"
  82. #include "llvm/IR/Instruction.h"
  83. #include "llvm/IR/Instructions.h"
  84. #include "llvm/IR/IntrinsicInst.h"
  85. #include "llvm/IR/Intrinsics.h"
  86. #include "llvm/IR/IntrinsicsAArch64.h"
  87. #include "llvm/IR/IntrinsicsARM.h"
  88. #include "llvm/IR/IntrinsicsWebAssembly.h"
  89. #include "llvm/IR/LLVMContext.h"
  90. #include "llvm/IR/Metadata.h"
  91. #include "llvm/IR/Module.h"
  92. #include "llvm/IR/ModuleSlotTracker.h"
  93. #include "llvm/IR/PassManager.h"
  94. #include "llvm/IR/Statepoint.h"
  95. #include "llvm/IR/Type.h"
  96. #include "llvm/IR/Use.h"
  97. #include "llvm/IR/User.h"
  98. #include "llvm/IR/Value.h"
  99. #include "llvm/InitializePasses.h"
  100. #include "llvm/Pass.h"
  101. #include "llvm/Support/AtomicOrdering.h"
  102. #include "llvm/Support/Casting.h"
  103. #include "llvm/Support/CommandLine.h"
  104. #include "llvm/Support/ErrorHandling.h"
  105. #include "llvm/Support/MathExtras.h"
  106. #include "llvm/Support/raw_ostream.h"
  107. #include <algorithm>
  108. #include <cassert>
  109. #include <cstdint>
  110. #include <memory>
  111. #include <optional>
  112. #include <string>
  113. #include <utility>
  114. using namespace llvm;
  115. static cl::opt<bool> VerifyNoAliasScopeDomination(
  116. "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
  117. cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
  118. "scopes are not dominating"));
  119. namespace llvm {
  120. struct VerifierSupport {
  121. raw_ostream *OS;
  122. const Module &M;
  123. ModuleSlotTracker MST;
  124. Triple TT;
  125. const DataLayout &DL;
  126. LLVMContext &Context;
  127. /// Track the brokenness of the module while recursively visiting.
  128. bool Broken = false;
  129. /// Broken debug info can be "recovered" from by stripping the debug info.
  130. bool BrokenDebugInfo = false;
  131. /// Whether to treat broken debug info as an error.
  132. bool TreatBrokenDebugInfoAsError = true;
  133. explicit VerifierSupport(raw_ostream *OS, const Module &M)
  134. : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
  135. Context(M.getContext()) {}
  136. private:
  137. void Write(const Module *M) {
  138. *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
  139. }
  140. void Write(const Value *V) {
  141. if (V)
  142. Write(*V);
  143. }
  144. void Write(const Value &V) {
  145. if (isa<Instruction>(V)) {
  146. V.print(*OS, MST);
  147. *OS << '\n';
  148. } else {
  149. V.printAsOperand(*OS, true, MST);
  150. *OS << '\n';
  151. }
  152. }
  153. void Write(const Metadata *MD) {
  154. if (!MD)
  155. return;
  156. MD->print(*OS, MST, &M);
  157. *OS << '\n';
  158. }
  159. template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
  160. Write(MD.get());
  161. }
  162. void Write(const NamedMDNode *NMD) {
  163. if (!NMD)
  164. return;
  165. NMD->print(*OS, MST);
  166. *OS << '\n';
  167. }
  168. void Write(Type *T) {
  169. if (!T)
  170. return;
  171. *OS << ' ' << *T;
  172. }
  173. void Write(const Comdat *C) {
  174. if (!C)
  175. return;
  176. *OS << *C;
  177. }
  178. void Write(const APInt *AI) {
  179. if (!AI)
  180. return;
  181. *OS << *AI << '\n';
  182. }
  183. void Write(const unsigned i) { *OS << i << '\n'; }
  184. // NOLINTNEXTLINE(readability-identifier-naming)
  185. void Write(const Attribute *A) {
  186. if (!A)
  187. return;
  188. *OS << A->getAsString() << '\n';
  189. }
  190. // NOLINTNEXTLINE(readability-identifier-naming)
  191. void Write(const AttributeSet *AS) {
  192. if (!AS)
  193. return;
  194. *OS << AS->getAsString() << '\n';
  195. }
  196. // NOLINTNEXTLINE(readability-identifier-naming)
  197. void Write(const AttributeList *AL) {
  198. if (!AL)
  199. return;
  200. AL->print(*OS);
  201. }
  202. template <typename T> void Write(ArrayRef<T> Vs) {
  203. for (const T &V : Vs)
  204. Write(V);
  205. }
  206. template <typename T1, typename... Ts>
  207. void WriteTs(const T1 &V1, const Ts &... Vs) {
  208. Write(V1);
  209. WriteTs(Vs...);
  210. }
  211. template <typename... Ts> void WriteTs() {}
  212. public:
  213. /// A check failed, so printout out the condition and the message.
  214. ///
  215. /// This provides a nice place to put a breakpoint if you want to see why
  216. /// something is not correct.
  217. void CheckFailed(const Twine &Message) {
  218. if (OS)
  219. *OS << Message << '\n';
  220. Broken = true;
  221. }
  222. /// A check failed (with values to print).
  223. ///
  224. /// This calls the Message-only version so that the above is easier to set a
  225. /// breakpoint on.
  226. template <typename T1, typename... Ts>
  227. void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
  228. CheckFailed(Message);
  229. if (OS)
  230. WriteTs(V1, Vs...);
  231. }
  232. /// A debug info check failed.
  233. void DebugInfoCheckFailed(const Twine &Message) {
  234. if (OS)
  235. *OS << Message << '\n';
  236. Broken |= TreatBrokenDebugInfoAsError;
  237. BrokenDebugInfo = true;
  238. }
  239. /// A debug info check failed (with values to print).
  240. template <typename T1, typename... Ts>
  241. void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
  242. const Ts &... Vs) {
  243. DebugInfoCheckFailed(Message);
  244. if (OS)
  245. WriteTs(V1, Vs...);
  246. }
  247. };
  248. } // namespace llvm
  249. namespace {
  250. class Verifier : public InstVisitor<Verifier>, VerifierSupport {
  251. friend class InstVisitor<Verifier>;
  252. // ISD::ArgFlagsTy::MemAlign only have 4 bits for alignment, so
  253. // the alignment size should not exceed 2^15. Since encode(Align)
  254. // would plus the shift value by 1, the alignment size should
  255. // not exceed 2^14, otherwise it can NOT be properly lowered
  256. // in backend.
  257. static constexpr unsigned ParamMaxAlignment = 1 << 14;
  258. DominatorTree DT;
  259. /// When verifying a basic block, keep track of all of the
  260. /// instructions we have seen so far.
  261. ///
  262. /// This allows us to do efficient dominance checks for the case when an
  263. /// instruction has an operand that is an instruction in the same block.
  264. SmallPtrSet<Instruction *, 16> InstsInThisBlock;
  265. /// Keep track of the metadata nodes that have been checked already.
  266. SmallPtrSet<const Metadata *, 32> MDNodes;
  267. /// Keep track which DISubprogram is attached to which function.
  268. DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
  269. /// Track all DICompileUnits visited.
  270. SmallPtrSet<const Metadata *, 2> CUVisited;
  271. /// The result type for a landingpad.
  272. Type *LandingPadResultTy;
  273. /// Whether we've seen a call to @llvm.localescape in this function
  274. /// already.
  275. bool SawFrameEscape;
  276. /// Whether the current function has a DISubprogram attached to it.
  277. bool HasDebugInfo = false;
  278. /// The current source language.
  279. dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user;
  280. /// Whether source was present on the first DIFile encountered in each CU.
  281. DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
  282. /// Stores the count of how many objects were passed to llvm.localescape for a
  283. /// given function and the largest index passed to llvm.localrecover.
  284. DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
  285. // Maps catchswitches and cleanuppads that unwind to siblings to the
  286. // terminators that indicate the unwind, used to detect cycles therein.
  287. MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
  288. /// Cache of constants visited in search of ConstantExprs.
  289. SmallPtrSet<const Constant *, 32> ConstantExprVisited;
  290. /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
  291. SmallVector<const Function *, 4> DeoptimizeDeclarations;
  292. /// Cache of attribute lists verified.
  293. SmallPtrSet<const void *, 32> AttributeListsVisited;
  294. // Verify that this GlobalValue is only used in this module.
  295. // This map is used to avoid visiting uses twice. We can arrive at a user
  296. // twice, if they have multiple operands. In particular for very large
  297. // constant expressions, we can arrive at a particular user many times.
  298. SmallPtrSet<const Value *, 32> GlobalValueVisited;
  299. // Keeps track of duplicate function argument debug info.
  300. SmallVector<const DILocalVariable *, 16> DebugFnArgs;
  301. TBAAVerifier TBAAVerifyHelper;
  302. SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
  303. void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
  304. public:
  305. explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
  306. const Module &M)
  307. : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
  308. SawFrameEscape(false), TBAAVerifyHelper(this) {
  309. TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
  310. }
  311. bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
  312. bool verify(const Function &F) {
  313. assert(F.getParent() == &M &&
  314. "An instance of this class only works with a specific module!");
  315. // First ensure the function is well-enough formed to compute dominance
  316. // information, and directly compute a dominance tree. We don't rely on the
  317. // pass manager to provide this as it isolates us from a potentially
  318. // out-of-date dominator tree and makes it significantly more complex to run
  319. // this code outside of a pass manager.
  320. // FIXME: It's really gross that we have to cast away constness here.
  321. if (!F.empty())
  322. DT.recalculate(const_cast<Function &>(F));
  323. for (const BasicBlock &BB : F) {
  324. if (!BB.empty() && BB.back().isTerminator())
  325. continue;
  326. if (OS) {
  327. *OS << "Basic Block in function '" << F.getName()
  328. << "' does not have terminator!\n";
  329. BB.printAsOperand(*OS, true, MST);
  330. *OS << "\n";
  331. }
  332. return false;
  333. }
  334. Broken = false;
  335. // FIXME: We strip const here because the inst visitor strips const.
  336. visit(const_cast<Function &>(F));
  337. verifySiblingFuncletUnwinds();
  338. InstsInThisBlock.clear();
  339. DebugFnArgs.clear();
  340. LandingPadResultTy = nullptr;
  341. SawFrameEscape = false;
  342. SiblingFuncletInfo.clear();
  343. verifyNoAliasScopeDecl();
  344. NoAliasScopeDecls.clear();
  345. return !Broken;
  346. }
  347. /// Verify the module that this instance of \c Verifier was initialized with.
  348. bool verify() {
  349. Broken = false;
  350. // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
  351. for (const Function &F : M)
  352. if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
  353. DeoptimizeDeclarations.push_back(&F);
  354. // Now that we've visited every function, verify that we never asked to
  355. // recover a frame index that wasn't escaped.
  356. verifyFrameRecoverIndices();
  357. for (const GlobalVariable &GV : M.globals())
  358. visitGlobalVariable(GV);
  359. for (const GlobalAlias &GA : M.aliases())
  360. visitGlobalAlias(GA);
  361. for (const GlobalIFunc &GI : M.ifuncs())
  362. visitGlobalIFunc(GI);
  363. for (const NamedMDNode &NMD : M.named_metadata())
  364. visitNamedMDNode(NMD);
  365. for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
  366. visitComdat(SMEC.getValue());
  367. visitModuleFlags();
  368. visitModuleIdents();
  369. visitModuleCommandLines();
  370. verifyCompileUnits();
  371. verifyDeoptimizeCallingConvs();
  372. DISubprogramAttachments.clear();
  373. return !Broken;
  374. }
  375. private:
  376. /// Whether a metadata node is allowed to be, or contain, a DILocation.
  377. enum class AreDebugLocsAllowed { No, Yes };
  378. // Verification methods...
  379. void visitGlobalValue(const GlobalValue &GV);
  380. void visitGlobalVariable(const GlobalVariable &GV);
  381. void visitGlobalAlias(const GlobalAlias &GA);
  382. void visitGlobalIFunc(const GlobalIFunc &GI);
  383. void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
  384. void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
  385. const GlobalAlias &A, const Constant &C);
  386. void visitNamedMDNode(const NamedMDNode &NMD);
  387. void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
  388. void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
  389. void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
  390. void visitComdat(const Comdat &C);
  391. void visitModuleIdents();
  392. void visitModuleCommandLines();
  393. void visitModuleFlags();
  394. void visitModuleFlag(const MDNode *Op,
  395. DenseMap<const MDString *, const MDNode *> &SeenIDs,
  396. SmallVectorImpl<const MDNode *> &Requirements);
  397. void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
  398. void visitFunction(const Function &F);
  399. void visitBasicBlock(BasicBlock &BB);
  400. void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
  401. void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
  402. void visitProfMetadata(Instruction &I, MDNode *MD);
  403. void visitCallStackMetadata(MDNode *MD);
  404. void visitMemProfMetadata(Instruction &I, MDNode *MD);
  405. void visitCallsiteMetadata(Instruction &I, MDNode *MD);
  406. void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
  407. void visitAnnotationMetadata(MDNode *Annotation);
  408. void visitAliasScopeMetadata(const MDNode *MD);
  409. void visitAliasScopeListMetadata(const MDNode *MD);
  410. void visitAccessGroupMetadata(const MDNode *MD);
  411. template <class Ty> bool isValidMetadataArray(const MDTuple &N);
  412. #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
  413. #include "llvm/IR/Metadata.def"
  414. void visitDIScope(const DIScope &N);
  415. void visitDIVariable(const DIVariable &N);
  416. void visitDILexicalBlockBase(const DILexicalBlockBase &N);
  417. void visitDITemplateParameter(const DITemplateParameter &N);
  418. void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
  419. // InstVisitor overrides...
  420. using InstVisitor<Verifier>::visit;
  421. void visit(Instruction &I);
  422. void visitTruncInst(TruncInst &I);
  423. void visitZExtInst(ZExtInst &I);
  424. void visitSExtInst(SExtInst &I);
  425. void visitFPTruncInst(FPTruncInst &I);
  426. void visitFPExtInst(FPExtInst &I);
  427. void visitFPToUIInst(FPToUIInst &I);
  428. void visitFPToSIInst(FPToSIInst &I);
  429. void visitUIToFPInst(UIToFPInst &I);
  430. void visitSIToFPInst(SIToFPInst &I);
  431. void visitIntToPtrInst(IntToPtrInst &I);
  432. void visitPtrToIntInst(PtrToIntInst &I);
  433. void visitBitCastInst(BitCastInst &I);
  434. void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
  435. void visitPHINode(PHINode &PN);
  436. void visitCallBase(CallBase &Call);
  437. void visitUnaryOperator(UnaryOperator &U);
  438. void visitBinaryOperator(BinaryOperator &B);
  439. void visitICmpInst(ICmpInst &IC);
  440. void visitFCmpInst(FCmpInst &FC);
  441. void visitExtractElementInst(ExtractElementInst &EI);
  442. void visitInsertElementInst(InsertElementInst &EI);
  443. void visitShuffleVectorInst(ShuffleVectorInst &EI);
  444. void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
  445. void visitCallInst(CallInst &CI);
  446. void visitInvokeInst(InvokeInst &II);
  447. void visitGetElementPtrInst(GetElementPtrInst &GEP);
  448. void visitLoadInst(LoadInst &LI);
  449. void visitStoreInst(StoreInst &SI);
  450. void verifyDominatesUse(Instruction &I, unsigned i);
  451. void visitInstruction(Instruction &I);
  452. void visitTerminator(Instruction &I);
  453. void visitBranchInst(BranchInst &BI);
  454. void visitReturnInst(ReturnInst &RI);
  455. void visitSwitchInst(SwitchInst &SI);
  456. void visitIndirectBrInst(IndirectBrInst &BI);
  457. void visitCallBrInst(CallBrInst &CBI);
  458. void visitSelectInst(SelectInst &SI);
  459. void visitUserOp1(Instruction &I);
  460. void visitUserOp2(Instruction &I) { visitUserOp1(I); }
  461. void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
  462. void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
  463. void visitVPIntrinsic(VPIntrinsic &VPI);
  464. void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
  465. void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
  466. void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
  467. void visitAtomicRMWInst(AtomicRMWInst &RMWI);
  468. void visitFenceInst(FenceInst &FI);
  469. void visitAllocaInst(AllocaInst &AI);
  470. void visitExtractValueInst(ExtractValueInst &EVI);
  471. void visitInsertValueInst(InsertValueInst &IVI);
  472. void visitEHPadPredecessors(Instruction &I);
  473. void visitLandingPadInst(LandingPadInst &LPI);
  474. void visitResumeInst(ResumeInst &RI);
  475. void visitCatchPadInst(CatchPadInst &CPI);
  476. void visitCatchReturnInst(CatchReturnInst &CatchReturn);
  477. void visitCleanupPadInst(CleanupPadInst &CPI);
  478. void visitFuncletPadInst(FuncletPadInst &FPI);
  479. void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
  480. void visitCleanupReturnInst(CleanupReturnInst &CRI);
  481. void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
  482. void verifySwiftErrorValue(const Value *SwiftErrorVal);
  483. void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
  484. void verifyMustTailCall(CallInst &CI);
  485. bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
  486. void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
  487. void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
  488. void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
  489. const Value *V);
  490. void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
  491. const Value *V, bool IsIntrinsic, bool IsInlineAsm);
  492. void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
  493. void visitConstantExprsRecursively(const Constant *EntryC);
  494. void visitConstantExpr(const ConstantExpr *CE);
  495. void verifyInlineAsmCall(const CallBase &Call);
  496. void verifyStatepoint(const CallBase &Call);
  497. void verifyFrameRecoverIndices();
  498. void verifySiblingFuncletUnwinds();
  499. void verifyFragmentExpression(const DbgVariableIntrinsic &I);
  500. template <typename ValueOrMetadata>
  501. void verifyFragmentExpression(const DIVariable &V,
  502. DIExpression::FragmentInfo Fragment,
  503. ValueOrMetadata *Desc);
  504. void verifyFnArgs(const DbgVariableIntrinsic &I);
  505. void verifyNotEntryValue(const DbgVariableIntrinsic &I);
  506. /// Module-level debug info verification...
  507. void verifyCompileUnits();
  508. /// Module-level verification that all @llvm.experimental.deoptimize
  509. /// declarations share the same calling convention.
  510. void verifyDeoptimizeCallingConvs();
  511. void verifyAttachedCallBundle(const CallBase &Call,
  512. const OperandBundleUse &BU);
  513. /// Verify all-or-nothing property of DIFile source attribute within a CU.
  514. void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
  515. /// Verify the llvm.experimental.noalias.scope.decl declarations
  516. void verifyNoAliasScopeDecl();
  517. };
  518. } // end anonymous namespace
  519. /// We know that cond should be true, if not print an error message.
  520. #define Check(C, ...) \
  521. do { \
  522. if (!(C)) { \
  523. CheckFailed(__VA_ARGS__); \
  524. return; \
  525. } \
  526. } while (false)
  527. /// We know that a debug info condition should be true, if not print
  528. /// an error message.
  529. #define CheckDI(C, ...) \
  530. do { \
  531. if (!(C)) { \
  532. DebugInfoCheckFailed(__VA_ARGS__); \
  533. return; \
  534. } \
  535. } while (false)
  536. void Verifier::visit(Instruction &I) {
  537. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  538. Check(I.getOperand(i) != nullptr, "Operand is null", &I);
  539. InstVisitor<Verifier>::visit(I);
  540. }
  541. // Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
  542. static void forEachUser(const Value *User,
  543. SmallPtrSet<const Value *, 32> &Visited,
  544. llvm::function_ref<bool(const Value *)> Callback) {
  545. if (!Visited.insert(User).second)
  546. return;
  547. SmallVector<const Value *> WorkList;
  548. append_range(WorkList, User->materialized_users());
  549. while (!WorkList.empty()) {
  550. const Value *Cur = WorkList.pop_back_val();
  551. if (!Visited.insert(Cur).second)
  552. continue;
  553. if (Callback(Cur))
  554. append_range(WorkList, Cur->materialized_users());
  555. }
  556. }
  557. void Verifier::visitGlobalValue(const GlobalValue &GV) {
  558. Check(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
  559. "Global is external, but doesn't have external or weak linkage!", &GV);
  560. if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
  561. if (MaybeAlign A = GO->getAlign()) {
  562. Check(A->value() <= Value::MaximumAlignment,
  563. "huge alignment values are unsupported", GO);
  564. }
  565. }
  566. Check(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
  567. "Only global variables can have appending linkage!", &GV);
  568. if (GV.hasAppendingLinkage()) {
  569. const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
  570. Check(GVar && GVar->getValueType()->isArrayTy(),
  571. "Only global arrays can have appending linkage!", GVar);
  572. }
  573. if (GV.isDeclarationForLinker())
  574. Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
  575. if (GV.hasDLLExportStorageClass()) {
  576. Check(!GV.hasHiddenVisibility(),
  577. "dllexport GlobalValue must have default or protected visibility",
  578. &GV);
  579. }
  580. if (GV.hasDLLImportStorageClass()) {
  581. Check(GV.hasDefaultVisibility(),
  582. "dllimport GlobalValue must have default visibility", &GV);
  583. Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
  584. &GV);
  585. Check((GV.isDeclaration() &&
  586. (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) ||
  587. GV.hasAvailableExternallyLinkage(),
  588. "Global is marked as dllimport, but not external", &GV);
  589. }
  590. if (GV.isImplicitDSOLocal())
  591. Check(GV.isDSOLocal(),
  592. "GlobalValue with local linkage or non-default "
  593. "visibility must be dso_local!",
  594. &GV);
  595. forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
  596. if (const Instruction *I = dyn_cast<Instruction>(V)) {
  597. if (!I->getParent() || !I->getParent()->getParent())
  598. CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
  599. I);
  600. else if (I->getParent()->getParent()->getParent() != &M)
  601. CheckFailed("Global is referenced in a different module!", &GV, &M, I,
  602. I->getParent()->getParent(),
  603. I->getParent()->getParent()->getParent());
  604. return false;
  605. } else if (const Function *F = dyn_cast<Function>(V)) {
  606. if (F->getParent() != &M)
  607. CheckFailed("Global is used by function in a different module", &GV, &M,
  608. F, F->getParent());
  609. return false;
  610. }
  611. return true;
  612. });
  613. }
  614. void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
  615. if (GV.hasInitializer()) {
  616. Check(GV.getInitializer()->getType() == GV.getValueType(),
  617. "Global variable initializer type does not match global "
  618. "variable type!",
  619. &GV);
  620. // If the global has common linkage, it must have a zero initializer and
  621. // cannot be constant.
  622. if (GV.hasCommonLinkage()) {
  623. Check(GV.getInitializer()->isNullValue(),
  624. "'common' global must have a zero initializer!", &GV);
  625. Check(!GV.isConstant(), "'common' global may not be marked constant!",
  626. &GV);
  627. Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
  628. }
  629. }
  630. if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
  631. GV.getName() == "llvm.global_dtors")) {
  632. Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
  633. "invalid linkage for intrinsic global variable", &GV);
  634. // Don't worry about emitting an error for it not being an array,
  635. // visitGlobalValue will complain on appending non-array.
  636. if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
  637. StructType *STy = dyn_cast<StructType>(ATy->getElementType());
  638. PointerType *FuncPtrTy =
  639. FunctionType::get(Type::getVoidTy(Context), false)->
  640. getPointerTo(DL.getProgramAddressSpace());
  641. Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
  642. STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
  643. STy->getTypeAtIndex(1) == FuncPtrTy,
  644. "wrong type for intrinsic global variable", &GV);
  645. Check(STy->getNumElements() == 3,
  646. "the third field of the element type is mandatory, "
  647. "specify ptr null to migrate from the obsoleted 2-field form");
  648. Type *ETy = STy->getTypeAtIndex(2);
  649. Type *Int8Ty = Type::getInt8Ty(ETy->getContext());
  650. Check(ETy->isPointerTy() &&
  651. cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty),
  652. "wrong type for intrinsic global variable", &GV);
  653. }
  654. }
  655. if (GV.hasName() && (GV.getName() == "llvm.used" ||
  656. GV.getName() == "llvm.compiler.used")) {
  657. Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
  658. "invalid linkage for intrinsic global variable", &GV);
  659. Type *GVType = GV.getValueType();
  660. if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
  661. PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
  662. Check(PTy, "wrong type for intrinsic global variable", &GV);
  663. if (GV.hasInitializer()) {
  664. const Constant *Init = GV.getInitializer();
  665. const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
  666. Check(InitArray, "wrong initalizer for intrinsic global variable",
  667. Init);
  668. for (Value *Op : InitArray->operands()) {
  669. Value *V = Op->stripPointerCasts();
  670. Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
  671. isa<GlobalAlias>(V),
  672. Twine("invalid ") + GV.getName() + " member", V);
  673. Check(V->hasName(),
  674. Twine("members of ") + GV.getName() + " must be named", V);
  675. }
  676. }
  677. }
  678. }
  679. // Visit any debug info attachments.
  680. SmallVector<MDNode *, 1> MDs;
  681. GV.getMetadata(LLVMContext::MD_dbg, MDs);
  682. for (auto *MD : MDs) {
  683. if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
  684. visitDIGlobalVariableExpression(*GVE);
  685. else
  686. CheckDI(false, "!dbg attachment of global variable must be a "
  687. "DIGlobalVariableExpression");
  688. }
  689. // Scalable vectors cannot be global variables, since we don't know
  690. // the runtime size. If the global is an array containing scalable vectors,
  691. // that will be caught by the isValidElementType methods in StructType or
  692. // ArrayType instead.
  693. Check(!isa<ScalableVectorType>(GV.getValueType()),
  694. "Globals cannot contain scalable vectors", &GV);
  695. if (auto *STy = dyn_cast<StructType>(GV.getValueType()))
  696. Check(!STy->containsScalableVectorType(),
  697. "Globals cannot contain scalable vectors", &GV);
  698. // Check if it's a target extension type that disallows being used as a
  699. // global.
  700. if (auto *TTy = dyn_cast<TargetExtType>(GV.getValueType()))
  701. Check(TTy->hasProperty(TargetExtType::CanBeGlobal),
  702. "Global @" + GV.getName() + " has illegal target extension type",
  703. TTy);
  704. if (!GV.hasInitializer()) {
  705. visitGlobalValue(GV);
  706. return;
  707. }
  708. // Walk any aggregate initializers looking for bitcasts between address spaces
  709. visitConstantExprsRecursively(GV.getInitializer());
  710. visitGlobalValue(GV);
  711. }
  712. void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
  713. SmallPtrSet<const GlobalAlias*, 4> Visited;
  714. Visited.insert(&GA);
  715. visitAliaseeSubExpr(Visited, GA, C);
  716. }
  717. void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
  718. const GlobalAlias &GA, const Constant &C) {
  719. if (GA.hasAvailableExternallyLinkage()) {
  720. Check(isa<GlobalValue>(C) &&
  721. cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
  722. "available_externally alias must point to available_externally "
  723. "global value",
  724. &GA);
  725. }
  726. if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
  727. if (!GA.hasAvailableExternallyLinkage()) {
  728. Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
  729. &GA);
  730. }
  731. if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
  732. Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
  733. Check(!GA2->isInterposable(),
  734. "Alias cannot point to an interposable alias", &GA);
  735. } else {
  736. // Only continue verifying subexpressions of GlobalAliases.
  737. // Do not recurse into global initializers.
  738. return;
  739. }
  740. }
  741. if (const auto *CE = dyn_cast<ConstantExpr>(&C))
  742. visitConstantExprsRecursively(CE);
  743. for (const Use &U : C.operands()) {
  744. Value *V = &*U;
  745. if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
  746. visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
  747. else if (const auto *C2 = dyn_cast<Constant>(V))
  748. visitAliaseeSubExpr(Visited, GA, *C2);
  749. }
  750. }
  751. void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
  752. Check(GlobalAlias::isValidLinkage(GA.getLinkage()),
  753. "Alias should have private, internal, linkonce, weak, linkonce_odr, "
  754. "weak_odr, external, or available_externally linkage!",
  755. &GA);
  756. const Constant *Aliasee = GA.getAliasee();
  757. Check(Aliasee, "Aliasee cannot be NULL!", &GA);
  758. Check(GA.getType() == Aliasee->getType(),
  759. "Alias and aliasee types should match!", &GA);
  760. Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
  761. "Aliasee should be either GlobalValue or ConstantExpr", &GA);
  762. visitAliaseeSubExpr(GA, *Aliasee);
  763. visitGlobalValue(GA);
  764. }
  765. void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
  766. Check(GlobalIFunc::isValidLinkage(GI.getLinkage()),
  767. "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
  768. "weak_odr, or external linkage!",
  769. &GI);
  770. // Pierce through ConstantExprs and GlobalAliases and check that the resolver
  771. // is a Function definition.
  772. const Function *Resolver = GI.getResolverFunction();
  773. Check(Resolver, "IFunc must have a Function resolver", &GI);
  774. Check(!Resolver->isDeclarationForLinker(),
  775. "IFunc resolver must be a definition", &GI);
  776. // Check that the immediate resolver operand (prior to any bitcasts) has the
  777. // correct type.
  778. const Type *ResolverTy = GI.getResolver()->getType();
  779. Check(isa<PointerType>(Resolver->getFunctionType()->getReturnType()),
  780. "IFunc resolver must return a pointer", &GI);
  781. const Type *ResolverFuncTy =
  782. GlobalIFunc::getResolverFunctionType(GI.getValueType());
  783. Check(ResolverTy == ResolverFuncTy->getPointerTo(GI.getAddressSpace()),
  784. "IFunc resolver has incorrect type", &GI);
  785. }
  786. void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
  787. // There used to be various other llvm.dbg.* nodes, but we don't support
  788. // upgrading them and we want to reserve the namespace for future uses.
  789. if (NMD.getName().startswith("llvm.dbg."))
  790. CheckDI(NMD.getName() == "llvm.dbg.cu",
  791. "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
  792. for (const MDNode *MD : NMD.operands()) {
  793. if (NMD.getName() == "llvm.dbg.cu")
  794. CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
  795. if (!MD)
  796. continue;
  797. visitMDNode(*MD, AreDebugLocsAllowed::Yes);
  798. }
  799. }
  800. void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
  801. // Only visit each node once. Metadata can be mutually recursive, so this
  802. // avoids infinite recursion here, as well as being an optimization.
  803. if (!MDNodes.insert(&MD).second)
  804. return;
  805. Check(&MD.getContext() == &Context,
  806. "MDNode context does not match Module context!", &MD);
  807. switch (MD.getMetadataID()) {
  808. default:
  809. llvm_unreachable("Invalid MDNode subclass");
  810. case Metadata::MDTupleKind:
  811. break;
  812. #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
  813. case Metadata::CLASS##Kind: \
  814. visit##CLASS(cast<CLASS>(MD)); \
  815. break;
  816. #include "llvm/IR/Metadata.def"
  817. }
  818. for (const Metadata *Op : MD.operands()) {
  819. if (!Op)
  820. continue;
  821. Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
  822. &MD, Op);
  823. CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
  824. "DILocation not allowed within this metadata node", &MD, Op);
  825. if (auto *N = dyn_cast<MDNode>(Op)) {
  826. visitMDNode(*N, AllowLocs);
  827. continue;
  828. }
  829. if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
  830. visitValueAsMetadata(*V, nullptr);
  831. continue;
  832. }
  833. }
  834. // Check these last, so we diagnose problems in operands first.
  835. Check(!MD.isTemporary(), "Expected no forward declarations!", &MD);
  836. Check(MD.isResolved(), "All nodes should be resolved!", &MD);
  837. }
  838. void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
  839. Check(MD.getValue(), "Expected valid value", &MD);
  840. Check(!MD.getValue()->getType()->isMetadataTy(),
  841. "Unexpected metadata round-trip through values", &MD, MD.getValue());
  842. auto *L = dyn_cast<LocalAsMetadata>(&MD);
  843. if (!L)
  844. return;
  845. Check(F, "function-local metadata used outside a function", L);
  846. // If this was an instruction, bb, or argument, verify that it is in the
  847. // function that we expect.
  848. Function *ActualF = nullptr;
  849. if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
  850. Check(I->getParent(), "function-local metadata not in basic block", L, I);
  851. ActualF = I->getParent()->getParent();
  852. } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
  853. ActualF = BB->getParent();
  854. else if (Argument *A = dyn_cast<Argument>(L->getValue()))
  855. ActualF = A->getParent();
  856. assert(ActualF && "Unimplemented function local metadata case!");
  857. Check(ActualF == F, "function-local metadata used in wrong function", L);
  858. }
  859. void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
  860. Metadata *MD = MDV.getMetadata();
  861. if (auto *N = dyn_cast<MDNode>(MD)) {
  862. visitMDNode(*N, AreDebugLocsAllowed::No);
  863. return;
  864. }
  865. // Only visit each node once. Metadata can be mutually recursive, so this
  866. // avoids infinite recursion here, as well as being an optimization.
  867. if (!MDNodes.insert(MD).second)
  868. return;
  869. if (auto *V = dyn_cast<ValueAsMetadata>(MD))
  870. visitValueAsMetadata(*V, F);
  871. }
  872. static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
  873. static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
  874. static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
  875. void Verifier::visitDILocation(const DILocation &N) {
  876. CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
  877. "location requires a valid scope", &N, N.getRawScope());
  878. if (auto *IA = N.getRawInlinedAt())
  879. CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
  880. if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
  881. CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
  882. }
  883. void Verifier::visitGenericDINode(const GenericDINode &N) {
  884. CheckDI(N.getTag(), "invalid tag", &N);
  885. }
  886. void Verifier::visitDIScope(const DIScope &N) {
  887. if (auto *F = N.getRawFile())
  888. CheckDI(isa<DIFile>(F), "invalid file", &N, F);
  889. }
  890. void Verifier::visitDISubrange(const DISubrange &N) {
  891. CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
  892. bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
  893. CheckDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||
  894. N.getRawUpperBound(),
  895. "Subrange must contain count or upperBound", &N);
  896. CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
  897. "Subrange can have any one of count or upperBound", &N);
  898. auto *CBound = N.getRawCountNode();
  899. CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
  900. isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
  901. "Count must be signed constant or DIVariable or DIExpression", &N);
  902. auto Count = N.getCount();
  903. CheckDI(!Count || !Count.is<ConstantInt *>() ||
  904. Count.get<ConstantInt *>()->getSExtValue() >= -1,
  905. "invalid subrange count", &N);
  906. auto *LBound = N.getRawLowerBound();
  907. CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
  908. isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
  909. "LowerBound must be signed constant or DIVariable or DIExpression",
  910. &N);
  911. auto *UBound = N.getRawUpperBound();
  912. CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
  913. isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
  914. "UpperBound must be signed constant or DIVariable or DIExpression",
  915. &N);
  916. auto *Stride = N.getRawStride();
  917. CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
  918. isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
  919. "Stride must be signed constant or DIVariable or DIExpression", &N);
  920. }
  921. void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
  922. CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
  923. CheckDI(N.getRawCountNode() || N.getRawUpperBound(),
  924. "GenericSubrange must contain count or upperBound", &N);
  925. CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
  926. "GenericSubrange can have any one of count or upperBound", &N);
  927. auto *CBound = N.getRawCountNode();
  928. CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
  929. "Count must be signed constant or DIVariable or DIExpression", &N);
  930. auto *LBound = N.getRawLowerBound();
  931. CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
  932. CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
  933. "LowerBound must be signed constant or DIVariable or DIExpression",
  934. &N);
  935. auto *UBound = N.getRawUpperBound();
  936. CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
  937. "UpperBound must be signed constant or DIVariable or DIExpression",
  938. &N);
  939. auto *Stride = N.getRawStride();
  940. CheckDI(Stride, "GenericSubrange must contain stride", &N);
  941. CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
  942. "Stride must be signed constant or DIVariable or DIExpression", &N);
  943. }
  944. void Verifier::visitDIEnumerator(const DIEnumerator &N) {
  945. CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
  946. }
  947. void Verifier::visitDIBasicType(const DIBasicType &N) {
  948. CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
  949. N.getTag() == dwarf::DW_TAG_unspecified_type ||
  950. N.getTag() == dwarf::DW_TAG_string_type,
  951. "invalid tag", &N);
  952. }
  953. void Verifier::visitDIStringType(const DIStringType &N) {
  954. CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
  955. CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
  956. &N);
  957. }
  958. void Verifier::visitDIDerivedType(const DIDerivedType &N) {
  959. // Common scope checks.
  960. visitDIScope(N);
  961. CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
  962. N.getTag() == dwarf::DW_TAG_pointer_type ||
  963. N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
  964. N.getTag() == dwarf::DW_TAG_reference_type ||
  965. N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
  966. N.getTag() == dwarf::DW_TAG_const_type ||
  967. N.getTag() == dwarf::DW_TAG_immutable_type ||
  968. N.getTag() == dwarf::DW_TAG_volatile_type ||
  969. N.getTag() == dwarf::DW_TAG_restrict_type ||
  970. N.getTag() == dwarf::DW_TAG_atomic_type ||
  971. N.getTag() == dwarf::DW_TAG_member ||
  972. N.getTag() == dwarf::DW_TAG_inheritance ||
  973. N.getTag() == dwarf::DW_TAG_friend ||
  974. N.getTag() == dwarf::DW_TAG_set_type,
  975. "invalid tag", &N);
  976. if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
  977. CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
  978. N.getRawExtraData());
  979. }
  980. if (N.getTag() == dwarf::DW_TAG_set_type) {
  981. if (auto *T = N.getRawBaseType()) {
  982. auto *Enum = dyn_cast_or_null<DICompositeType>(T);
  983. auto *Basic = dyn_cast_or_null<DIBasicType>(T);
  984. CheckDI(
  985. (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
  986. (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
  987. Basic->getEncoding() == dwarf::DW_ATE_signed ||
  988. Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
  989. Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
  990. Basic->getEncoding() == dwarf::DW_ATE_boolean)),
  991. "invalid set base type", &N, T);
  992. }
  993. }
  994. CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
  995. CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
  996. N.getRawBaseType());
  997. if (N.getDWARFAddressSpace()) {
  998. CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
  999. N.getTag() == dwarf::DW_TAG_reference_type ||
  1000. N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
  1001. "DWARF address space only applies to pointer or reference types",
  1002. &N);
  1003. }
  1004. }
  1005. /// Detect mutually exclusive flags.
  1006. static bool hasConflictingReferenceFlags(unsigned Flags) {
  1007. return ((Flags & DINode::FlagLValueReference) &&
  1008. (Flags & DINode::FlagRValueReference)) ||
  1009. ((Flags & DINode::FlagTypePassByValue) &&
  1010. (Flags & DINode::FlagTypePassByReference));
  1011. }
  1012. void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
  1013. auto *Params = dyn_cast<MDTuple>(&RawParams);
  1014. CheckDI(Params, "invalid template params", &N, &RawParams);
  1015. for (Metadata *Op : Params->operands()) {
  1016. CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
  1017. &N, Params, Op);
  1018. }
  1019. }
  1020. void Verifier::visitDICompositeType(const DICompositeType &N) {
  1021. // Common scope checks.
  1022. visitDIScope(N);
  1023. CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
  1024. N.getTag() == dwarf::DW_TAG_structure_type ||
  1025. N.getTag() == dwarf::DW_TAG_union_type ||
  1026. N.getTag() == dwarf::DW_TAG_enumeration_type ||
  1027. N.getTag() == dwarf::DW_TAG_class_type ||
  1028. N.getTag() == dwarf::DW_TAG_variant_part ||
  1029. N.getTag() == dwarf::DW_TAG_namelist,
  1030. "invalid tag", &N);
  1031. CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
  1032. CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
  1033. N.getRawBaseType());
  1034. CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
  1035. "invalid composite elements", &N, N.getRawElements());
  1036. CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
  1037. N.getRawVTableHolder());
  1038. CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
  1039. "invalid reference flags", &N);
  1040. unsigned DIBlockByRefStruct = 1 << 4;
  1041. CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
  1042. "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
  1043. if (N.isVector()) {
  1044. const DINodeArray Elements = N.getElements();
  1045. CheckDI(Elements.size() == 1 &&
  1046. Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
  1047. "invalid vector, expected one element of type subrange", &N);
  1048. }
  1049. if (auto *Params = N.getRawTemplateParams())
  1050. visitTemplateParams(N, *Params);
  1051. if (auto *D = N.getRawDiscriminator()) {
  1052. CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
  1053. "discriminator can only appear on variant part");
  1054. }
  1055. if (N.getRawDataLocation()) {
  1056. CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
  1057. "dataLocation can only appear in array type");
  1058. }
  1059. if (N.getRawAssociated()) {
  1060. CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
  1061. "associated can only appear in array type");
  1062. }
  1063. if (N.getRawAllocated()) {
  1064. CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
  1065. "allocated can only appear in array type");
  1066. }
  1067. if (N.getRawRank()) {
  1068. CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
  1069. "rank can only appear in array type");
  1070. }
  1071. }
  1072. void Verifier::visitDISubroutineType(const DISubroutineType &N) {
  1073. CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
  1074. if (auto *Types = N.getRawTypeArray()) {
  1075. CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
  1076. for (Metadata *Ty : N.getTypeArray()->operands()) {
  1077. CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
  1078. }
  1079. }
  1080. CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
  1081. "invalid reference flags", &N);
  1082. }
  1083. void Verifier::visitDIFile(const DIFile &N) {
  1084. CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
  1085. std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
  1086. if (Checksum) {
  1087. CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
  1088. "invalid checksum kind", &N);
  1089. size_t Size;
  1090. switch (Checksum->Kind) {
  1091. case DIFile::CSK_MD5:
  1092. Size = 32;
  1093. break;
  1094. case DIFile::CSK_SHA1:
  1095. Size = 40;
  1096. break;
  1097. case DIFile::CSK_SHA256:
  1098. Size = 64;
  1099. break;
  1100. }
  1101. CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
  1102. CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
  1103. "invalid checksum", &N);
  1104. }
  1105. }
  1106. void Verifier::visitDICompileUnit(const DICompileUnit &N) {
  1107. CheckDI(N.isDistinct(), "compile units must be distinct", &N);
  1108. CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
  1109. // Don't bother verifying the compilation directory or producer string
  1110. // as those could be empty.
  1111. CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
  1112. N.getRawFile());
  1113. CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
  1114. N.getFile());
  1115. CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
  1116. verifySourceDebugInfo(N, *N.getFile());
  1117. CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
  1118. "invalid emission kind", &N);
  1119. if (auto *Array = N.getRawEnumTypes()) {
  1120. CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
  1121. for (Metadata *Op : N.getEnumTypes()->operands()) {
  1122. auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
  1123. CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
  1124. "invalid enum type", &N, N.getEnumTypes(), Op);
  1125. }
  1126. }
  1127. if (auto *Array = N.getRawRetainedTypes()) {
  1128. CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
  1129. for (Metadata *Op : N.getRetainedTypes()->operands()) {
  1130. CheckDI(
  1131. Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
  1132. !cast<DISubprogram>(Op)->isDefinition())),
  1133. "invalid retained type", &N, Op);
  1134. }
  1135. }
  1136. if (auto *Array = N.getRawGlobalVariables()) {
  1137. CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
  1138. for (Metadata *Op : N.getGlobalVariables()->operands()) {
  1139. CheckDI(Op && (isa<DIGlobalVariableExpression>(Op)),
  1140. "invalid global variable ref", &N, Op);
  1141. }
  1142. }
  1143. if (auto *Array = N.getRawImportedEntities()) {
  1144. CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
  1145. for (Metadata *Op : N.getImportedEntities()->operands()) {
  1146. CheckDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
  1147. &N, Op);
  1148. }
  1149. }
  1150. if (auto *Array = N.getRawMacros()) {
  1151. CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
  1152. for (Metadata *Op : N.getMacros()->operands()) {
  1153. CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
  1154. }
  1155. }
  1156. CUVisited.insert(&N);
  1157. }
  1158. void Verifier::visitDISubprogram(const DISubprogram &N) {
  1159. CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
  1160. CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
  1161. if (auto *F = N.getRawFile())
  1162. CheckDI(isa<DIFile>(F), "invalid file", &N, F);
  1163. else
  1164. CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
  1165. if (auto *T = N.getRawType())
  1166. CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
  1167. CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
  1168. N.getRawContainingType());
  1169. if (auto *Params = N.getRawTemplateParams())
  1170. visitTemplateParams(N, *Params);
  1171. if (auto *S = N.getRawDeclaration())
  1172. CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
  1173. "invalid subprogram declaration", &N, S);
  1174. if (auto *RawNode = N.getRawRetainedNodes()) {
  1175. auto *Node = dyn_cast<MDTuple>(RawNode);
  1176. CheckDI(Node, "invalid retained nodes list", &N, RawNode);
  1177. for (Metadata *Op : Node->operands()) {
  1178. CheckDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
  1179. "invalid retained nodes, expected DILocalVariable or DILabel", &N,
  1180. Node, Op);
  1181. }
  1182. }
  1183. CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
  1184. "invalid reference flags", &N);
  1185. auto *Unit = N.getRawUnit();
  1186. if (N.isDefinition()) {
  1187. // Subprogram definitions (not part of the type hierarchy).
  1188. CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
  1189. CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
  1190. CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
  1191. if (N.getFile())
  1192. verifySourceDebugInfo(*N.getUnit(), *N.getFile());
  1193. } else {
  1194. // Subprogram declarations (part of the type hierarchy).
  1195. CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
  1196. }
  1197. if (auto *RawThrownTypes = N.getRawThrownTypes()) {
  1198. auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
  1199. CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
  1200. for (Metadata *Op : ThrownTypes->operands())
  1201. CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
  1202. Op);
  1203. }
  1204. if (N.areAllCallsDescribed())
  1205. CheckDI(N.isDefinition(),
  1206. "DIFlagAllCallsDescribed must be attached to a definition");
  1207. }
  1208. void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
  1209. CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
  1210. CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
  1211. "invalid local scope", &N, N.getRawScope());
  1212. if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
  1213. CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
  1214. }
  1215. void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
  1216. visitDILexicalBlockBase(N);
  1217. CheckDI(N.getLine() || !N.getColumn(),
  1218. "cannot have column info without line info", &N);
  1219. }
  1220. void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
  1221. visitDILexicalBlockBase(N);
  1222. }
  1223. void Verifier::visitDICommonBlock(const DICommonBlock &N) {
  1224. CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
  1225. if (auto *S = N.getRawScope())
  1226. CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
  1227. if (auto *S = N.getRawDecl())
  1228. CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
  1229. }
  1230. void Verifier::visitDINamespace(const DINamespace &N) {
  1231. CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
  1232. if (auto *S = N.getRawScope())
  1233. CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
  1234. }
  1235. void Verifier::visitDIMacro(const DIMacro &N) {
  1236. CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
  1237. N.getMacinfoType() == dwarf::DW_MACINFO_undef,
  1238. "invalid macinfo type", &N);
  1239. CheckDI(!N.getName().empty(), "anonymous macro", &N);
  1240. if (!N.getValue().empty()) {
  1241. assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
  1242. }
  1243. }
  1244. void Verifier::visitDIMacroFile(const DIMacroFile &N) {
  1245. CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
  1246. "invalid macinfo type", &N);
  1247. if (auto *F = N.getRawFile())
  1248. CheckDI(isa<DIFile>(F), "invalid file", &N, F);
  1249. if (auto *Array = N.getRawElements()) {
  1250. CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
  1251. for (Metadata *Op : N.getElements()->operands()) {
  1252. CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
  1253. }
  1254. }
  1255. }
  1256. void Verifier::visitDIArgList(const DIArgList &N) {
  1257. CheckDI(!N.getNumOperands(),
  1258. "DIArgList should have no operands other than a list of "
  1259. "ValueAsMetadata",
  1260. &N);
  1261. }
  1262. void Verifier::visitDIModule(const DIModule &N) {
  1263. CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
  1264. CheckDI(!N.getName().empty(), "anonymous module", &N);
  1265. }
  1266. void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
  1267. CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
  1268. }
  1269. void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
  1270. visitDITemplateParameter(N);
  1271. CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
  1272. &N);
  1273. }
  1274. void Verifier::visitDITemplateValueParameter(
  1275. const DITemplateValueParameter &N) {
  1276. visitDITemplateParameter(N);
  1277. CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
  1278. N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
  1279. N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
  1280. "invalid tag", &N);
  1281. }
  1282. void Verifier::visitDIVariable(const DIVariable &N) {
  1283. if (auto *S = N.getRawScope())
  1284. CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
  1285. if (auto *F = N.getRawFile())
  1286. CheckDI(isa<DIFile>(F), "invalid file", &N, F);
  1287. }
  1288. void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
  1289. // Checks common to all variables.
  1290. visitDIVariable(N);
  1291. CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
  1292. CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
  1293. // Check only if the global variable is not an extern
  1294. if (N.isDefinition())
  1295. CheckDI(N.getType(), "missing global variable type", &N);
  1296. if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
  1297. CheckDI(isa<DIDerivedType>(Member),
  1298. "invalid static data member declaration", &N, Member);
  1299. }
  1300. }
  1301. void Verifier::visitDILocalVariable(const DILocalVariable &N) {
  1302. // Checks common to all variables.
  1303. visitDIVariable(N);
  1304. CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
  1305. CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
  1306. CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
  1307. "local variable requires a valid scope", &N, N.getRawScope());
  1308. if (auto Ty = N.getType())
  1309. CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
  1310. }
  1311. void Verifier::visitDIAssignID(const DIAssignID &N) {
  1312. CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
  1313. CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
  1314. }
  1315. void Verifier::visitDILabel(const DILabel &N) {
  1316. if (auto *S = N.getRawScope())
  1317. CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
  1318. if (auto *F = N.getRawFile())
  1319. CheckDI(isa<DIFile>(F), "invalid file", &N, F);
  1320. CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
  1321. CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
  1322. "label requires a valid scope", &N, N.getRawScope());
  1323. }
  1324. void Verifier::visitDIExpression(const DIExpression &N) {
  1325. CheckDI(N.isValid(), "invalid expression", &N);
  1326. }
  1327. void Verifier::visitDIGlobalVariableExpression(
  1328. const DIGlobalVariableExpression &GVE) {
  1329. CheckDI(GVE.getVariable(), "missing variable");
  1330. if (auto *Var = GVE.getVariable())
  1331. visitDIGlobalVariable(*Var);
  1332. if (auto *Expr = GVE.getExpression()) {
  1333. visitDIExpression(*Expr);
  1334. if (auto Fragment = Expr->getFragmentInfo())
  1335. verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
  1336. }
  1337. }
  1338. void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
  1339. CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
  1340. if (auto *T = N.getRawType())
  1341. CheckDI(isType(T), "invalid type ref", &N, T);
  1342. if (auto *F = N.getRawFile())
  1343. CheckDI(isa<DIFile>(F), "invalid file", &N, F);
  1344. }
  1345. void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
  1346. CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
  1347. N.getTag() == dwarf::DW_TAG_imported_declaration,
  1348. "invalid tag", &N);
  1349. if (auto *S = N.getRawScope())
  1350. CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
  1351. CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
  1352. N.getRawEntity());
  1353. }
  1354. void Verifier::visitComdat(const Comdat &C) {
  1355. // In COFF the Module is invalid if the GlobalValue has private linkage.
  1356. // Entities with private linkage don't have entries in the symbol table.
  1357. if (TT.isOSBinFormatCOFF())
  1358. if (const GlobalValue *GV = M.getNamedValue(C.getName()))
  1359. Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
  1360. GV);
  1361. }
  1362. void Verifier::visitModuleIdents() {
  1363. const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
  1364. if (!Idents)
  1365. return;
  1366. // llvm.ident takes a list of metadata entry. Each entry has only one string.
  1367. // Scan each llvm.ident entry and make sure that this requirement is met.
  1368. for (const MDNode *N : Idents->operands()) {
  1369. Check(N->getNumOperands() == 1,
  1370. "incorrect number of operands in llvm.ident metadata", N);
  1371. Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
  1372. ("invalid value for llvm.ident metadata entry operand"
  1373. "(the operand should be a string)"),
  1374. N->getOperand(0));
  1375. }
  1376. }
  1377. void Verifier::visitModuleCommandLines() {
  1378. const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
  1379. if (!CommandLines)
  1380. return;
  1381. // llvm.commandline takes a list of metadata entry. Each entry has only one
  1382. // string. Scan each llvm.commandline entry and make sure that this
  1383. // requirement is met.
  1384. for (const MDNode *N : CommandLines->operands()) {
  1385. Check(N->getNumOperands() == 1,
  1386. "incorrect number of operands in llvm.commandline metadata", N);
  1387. Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
  1388. ("invalid value for llvm.commandline metadata entry operand"
  1389. "(the operand should be a string)"),
  1390. N->getOperand(0));
  1391. }
  1392. }
  1393. void Verifier::visitModuleFlags() {
  1394. const NamedMDNode *Flags = M.getModuleFlagsMetadata();
  1395. if (!Flags) return;
  1396. // Scan each flag, and track the flags and requirements.
  1397. DenseMap<const MDString*, const MDNode*> SeenIDs;
  1398. SmallVector<const MDNode*, 16> Requirements;
  1399. for (const MDNode *MDN : Flags->operands())
  1400. visitModuleFlag(MDN, SeenIDs, Requirements);
  1401. // Validate that the requirements in the module are valid.
  1402. for (const MDNode *Requirement : Requirements) {
  1403. const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
  1404. const Metadata *ReqValue = Requirement->getOperand(1);
  1405. const MDNode *Op = SeenIDs.lookup(Flag);
  1406. if (!Op) {
  1407. CheckFailed("invalid requirement on flag, flag is not present in module",
  1408. Flag);
  1409. continue;
  1410. }
  1411. if (Op->getOperand(2) != ReqValue) {
  1412. CheckFailed(("invalid requirement on flag, "
  1413. "flag does not have the required value"),
  1414. Flag);
  1415. continue;
  1416. }
  1417. }
  1418. }
  1419. void
  1420. Verifier::visitModuleFlag(const MDNode *Op,
  1421. DenseMap<const MDString *, const MDNode *> &SeenIDs,
  1422. SmallVectorImpl<const MDNode *> &Requirements) {
  1423. // Each module flag should have three arguments, the merge behavior (a
  1424. // constant int), the flag ID (an MDString), and the value.
  1425. Check(Op->getNumOperands() == 3,
  1426. "incorrect number of operands in module flag", Op);
  1427. Module::ModFlagBehavior MFB;
  1428. if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
  1429. Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
  1430. "invalid behavior operand in module flag (expected constant integer)",
  1431. Op->getOperand(0));
  1432. Check(false,
  1433. "invalid behavior operand in module flag (unexpected constant)",
  1434. Op->getOperand(0));
  1435. }
  1436. MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
  1437. Check(ID, "invalid ID operand in module flag (expected metadata string)",
  1438. Op->getOperand(1));
  1439. // Check the values for behaviors with additional requirements.
  1440. switch (MFB) {
  1441. case Module::Error:
  1442. case Module::Warning:
  1443. case Module::Override:
  1444. // These behavior types accept any value.
  1445. break;
  1446. case Module::Min: {
  1447. auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
  1448. Check(V && V->getValue().isNonNegative(),
  1449. "invalid value for 'min' module flag (expected constant non-negative "
  1450. "integer)",
  1451. Op->getOperand(2));
  1452. break;
  1453. }
  1454. case Module::Max: {
  1455. Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
  1456. "invalid value for 'max' module flag (expected constant integer)",
  1457. Op->getOperand(2));
  1458. break;
  1459. }
  1460. case Module::Require: {
  1461. // The value should itself be an MDNode with two operands, a flag ID (an
  1462. // MDString), and a value.
  1463. MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
  1464. Check(Value && Value->getNumOperands() == 2,
  1465. "invalid value for 'require' module flag (expected metadata pair)",
  1466. Op->getOperand(2));
  1467. Check(isa<MDString>(Value->getOperand(0)),
  1468. ("invalid value for 'require' module flag "
  1469. "(first value operand should be a string)"),
  1470. Value->getOperand(0));
  1471. // Append it to the list of requirements, to check once all module flags are
  1472. // scanned.
  1473. Requirements.push_back(Value);
  1474. break;
  1475. }
  1476. case Module::Append:
  1477. case Module::AppendUnique: {
  1478. // These behavior types require the operand be an MDNode.
  1479. Check(isa<MDNode>(Op->getOperand(2)),
  1480. "invalid value for 'append'-type module flag "
  1481. "(expected a metadata node)",
  1482. Op->getOperand(2));
  1483. break;
  1484. }
  1485. }
  1486. // Unless this is a "requires" flag, check the ID is unique.
  1487. if (MFB != Module::Require) {
  1488. bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
  1489. Check(Inserted,
  1490. "module flag identifiers must be unique (or of 'require' type)", ID);
  1491. }
  1492. if (ID->getString() == "wchar_size") {
  1493. ConstantInt *Value
  1494. = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
  1495. Check(Value, "wchar_size metadata requires constant integer argument");
  1496. }
  1497. if (ID->getString() == "Linker Options") {
  1498. // If the llvm.linker.options named metadata exists, we assume that the
  1499. // bitcode reader has upgraded the module flag. Otherwise the flag might
  1500. // have been created by a client directly.
  1501. Check(M.getNamedMetadata("llvm.linker.options"),
  1502. "'Linker Options' named metadata no longer supported");
  1503. }
  1504. if (ID->getString() == "SemanticInterposition") {
  1505. ConstantInt *Value =
  1506. mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
  1507. Check(Value,
  1508. "SemanticInterposition metadata requires constant integer argument");
  1509. }
  1510. if (ID->getString() == "CG Profile") {
  1511. for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
  1512. visitModuleFlagCGProfileEntry(MDO);
  1513. }
  1514. }
  1515. void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
  1516. auto CheckFunction = [&](const MDOperand &FuncMDO) {
  1517. if (!FuncMDO)
  1518. return;
  1519. auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
  1520. Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
  1521. "expected a Function or null", FuncMDO);
  1522. };
  1523. auto Node = dyn_cast_or_null<MDNode>(MDO);
  1524. Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
  1525. CheckFunction(Node->getOperand(0));
  1526. CheckFunction(Node->getOperand(1));
  1527. auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
  1528. Check(Count && Count->getType()->isIntegerTy(),
  1529. "expected an integer constant", Node->getOperand(2));
  1530. }
  1531. void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
  1532. for (Attribute A : Attrs) {
  1533. if (A.isStringAttribute()) {
  1534. #define GET_ATTR_NAMES
  1535. #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
  1536. #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
  1537. if (A.getKindAsString() == #DISPLAY_NAME) { \
  1538. auto V = A.getValueAsString(); \
  1539. if (!(V.empty() || V == "true" || V == "false")) \
  1540. CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
  1541. ""); \
  1542. }
  1543. #include "llvm/IR/Attributes.inc"
  1544. continue;
  1545. }
  1546. if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
  1547. CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
  1548. V);
  1549. return;
  1550. }
  1551. }
  1552. }
  1553. // VerifyParameterAttrs - Check the given attributes for an argument or return
  1554. // value of the specified type. The value V is printed in error messages.
  1555. void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
  1556. const Value *V) {
  1557. if (!Attrs.hasAttributes())
  1558. return;
  1559. verifyAttributeTypes(Attrs, V);
  1560. for (Attribute Attr : Attrs)
  1561. Check(Attr.isStringAttribute() ||
  1562. Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
  1563. "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
  1564. V);
  1565. if (Attrs.hasAttribute(Attribute::ImmArg)) {
  1566. Check(Attrs.getNumAttributes() == 1,
  1567. "Attribute 'immarg' is incompatible with other attributes", V);
  1568. }
  1569. // Check for mutually incompatible attributes. Only inreg is compatible with
  1570. // sret.
  1571. unsigned AttrCount = 0;
  1572. AttrCount += Attrs.hasAttribute(Attribute::ByVal);
  1573. AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
  1574. AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
  1575. AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
  1576. Attrs.hasAttribute(Attribute::InReg);
  1577. AttrCount += Attrs.hasAttribute(Attribute::Nest);
  1578. AttrCount += Attrs.hasAttribute(Attribute::ByRef);
  1579. Check(AttrCount <= 1,
  1580. "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
  1581. "'byref', and 'sret' are incompatible!",
  1582. V);
  1583. Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
  1584. Attrs.hasAttribute(Attribute::ReadOnly)),
  1585. "Attributes "
  1586. "'inalloca and readonly' are incompatible!",
  1587. V);
  1588. Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
  1589. Attrs.hasAttribute(Attribute::Returned)),
  1590. "Attributes "
  1591. "'sret and returned' are incompatible!",
  1592. V);
  1593. Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
  1594. Attrs.hasAttribute(Attribute::SExt)),
  1595. "Attributes "
  1596. "'zeroext and signext' are incompatible!",
  1597. V);
  1598. Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
  1599. Attrs.hasAttribute(Attribute::ReadOnly)),
  1600. "Attributes "
  1601. "'readnone and readonly' are incompatible!",
  1602. V);
  1603. Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
  1604. Attrs.hasAttribute(Attribute::WriteOnly)),
  1605. "Attributes "
  1606. "'readnone and writeonly' are incompatible!",
  1607. V);
  1608. Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
  1609. Attrs.hasAttribute(Attribute::WriteOnly)),
  1610. "Attributes "
  1611. "'readonly and writeonly' are incompatible!",
  1612. V);
  1613. Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
  1614. Attrs.hasAttribute(Attribute::AlwaysInline)),
  1615. "Attributes "
  1616. "'noinline and alwaysinline' are incompatible!",
  1617. V);
  1618. AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
  1619. for (Attribute Attr : Attrs) {
  1620. if (!Attr.isStringAttribute() &&
  1621. IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
  1622. CheckFailed("Attribute '" + Attr.getAsString() +
  1623. "' applied to incompatible type!", V);
  1624. return;
  1625. }
  1626. }
  1627. if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
  1628. if (Attrs.hasAttribute(Attribute::ByVal)) {
  1629. if (Attrs.hasAttribute(Attribute::Alignment)) {
  1630. Align AttrAlign = Attrs.getAlignment().valueOrOne();
  1631. Align MaxAlign(ParamMaxAlignment);
  1632. Check(AttrAlign <= MaxAlign,
  1633. "Attribute 'align' exceed the max size 2^14", V);
  1634. }
  1635. SmallPtrSet<Type *, 4> Visited;
  1636. Check(Attrs.getByValType()->isSized(&Visited),
  1637. "Attribute 'byval' does not support unsized types!", V);
  1638. }
  1639. if (Attrs.hasAttribute(Attribute::ByRef)) {
  1640. SmallPtrSet<Type *, 4> Visited;
  1641. Check(Attrs.getByRefType()->isSized(&Visited),
  1642. "Attribute 'byref' does not support unsized types!", V);
  1643. }
  1644. if (Attrs.hasAttribute(Attribute::InAlloca)) {
  1645. SmallPtrSet<Type *, 4> Visited;
  1646. Check(Attrs.getInAllocaType()->isSized(&Visited),
  1647. "Attribute 'inalloca' does not support unsized types!", V);
  1648. }
  1649. if (Attrs.hasAttribute(Attribute::Preallocated)) {
  1650. SmallPtrSet<Type *, 4> Visited;
  1651. Check(Attrs.getPreallocatedType()->isSized(&Visited),
  1652. "Attribute 'preallocated' does not support unsized types!", V);
  1653. }
  1654. if (!PTy->isOpaque()) {
  1655. if (!isa<PointerType>(PTy->getNonOpaquePointerElementType()))
  1656. Check(!Attrs.hasAttribute(Attribute::SwiftError),
  1657. "Attribute 'swifterror' only applies to parameters "
  1658. "with pointer to pointer type!",
  1659. V);
  1660. if (Attrs.hasAttribute(Attribute::ByRef)) {
  1661. Check(Attrs.getByRefType() == PTy->getNonOpaquePointerElementType(),
  1662. "Attribute 'byref' type does not match parameter!", V);
  1663. }
  1664. if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
  1665. Check(Attrs.getByValType() == PTy->getNonOpaquePointerElementType(),
  1666. "Attribute 'byval' type does not match parameter!", V);
  1667. }
  1668. if (Attrs.hasAttribute(Attribute::Preallocated)) {
  1669. Check(Attrs.getPreallocatedType() ==
  1670. PTy->getNonOpaquePointerElementType(),
  1671. "Attribute 'preallocated' type does not match parameter!", V);
  1672. }
  1673. if (Attrs.hasAttribute(Attribute::InAlloca)) {
  1674. Check(Attrs.getInAllocaType() == PTy->getNonOpaquePointerElementType(),
  1675. "Attribute 'inalloca' type does not match parameter!", V);
  1676. }
  1677. if (Attrs.hasAttribute(Attribute::ElementType)) {
  1678. Check(Attrs.getElementType() == PTy->getNonOpaquePointerElementType(),
  1679. "Attribute 'elementtype' type does not match parameter!", V);
  1680. }
  1681. }
  1682. }
  1683. }
  1684. void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
  1685. const Value *V) {
  1686. if (Attrs.hasFnAttr(Attr)) {
  1687. StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
  1688. unsigned N;
  1689. if (S.getAsInteger(10, N))
  1690. CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
  1691. }
  1692. }
  1693. // Check parameter attributes against a function type.
  1694. // The value V is printed in error messages.
  1695. void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
  1696. const Value *V, bool IsIntrinsic,
  1697. bool IsInlineAsm) {
  1698. if (Attrs.isEmpty())
  1699. return;
  1700. if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
  1701. Check(Attrs.hasParentContext(Context),
  1702. "Attribute list does not match Module context!", &Attrs, V);
  1703. for (const auto &AttrSet : Attrs) {
  1704. Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
  1705. "Attribute set does not match Module context!", &AttrSet, V);
  1706. for (const auto &A : AttrSet) {
  1707. Check(A.hasParentContext(Context),
  1708. "Attribute does not match Module context!", &A, V);
  1709. }
  1710. }
  1711. }
  1712. bool SawNest = false;
  1713. bool SawReturned = false;
  1714. bool SawSRet = false;
  1715. bool SawSwiftSelf = false;
  1716. bool SawSwiftAsync = false;
  1717. bool SawSwiftError = false;
  1718. // Verify return value attributes.
  1719. AttributeSet RetAttrs = Attrs.getRetAttrs();
  1720. for (Attribute RetAttr : RetAttrs)
  1721. Check(RetAttr.isStringAttribute() ||
  1722. Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
  1723. "Attribute '" + RetAttr.getAsString() +
  1724. "' does not apply to function return values",
  1725. V);
  1726. verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
  1727. // Verify parameter attributes.
  1728. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1729. Type *Ty = FT->getParamType(i);
  1730. AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
  1731. if (!IsIntrinsic) {
  1732. Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
  1733. "immarg attribute only applies to intrinsics", V);
  1734. if (!IsInlineAsm)
  1735. Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
  1736. "Attribute 'elementtype' can only be applied to intrinsics"
  1737. " and inline asm.",
  1738. V);
  1739. }
  1740. verifyParameterAttrs(ArgAttrs, Ty, V);
  1741. if (ArgAttrs.hasAttribute(Attribute::Nest)) {
  1742. Check(!SawNest, "More than one parameter has attribute nest!", V);
  1743. SawNest = true;
  1744. }
  1745. if (ArgAttrs.hasAttribute(Attribute::Returned)) {
  1746. Check(!SawReturned, "More than one parameter has attribute returned!", V);
  1747. Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
  1748. "Incompatible argument and return types for 'returned' attribute",
  1749. V);
  1750. SawReturned = true;
  1751. }
  1752. if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
  1753. Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
  1754. Check(i == 0 || i == 1,
  1755. "Attribute 'sret' is not on first or second parameter!", V);
  1756. SawSRet = true;
  1757. }
  1758. if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
  1759. Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
  1760. SawSwiftSelf = true;
  1761. }
  1762. if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
  1763. Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
  1764. SawSwiftAsync = true;
  1765. }
  1766. if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
  1767. Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
  1768. SawSwiftError = true;
  1769. }
  1770. if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
  1771. Check(i == FT->getNumParams() - 1,
  1772. "inalloca isn't on the last parameter!", V);
  1773. }
  1774. }
  1775. if (!Attrs.hasFnAttrs())
  1776. return;
  1777. verifyAttributeTypes(Attrs.getFnAttrs(), V);
  1778. for (Attribute FnAttr : Attrs.getFnAttrs())
  1779. Check(FnAttr.isStringAttribute() ||
  1780. Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
  1781. "Attribute '" + FnAttr.getAsString() +
  1782. "' does not apply to functions!",
  1783. V);
  1784. Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
  1785. Attrs.hasFnAttr(Attribute::AlwaysInline)),
  1786. "Attributes 'noinline and alwaysinline' are incompatible!", V);
  1787. if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
  1788. Check(Attrs.hasFnAttr(Attribute::NoInline),
  1789. "Attribute 'optnone' requires 'noinline'!", V);
  1790. Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
  1791. "Attributes 'optsize and optnone' are incompatible!", V);
  1792. Check(!Attrs.hasFnAttr(Attribute::MinSize),
  1793. "Attributes 'minsize and optnone' are incompatible!", V);
  1794. }
  1795. if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
  1796. Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
  1797. "Attributes 'aarch64_pstate_sm_enabled and "
  1798. "aarch64_pstate_sm_compatible' are incompatible!",
  1799. V);
  1800. }
  1801. if (Attrs.hasFnAttr("aarch64_pstate_za_new")) {
  1802. Check(!Attrs.hasFnAttr("aarch64_pstate_za_preserved"),
  1803. "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
  1804. "are incompatible!",
  1805. V);
  1806. Check(!Attrs.hasFnAttr("aarch64_pstate_za_shared"),
  1807. "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
  1808. "are incompatible!",
  1809. V);
  1810. }
  1811. if (Attrs.hasFnAttr(Attribute::JumpTable)) {
  1812. const GlobalValue *GV = cast<GlobalValue>(V);
  1813. Check(GV->hasGlobalUnnamedAddr(),
  1814. "Attribute 'jumptable' requires 'unnamed_addr'", V);
  1815. }
  1816. if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
  1817. auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
  1818. if (ParamNo >= FT->getNumParams()) {
  1819. CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
  1820. return false;
  1821. }
  1822. if (!FT->getParamType(ParamNo)->isIntegerTy()) {
  1823. CheckFailed("'allocsize' " + Name +
  1824. " argument must refer to an integer parameter",
  1825. V);
  1826. return false;
  1827. }
  1828. return true;
  1829. };
  1830. if (!CheckParam("element size", Args->first))
  1831. return;
  1832. if (Args->second && !CheckParam("number of elements", *Args->second))
  1833. return;
  1834. }
  1835. if (Attrs.hasFnAttr(Attribute::AllocKind)) {
  1836. AllocFnKind K = Attrs.getAllocKind();
  1837. AllocFnKind Type =
  1838. K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
  1839. if (!is_contained(
  1840. {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
  1841. Type))
  1842. CheckFailed(
  1843. "'allockind()' requires exactly one of alloc, realloc, and free");
  1844. if ((Type == AllocFnKind::Free) &&
  1845. ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
  1846. AllocFnKind::Aligned)) != AllocFnKind::Unknown))
  1847. CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
  1848. "or aligned modifiers.");
  1849. AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
  1850. if ((K & ZeroedUninit) == ZeroedUninit)
  1851. CheckFailed("'allockind()' can't be both zeroed and uninitialized");
  1852. }
  1853. if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
  1854. unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
  1855. if (VScaleMin == 0)
  1856. CheckFailed("'vscale_range' minimum must be greater than 0", V);
  1857. std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
  1858. if (VScaleMax && VScaleMin > VScaleMax)
  1859. CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
  1860. }
  1861. if (Attrs.hasFnAttr("frame-pointer")) {
  1862. StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
  1863. if (FP != "all" && FP != "non-leaf" && FP != "none")
  1864. CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
  1865. }
  1866. checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
  1867. checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
  1868. checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
  1869. }
  1870. void Verifier::verifyFunctionMetadata(
  1871. ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
  1872. for (const auto &Pair : MDs) {
  1873. if (Pair.first == LLVMContext::MD_prof) {
  1874. MDNode *MD = Pair.second;
  1875. Check(MD->getNumOperands() >= 2,
  1876. "!prof annotations should have no less than 2 operands", MD);
  1877. // Check first operand.
  1878. Check(MD->getOperand(0) != nullptr, "first operand should not be null",
  1879. MD);
  1880. Check(isa<MDString>(MD->getOperand(0)),
  1881. "expected string with name of the !prof annotation", MD);
  1882. MDString *MDS = cast<MDString>(MD->getOperand(0));
  1883. StringRef ProfName = MDS->getString();
  1884. Check(ProfName.equals("function_entry_count") ||
  1885. ProfName.equals("synthetic_function_entry_count"),
  1886. "first operand should be 'function_entry_count'"
  1887. " or 'synthetic_function_entry_count'",
  1888. MD);
  1889. // Check second operand.
  1890. Check(MD->getOperand(1) != nullptr, "second operand should not be null",
  1891. MD);
  1892. Check(isa<ConstantAsMetadata>(MD->getOperand(1)),
  1893. "expected integer argument to function_entry_count", MD);
  1894. } else if (Pair.first == LLVMContext::MD_kcfi_type) {
  1895. MDNode *MD = Pair.second;
  1896. Check(MD->getNumOperands() == 1,
  1897. "!kcfi_type must have exactly one operand", MD);
  1898. Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
  1899. MD);
  1900. Check(isa<ConstantAsMetadata>(MD->getOperand(0)),
  1901. "expected a constant operand for !kcfi_type", MD);
  1902. Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
  1903. Check(isa<ConstantInt>(C),
  1904. "expected a constant integer operand for !kcfi_type", MD);
  1905. IntegerType *Type = cast<ConstantInt>(C)->getType();
  1906. Check(Type->getBitWidth() == 32,
  1907. "expected a 32-bit integer constant operand for !kcfi_type", MD);
  1908. }
  1909. }
  1910. }
  1911. void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
  1912. if (!ConstantExprVisited.insert(EntryC).second)
  1913. return;
  1914. SmallVector<const Constant *, 16> Stack;
  1915. Stack.push_back(EntryC);
  1916. while (!Stack.empty()) {
  1917. const Constant *C = Stack.pop_back_val();
  1918. // Check this constant expression.
  1919. if (const auto *CE = dyn_cast<ConstantExpr>(C))
  1920. visitConstantExpr(CE);
  1921. if (const auto *GV = dyn_cast<GlobalValue>(C)) {
  1922. // Global Values get visited separately, but we do need to make sure
  1923. // that the global value is in the correct module
  1924. Check(GV->getParent() == &M, "Referencing global in another module!",
  1925. EntryC, &M, GV, GV->getParent());
  1926. continue;
  1927. }
  1928. // Visit all sub-expressions.
  1929. for (const Use &U : C->operands()) {
  1930. const auto *OpC = dyn_cast<Constant>(U);
  1931. if (!OpC)
  1932. continue;
  1933. if (!ConstantExprVisited.insert(OpC).second)
  1934. continue;
  1935. Stack.push_back(OpC);
  1936. }
  1937. }
  1938. }
  1939. void Verifier::visitConstantExpr(const ConstantExpr *CE) {
  1940. if (CE->getOpcode() == Instruction::BitCast)
  1941. Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
  1942. CE->getType()),
  1943. "Invalid bitcast", CE);
  1944. }
  1945. bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
  1946. // There shouldn't be more attribute sets than there are parameters plus the
  1947. // function and return value.
  1948. return Attrs.getNumAttrSets() <= Params + 2;
  1949. }
  1950. void Verifier::verifyInlineAsmCall(const CallBase &Call) {
  1951. const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
  1952. unsigned ArgNo = 0;
  1953. unsigned LabelNo = 0;
  1954. for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
  1955. if (CI.Type == InlineAsm::isLabel) {
  1956. ++LabelNo;
  1957. continue;
  1958. }
  1959. // Only deal with constraints that correspond to call arguments.
  1960. if (!CI.hasArg())
  1961. continue;
  1962. if (CI.isIndirect) {
  1963. const Value *Arg = Call.getArgOperand(ArgNo);
  1964. Check(Arg->getType()->isPointerTy(),
  1965. "Operand for indirect constraint must have pointer type", &Call);
  1966. Check(Call.getParamElementType(ArgNo),
  1967. "Operand for indirect constraint must have elementtype attribute",
  1968. &Call);
  1969. } else {
  1970. Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
  1971. "Elementtype attribute can only be applied for indirect "
  1972. "constraints",
  1973. &Call);
  1974. }
  1975. ArgNo++;
  1976. }
  1977. if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
  1978. Check(LabelNo == CallBr->getNumIndirectDests(),
  1979. "Number of label constraints does not match number of callbr dests",
  1980. &Call);
  1981. } else {
  1982. Check(LabelNo == 0, "Label constraints can only be used with callbr",
  1983. &Call);
  1984. }
  1985. }
  1986. /// Verify that statepoint intrinsic is well formed.
  1987. void Verifier::verifyStatepoint(const CallBase &Call) {
  1988. assert(Call.getCalledFunction() &&
  1989. Call.getCalledFunction()->getIntrinsicID() ==
  1990. Intrinsic::experimental_gc_statepoint);
  1991. Check(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
  1992. !Call.onlyAccessesArgMemory(),
  1993. "gc.statepoint must read and write all memory to preserve "
  1994. "reordering restrictions required by safepoint semantics",
  1995. Call);
  1996. const int64_t NumPatchBytes =
  1997. cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
  1998. assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
  1999. Check(NumPatchBytes >= 0,
  2000. "gc.statepoint number of patchable bytes must be "
  2001. "positive",
  2002. Call);
  2003. Type *TargetElemType = Call.getParamElementType(2);
  2004. Check(TargetElemType,
  2005. "gc.statepoint callee argument must have elementtype attribute", Call);
  2006. FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
  2007. Check(TargetFuncType,
  2008. "gc.statepoint callee elementtype must be function type", Call);
  2009. const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
  2010. Check(NumCallArgs >= 0,
  2011. "gc.statepoint number of arguments to underlying call "
  2012. "must be positive",
  2013. Call);
  2014. const int NumParams = (int)TargetFuncType->getNumParams();
  2015. if (TargetFuncType->isVarArg()) {
  2016. Check(NumCallArgs >= NumParams,
  2017. "gc.statepoint mismatch in number of vararg call args", Call);
  2018. // TODO: Remove this limitation
  2019. Check(TargetFuncType->getReturnType()->isVoidTy(),
  2020. "gc.statepoint doesn't support wrapping non-void "
  2021. "vararg functions yet",
  2022. Call);
  2023. } else
  2024. Check(NumCallArgs == NumParams,
  2025. "gc.statepoint mismatch in number of call args", Call);
  2026. const uint64_t Flags
  2027. = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
  2028. Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
  2029. "unknown flag used in gc.statepoint flags argument", Call);
  2030. // Verify that the types of the call parameter arguments match
  2031. // the type of the wrapped callee.
  2032. AttributeList Attrs = Call.getAttributes();
  2033. for (int i = 0; i < NumParams; i++) {
  2034. Type *ParamType = TargetFuncType->getParamType(i);
  2035. Type *ArgType = Call.getArgOperand(5 + i)->getType();
  2036. Check(ArgType == ParamType,
  2037. "gc.statepoint call argument does not match wrapped "
  2038. "function type",
  2039. Call);
  2040. if (TargetFuncType->isVarArg()) {
  2041. AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
  2042. Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
  2043. "Attribute 'sret' cannot be used for vararg call arguments!", Call);
  2044. }
  2045. }
  2046. const int EndCallArgsInx = 4 + NumCallArgs;
  2047. const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
  2048. Check(isa<ConstantInt>(NumTransitionArgsV),
  2049. "gc.statepoint number of transition arguments "
  2050. "must be constant integer",
  2051. Call);
  2052. const int NumTransitionArgs =
  2053. cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
  2054. Check(NumTransitionArgs == 0,
  2055. "gc.statepoint w/inline transition bundle is deprecated", Call);
  2056. const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
  2057. const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
  2058. Check(isa<ConstantInt>(NumDeoptArgsV),
  2059. "gc.statepoint number of deoptimization arguments "
  2060. "must be constant integer",
  2061. Call);
  2062. const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
  2063. Check(NumDeoptArgs == 0,
  2064. "gc.statepoint w/inline deopt operands is deprecated", Call);
  2065. const int ExpectedNumArgs = 7 + NumCallArgs;
  2066. Check(ExpectedNumArgs == (int)Call.arg_size(),
  2067. "gc.statepoint too many arguments", Call);
  2068. // Check that the only uses of this gc.statepoint are gc.result or
  2069. // gc.relocate calls which are tied to this statepoint and thus part
  2070. // of the same statepoint sequence
  2071. for (const User *U : Call.users()) {
  2072. const CallInst *UserCall = dyn_cast<const CallInst>(U);
  2073. Check(UserCall, "illegal use of statepoint token", Call, U);
  2074. if (!UserCall)
  2075. continue;
  2076. Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
  2077. "gc.result or gc.relocate are the only value uses "
  2078. "of a gc.statepoint",
  2079. Call, U);
  2080. if (isa<GCResultInst>(UserCall)) {
  2081. Check(UserCall->getArgOperand(0) == &Call,
  2082. "gc.result connected to wrong gc.statepoint", Call, UserCall);
  2083. } else if (isa<GCRelocateInst>(Call)) {
  2084. Check(UserCall->getArgOperand(0) == &Call,
  2085. "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
  2086. }
  2087. }
  2088. // Note: It is legal for a single derived pointer to be listed multiple
  2089. // times. It's non-optimal, but it is legal. It can also happen after
  2090. // insertion if we strip a bitcast away.
  2091. // Note: It is really tempting to check that each base is relocated and
  2092. // that a derived pointer is never reused as a base pointer. This turns
  2093. // out to be problematic since optimizations run after safepoint insertion
  2094. // can recognize equality properties that the insertion logic doesn't know
  2095. // about. See example statepoint.ll in the verifier subdirectory
  2096. }
  2097. void Verifier::verifyFrameRecoverIndices() {
  2098. for (auto &Counts : FrameEscapeInfo) {
  2099. Function *F = Counts.first;
  2100. unsigned EscapedObjectCount = Counts.second.first;
  2101. unsigned MaxRecoveredIndex = Counts.second.second;
  2102. Check(MaxRecoveredIndex <= EscapedObjectCount,
  2103. "all indices passed to llvm.localrecover must be less than the "
  2104. "number of arguments passed to llvm.localescape in the parent "
  2105. "function",
  2106. F);
  2107. }
  2108. }
  2109. static Instruction *getSuccPad(Instruction *Terminator) {
  2110. BasicBlock *UnwindDest;
  2111. if (auto *II = dyn_cast<InvokeInst>(Terminator))
  2112. UnwindDest = II->getUnwindDest();
  2113. else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
  2114. UnwindDest = CSI->getUnwindDest();
  2115. else
  2116. UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
  2117. return UnwindDest->getFirstNonPHI();
  2118. }
  2119. void Verifier::verifySiblingFuncletUnwinds() {
  2120. SmallPtrSet<Instruction *, 8> Visited;
  2121. SmallPtrSet<Instruction *, 8> Active;
  2122. for (const auto &Pair : SiblingFuncletInfo) {
  2123. Instruction *PredPad = Pair.first;
  2124. if (Visited.count(PredPad))
  2125. continue;
  2126. Active.insert(PredPad);
  2127. Instruction *Terminator = Pair.second;
  2128. do {
  2129. Instruction *SuccPad = getSuccPad(Terminator);
  2130. if (Active.count(SuccPad)) {
  2131. // Found a cycle; report error
  2132. Instruction *CyclePad = SuccPad;
  2133. SmallVector<Instruction *, 8> CycleNodes;
  2134. do {
  2135. CycleNodes.push_back(CyclePad);
  2136. Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
  2137. if (CycleTerminator != CyclePad)
  2138. CycleNodes.push_back(CycleTerminator);
  2139. CyclePad = getSuccPad(CycleTerminator);
  2140. } while (CyclePad != SuccPad);
  2141. Check(false, "EH pads can't handle each other's exceptions",
  2142. ArrayRef<Instruction *>(CycleNodes));
  2143. }
  2144. // Don't re-walk a node we've already checked
  2145. if (!Visited.insert(SuccPad).second)
  2146. break;
  2147. // Walk to this successor if it has a map entry.
  2148. PredPad = SuccPad;
  2149. auto TermI = SiblingFuncletInfo.find(PredPad);
  2150. if (TermI == SiblingFuncletInfo.end())
  2151. break;
  2152. Terminator = TermI->second;
  2153. Active.insert(PredPad);
  2154. } while (true);
  2155. // Each node only has one successor, so we've walked all the active
  2156. // nodes' successors.
  2157. Active.clear();
  2158. }
  2159. }
  2160. // visitFunction - Verify that a function is ok.
  2161. //
  2162. void Verifier::visitFunction(const Function &F) {
  2163. visitGlobalValue(F);
  2164. // Check function arguments.
  2165. FunctionType *FT = F.getFunctionType();
  2166. unsigned NumArgs = F.arg_size();
  2167. Check(&Context == &F.getContext(),
  2168. "Function context does not match Module context!", &F);
  2169. Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
  2170. Check(FT->getNumParams() == NumArgs,
  2171. "# formal arguments must match # of arguments for function type!", &F,
  2172. FT);
  2173. Check(F.getReturnType()->isFirstClassType() ||
  2174. F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
  2175. "Functions cannot return aggregate values!", &F);
  2176. Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
  2177. "Invalid struct return type!", &F);
  2178. AttributeList Attrs = F.getAttributes();
  2179. Check(verifyAttributeCount(Attrs, FT->getNumParams()),
  2180. "Attribute after last parameter!", &F);
  2181. bool IsIntrinsic = F.isIntrinsic();
  2182. // Check function attributes.
  2183. verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
  2184. // On function declarations/definitions, we do not support the builtin
  2185. // attribute. We do not check this in VerifyFunctionAttrs since that is
  2186. // checking for Attributes that can/can not ever be on functions.
  2187. Check(!Attrs.hasFnAttr(Attribute::Builtin),
  2188. "Attribute 'builtin' can only be applied to a callsite.", &F);
  2189. Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
  2190. "Attribute 'elementtype' can only be applied to a callsite.", &F);
  2191. // Check that this function meets the restrictions on this calling convention.
  2192. // Sometimes varargs is used for perfectly forwarding thunks, so some of these
  2193. // restrictions can be lifted.
  2194. switch (F.getCallingConv()) {
  2195. default:
  2196. case CallingConv::C:
  2197. break;
  2198. case CallingConv::X86_INTR: {
  2199. Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
  2200. "Calling convention parameter requires byval", &F);
  2201. break;
  2202. }
  2203. case CallingConv::AMDGPU_KERNEL:
  2204. case CallingConv::SPIR_KERNEL:
  2205. Check(F.getReturnType()->isVoidTy(),
  2206. "Calling convention requires void return type", &F);
  2207. [[fallthrough]];
  2208. case CallingConv::AMDGPU_VS:
  2209. case CallingConv::AMDGPU_HS:
  2210. case CallingConv::AMDGPU_GS:
  2211. case CallingConv::AMDGPU_PS:
  2212. case CallingConv::AMDGPU_CS:
  2213. Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
  2214. if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
  2215. const unsigned StackAS = DL.getAllocaAddrSpace();
  2216. unsigned i = 0;
  2217. for (const Argument &Arg : F.args()) {
  2218. Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
  2219. "Calling convention disallows byval", &F);
  2220. Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
  2221. "Calling convention disallows preallocated", &F);
  2222. Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
  2223. "Calling convention disallows inalloca", &F);
  2224. if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
  2225. // FIXME: Should also disallow LDS and GDS, but we don't have the enum
  2226. // value here.
  2227. Check(Arg.getType()->getPointerAddressSpace() != StackAS,
  2228. "Calling convention disallows stack byref", &F);
  2229. }
  2230. ++i;
  2231. }
  2232. }
  2233. [[fallthrough]];
  2234. case CallingConv::Fast:
  2235. case CallingConv::Cold:
  2236. case CallingConv::Intel_OCL_BI:
  2237. case CallingConv::PTX_Kernel:
  2238. case CallingConv::PTX_Device:
  2239. Check(!F.isVarArg(),
  2240. "Calling convention does not support varargs or "
  2241. "perfect forwarding!",
  2242. &F);
  2243. break;
  2244. }
  2245. // Check that the argument values match the function type for this function...
  2246. unsigned i = 0;
  2247. for (const Argument &Arg : F.args()) {
  2248. Check(Arg.getType() == FT->getParamType(i),
  2249. "Argument value does not match function argument type!", &Arg,
  2250. FT->getParamType(i));
  2251. Check(Arg.getType()->isFirstClassType(),
  2252. "Function arguments must have first-class types!", &Arg);
  2253. if (!IsIntrinsic) {
  2254. Check(!Arg.getType()->isMetadataTy(),
  2255. "Function takes metadata but isn't an intrinsic", &Arg, &F);
  2256. Check(!Arg.getType()->isTokenTy(),
  2257. "Function takes token but isn't an intrinsic", &Arg, &F);
  2258. Check(!Arg.getType()->isX86_AMXTy(),
  2259. "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
  2260. }
  2261. // Check that swifterror argument is only used by loads and stores.
  2262. if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
  2263. verifySwiftErrorValue(&Arg);
  2264. }
  2265. ++i;
  2266. }
  2267. if (!IsIntrinsic) {
  2268. Check(!F.getReturnType()->isTokenTy(),
  2269. "Function returns a token but isn't an intrinsic", &F);
  2270. Check(!F.getReturnType()->isX86_AMXTy(),
  2271. "Function returns a x86_amx but isn't an intrinsic", &F);
  2272. }
  2273. // Get the function metadata attachments.
  2274. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  2275. F.getAllMetadata(MDs);
  2276. assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
  2277. verifyFunctionMetadata(MDs);
  2278. // Check validity of the personality function
  2279. if (F.hasPersonalityFn()) {
  2280. auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
  2281. if (Per)
  2282. Check(Per->getParent() == F.getParent(),
  2283. "Referencing personality function in another module!", &F,
  2284. F.getParent(), Per, Per->getParent());
  2285. }
  2286. if (F.isMaterializable()) {
  2287. // Function has a body somewhere we can't see.
  2288. Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
  2289. MDs.empty() ? nullptr : MDs.front().second);
  2290. } else if (F.isDeclaration()) {
  2291. for (const auto &I : MDs) {
  2292. // This is used for call site debug information.
  2293. CheckDI(I.first != LLVMContext::MD_dbg ||
  2294. !cast<DISubprogram>(I.second)->isDistinct(),
  2295. "function declaration may only have a unique !dbg attachment",
  2296. &F);
  2297. Check(I.first != LLVMContext::MD_prof,
  2298. "function declaration may not have a !prof attachment", &F);
  2299. // Verify the metadata itself.
  2300. visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
  2301. }
  2302. Check(!F.hasPersonalityFn(),
  2303. "Function declaration shouldn't have a personality routine", &F);
  2304. } else {
  2305. // Verify that this function (which has a body) is not named "llvm.*". It
  2306. // is not legal to define intrinsics.
  2307. Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
  2308. // Check the entry node
  2309. const BasicBlock *Entry = &F.getEntryBlock();
  2310. Check(pred_empty(Entry),
  2311. "Entry block to function must not have predecessors!", Entry);
  2312. // The address of the entry block cannot be taken, unless it is dead.
  2313. if (Entry->hasAddressTaken()) {
  2314. Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
  2315. "blockaddress may not be used with the entry block!", Entry);
  2316. }
  2317. unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
  2318. NumKCFIAttachments = 0;
  2319. // Visit metadata attachments.
  2320. for (const auto &I : MDs) {
  2321. // Verify that the attachment is legal.
  2322. auto AllowLocs = AreDebugLocsAllowed::No;
  2323. switch (I.first) {
  2324. default:
  2325. break;
  2326. case LLVMContext::MD_dbg: {
  2327. ++NumDebugAttachments;
  2328. CheckDI(NumDebugAttachments == 1,
  2329. "function must have a single !dbg attachment", &F, I.second);
  2330. CheckDI(isa<DISubprogram>(I.second),
  2331. "function !dbg attachment must be a subprogram", &F, I.second);
  2332. CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
  2333. "function definition may only have a distinct !dbg attachment",
  2334. &F);
  2335. auto *SP = cast<DISubprogram>(I.second);
  2336. const Function *&AttachedTo = DISubprogramAttachments[SP];
  2337. CheckDI(!AttachedTo || AttachedTo == &F,
  2338. "DISubprogram attached to more than one function", SP, &F);
  2339. AttachedTo = &F;
  2340. AllowLocs = AreDebugLocsAllowed::Yes;
  2341. break;
  2342. }
  2343. case LLVMContext::MD_prof:
  2344. ++NumProfAttachments;
  2345. Check(NumProfAttachments == 1,
  2346. "function must have a single !prof attachment", &F, I.second);
  2347. break;
  2348. case LLVMContext::MD_kcfi_type:
  2349. ++NumKCFIAttachments;
  2350. Check(NumKCFIAttachments == 1,
  2351. "function must have a single !kcfi_type attachment", &F,
  2352. I.second);
  2353. break;
  2354. }
  2355. // Verify the metadata itself.
  2356. visitMDNode(*I.second, AllowLocs);
  2357. }
  2358. }
  2359. // If this function is actually an intrinsic, verify that it is only used in
  2360. // direct call/invokes, never having its "address taken".
  2361. // Only do this if the module is materialized, otherwise we don't have all the
  2362. // uses.
  2363. if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
  2364. const User *U;
  2365. if (F.hasAddressTaken(&U, false, true, false,
  2366. /*IgnoreARCAttachedCall=*/true))
  2367. Check(false, "Invalid user of intrinsic instruction!", U);
  2368. }
  2369. // Check intrinsics' signatures.
  2370. switch (F.getIntrinsicID()) {
  2371. case Intrinsic::experimental_gc_get_pointer_base: {
  2372. FunctionType *FT = F.getFunctionType();
  2373. Check(FT->getNumParams() == 1, "wrong number of parameters", F);
  2374. Check(isa<PointerType>(F.getReturnType()),
  2375. "gc.get.pointer.base must return a pointer", F);
  2376. Check(FT->getParamType(0) == F.getReturnType(),
  2377. "gc.get.pointer.base operand and result must be of the same type", F);
  2378. break;
  2379. }
  2380. case Intrinsic::experimental_gc_get_pointer_offset: {
  2381. FunctionType *FT = F.getFunctionType();
  2382. Check(FT->getNumParams() == 1, "wrong number of parameters", F);
  2383. Check(isa<PointerType>(FT->getParamType(0)),
  2384. "gc.get.pointer.offset operand must be a pointer", F);
  2385. Check(F.getReturnType()->isIntegerTy(),
  2386. "gc.get.pointer.offset must return integer", F);
  2387. break;
  2388. }
  2389. }
  2390. auto *N = F.getSubprogram();
  2391. HasDebugInfo = (N != nullptr);
  2392. if (!HasDebugInfo)
  2393. return;
  2394. // Check that all !dbg attachments lead to back to N.
  2395. //
  2396. // FIXME: Check this incrementally while visiting !dbg attachments.
  2397. // FIXME: Only check when N is the canonical subprogram for F.
  2398. SmallPtrSet<const MDNode *, 32> Seen;
  2399. auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
  2400. // Be careful about using DILocation here since we might be dealing with
  2401. // broken code (this is the Verifier after all).
  2402. const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
  2403. if (!DL)
  2404. return;
  2405. if (!Seen.insert(DL).second)
  2406. return;
  2407. Metadata *Parent = DL->getRawScope();
  2408. CheckDI(Parent && isa<DILocalScope>(Parent),
  2409. "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
  2410. DILocalScope *Scope = DL->getInlinedAtScope();
  2411. Check(Scope, "Failed to find DILocalScope", DL);
  2412. if (!Seen.insert(Scope).second)
  2413. return;
  2414. DISubprogram *SP = Scope->getSubprogram();
  2415. // Scope and SP could be the same MDNode and we don't want to skip
  2416. // validation in that case
  2417. if (SP && ((Scope != SP) && !Seen.insert(SP).second))
  2418. return;
  2419. CheckDI(SP->describes(&F),
  2420. "!dbg attachment points at wrong subprogram for function", N, &F,
  2421. &I, DL, Scope, SP);
  2422. };
  2423. for (auto &BB : F)
  2424. for (auto &I : BB) {
  2425. VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
  2426. // The llvm.loop annotations also contain two DILocations.
  2427. if (auto MD = I.getMetadata(LLVMContext::MD_loop))
  2428. for (unsigned i = 1; i < MD->getNumOperands(); ++i)
  2429. VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
  2430. if (BrokenDebugInfo)
  2431. return;
  2432. }
  2433. }
  2434. // verifyBasicBlock - Verify that a basic block is well formed...
  2435. //
  2436. void Verifier::visitBasicBlock(BasicBlock &BB) {
  2437. InstsInThisBlock.clear();
  2438. // Ensure that basic blocks have terminators!
  2439. Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
  2440. // Check constraints that this basic block imposes on all of the PHI nodes in
  2441. // it.
  2442. if (isa<PHINode>(BB.front())) {
  2443. SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
  2444. SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
  2445. llvm::sort(Preds);
  2446. for (const PHINode &PN : BB.phis()) {
  2447. Check(PN.getNumIncomingValues() == Preds.size(),
  2448. "PHINode should have one entry for each predecessor of its "
  2449. "parent basic block!",
  2450. &PN);
  2451. // Get and sort all incoming values in the PHI node...
  2452. Values.clear();
  2453. Values.reserve(PN.getNumIncomingValues());
  2454. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
  2455. Values.push_back(
  2456. std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
  2457. llvm::sort(Values);
  2458. for (unsigned i = 0, e = Values.size(); i != e; ++i) {
  2459. // Check to make sure that if there is more than one entry for a
  2460. // particular basic block in this PHI node, that the incoming values are
  2461. // all identical.
  2462. //
  2463. Check(i == 0 || Values[i].first != Values[i - 1].first ||
  2464. Values[i].second == Values[i - 1].second,
  2465. "PHI node has multiple entries for the same basic block with "
  2466. "different incoming values!",
  2467. &PN, Values[i].first, Values[i].second, Values[i - 1].second);
  2468. // Check to make sure that the predecessors and PHI node entries are
  2469. // matched up.
  2470. Check(Values[i].first == Preds[i],
  2471. "PHI node entries do not match predecessors!", &PN,
  2472. Values[i].first, Preds[i]);
  2473. }
  2474. }
  2475. }
  2476. // Check that all instructions have their parent pointers set up correctly.
  2477. for (auto &I : BB)
  2478. {
  2479. Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
  2480. }
  2481. }
  2482. void Verifier::visitTerminator(Instruction &I) {
  2483. // Ensure that terminators only exist at the end of the basic block.
  2484. Check(&I == I.getParent()->getTerminator(),
  2485. "Terminator found in the middle of a basic block!", I.getParent());
  2486. visitInstruction(I);
  2487. }
  2488. void Verifier::visitBranchInst(BranchInst &BI) {
  2489. if (BI.isConditional()) {
  2490. Check(BI.getCondition()->getType()->isIntegerTy(1),
  2491. "Branch condition is not 'i1' type!", &BI, BI.getCondition());
  2492. }
  2493. visitTerminator(BI);
  2494. }
  2495. void Verifier::visitReturnInst(ReturnInst &RI) {
  2496. Function *F = RI.getParent()->getParent();
  2497. unsigned N = RI.getNumOperands();
  2498. if (F->getReturnType()->isVoidTy())
  2499. Check(N == 0,
  2500. "Found return instr that returns non-void in Function of void "
  2501. "return type!",
  2502. &RI, F->getReturnType());
  2503. else
  2504. Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
  2505. "Function return type does not match operand "
  2506. "type of return inst!",
  2507. &RI, F->getReturnType());
  2508. // Check to make sure that the return value has necessary properties for
  2509. // terminators...
  2510. visitTerminator(RI);
  2511. }
  2512. void Verifier::visitSwitchInst(SwitchInst &SI) {
  2513. Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
  2514. // Check to make sure that all of the constants in the switch instruction
  2515. // have the same type as the switched-on value.
  2516. Type *SwitchTy = SI.getCondition()->getType();
  2517. SmallPtrSet<ConstantInt*, 32> Constants;
  2518. for (auto &Case : SI.cases()) {
  2519. Check(isa<ConstantInt>(SI.getOperand(Case.getCaseIndex() * 2 + 2)),
  2520. "Case value is not a constant integer.", &SI);
  2521. Check(Case.getCaseValue()->getType() == SwitchTy,
  2522. "Switch constants must all be same type as switch value!", &SI);
  2523. Check(Constants.insert(Case.getCaseValue()).second,
  2524. "Duplicate integer as switch case", &SI, Case.getCaseValue());
  2525. }
  2526. visitTerminator(SI);
  2527. }
  2528. void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
  2529. Check(BI.getAddress()->getType()->isPointerTy(),
  2530. "Indirectbr operand must have pointer type!", &BI);
  2531. for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
  2532. Check(BI.getDestination(i)->getType()->isLabelTy(),
  2533. "Indirectbr destinations must all have pointer type!", &BI);
  2534. visitTerminator(BI);
  2535. }
  2536. void Verifier::visitCallBrInst(CallBrInst &CBI) {
  2537. Check(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", &CBI);
  2538. const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
  2539. Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
  2540. verifyInlineAsmCall(CBI);
  2541. visitTerminator(CBI);
  2542. }
  2543. void Verifier::visitSelectInst(SelectInst &SI) {
  2544. Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
  2545. SI.getOperand(2)),
  2546. "Invalid operands for select instruction!", &SI);
  2547. Check(SI.getTrueValue()->getType() == SI.getType(),
  2548. "Select values must have same type as select instruction!", &SI);
  2549. visitInstruction(SI);
  2550. }
  2551. /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
  2552. /// a pass, if any exist, it's an error.
  2553. ///
  2554. void Verifier::visitUserOp1(Instruction &I) {
  2555. Check(false, "User-defined operators should not live outside of a pass!", &I);
  2556. }
  2557. void Verifier::visitTruncInst(TruncInst &I) {
  2558. // Get the source and destination types
  2559. Type *SrcTy = I.getOperand(0)->getType();
  2560. Type *DestTy = I.getType();
  2561. // Get the size of the types in bits, we'll need this later
  2562. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2563. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2564. Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
  2565. Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
  2566. Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2567. "trunc source and destination must both be a vector or neither", &I);
  2568. Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
  2569. visitInstruction(I);
  2570. }
  2571. void Verifier::visitZExtInst(ZExtInst &I) {
  2572. // Get the source and destination types
  2573. Type *SrcTy = I.getOperand(0)->getType();
  2574. Type *DestTy = I.getType();
  2575. // Get the size of the types in bits, we'll need this later
  2576. Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
  2577. Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
  2578. Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2579. "zext source and destination must both be a vector or neither", &I);
  2580. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2581. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2582. Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
  2583. visitInstruction(I);
  2584. }
  2585. void Verifier::visitSExtInst(SExtInst &I) {
  2586. // Get the source and destination types
  2587. Type *SrcTy = I.getOperand(0)->getType();
  2588. Type *DestTy = I.getType();
  2589. // Get the size of the types in bits, we'll need this later
  2590. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2591. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2592. Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
  2593. Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
  2594. Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2595. "sext source and destination must both be a vector or neither", &I);
  2596. Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
  2597. visitInstruction(I);
  2598. }
  2599. void Verifier::visitFPTruncInst(FPTruncInst &I) {
  2600. // Get the source and destination types
  2601. Type *SrcTy = I.getOperand(0)->getType();
  2602. Type *DestTy = I.getType();
  2603. // Get the size of the types in bits, we'll need this later
  2604. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2605. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2606. Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
  2607. Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
  2608. Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2609. "fptrunc source and destination must both be a vector or neither", &I);
  2610. Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
  2611. visitInstruction(I);
  2612. }
  2613. void Verifier::visitFPExtInst(FPExtInst &I) {
  2614. // Get the source and destination types
  2615. Type *SrcTy = I.getOperand(0)->getType();
  2616. Type *DestTy = I.getType();
  2617. // Get the size of the types in bits, we'll need this later
  2618. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2619. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2620. Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
  2621. Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
  2622. Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2623. "fpext source and destination must both be a vector or neither", &I);
  2624. Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
  2625. visitInstruction(I);
  2626. }
  2627. void Verifier::visitUIToFPInst(UIToFPInst &I) {
  2628. // Get the source and destination types
  2629. Type *SrcTy = I.getOperand(0)->getType();
  2630. Type *DestTy = I.getType();
  2631. bool SrcVec = SrcTy->isVectorTy();
  2632. bool DstVec = DestTy->isVectorTy();
  2633. Check(SrcVec == DstVec,
  2634. "UIToFP source and dest must both be vector or scalar", &I);
  2635. Check(SrcTy->isIntOrIntVectorTy(),
  2636. "UIToFP source must be integer or integer vector", &I);
  2637. Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
  2638. &I);
  2639. if (SrcVec && DstVec)
  2640. Check(cast<VectorType>(SrcTy)->getElementCount() ==
  2641. cast<VectorType>(DestTy)->getElementCount(),
  2642. "UIToFP source and dest vector length mismatch", &I);
  2643. visitInstruction(I);
  2644. }
  2645. void Verifier::visitSIToFPInst(SIToFPInst &I) {
  2646. // Get the source and destination types
  2647. Type *SrcTy = I.getOperand(0)->getType();
  2648. Type *DestTy = I.getType();
  2649. bool SrcVec = SrcTy->isVectorTy();
  2650. bool DstVec = DestTy->isVectorTy();
  2651. Check(SrcVec == DstVec,
  2652. "SIToFP source and dest must both be vector or scalar", &I);
  2653. Check(SrcTy->isIntOrIntVectorTy(),
  2654. "SIToFP source must be integer or integer vector", &I);
  2655. Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
  2656. &I);
  2657. if (SrcVec && DstVec)
  2658. Check(cast<VectorType>(SrcTy)->getElementCount() ==
  2659. cast<VectorType>(DestTy)->getElementCount(),
  2660. "SIToFP source and dest vector length mismatch", &I);
  2661. visitInstruction(I);
  2662. }
  2663. void Verifier::visitFPToUIInst(FPToUIInst &I) {
  2664. // Get the source and destination types
  2665. Type *SrcTy = I.getOperand(0)->getType();
  2666. Type *DestTy = I.getType();
  2667. bool SrcVec = SrcTy->isVectorTy();
  2668. bool DstVec = DestTy->isVectorTy();
  2669. Check(SrcVec == DstVec,
  2670. "FPToUI source and dest must both be vector or scalar", &I);
  2671. Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
  2672. Check(DestTy->isIntOrIntVectorTy(),
  2673. "FPToUI result must be integer or integer vector", &I);
  2674. if (SrcVec && DstVec)
  2675. Check(cast<VectorType>(SrcTy)->getElementCount() ==
  2676. cast<VectorType>(DestTy)->getElementCount(),
  2677. "FPToUI source and dest vector length mismatch", &I);
  2678. visitInstruction(I);
  2679. }
  2680. void Verifier::visitFPToSIInst(FPToSIInst &I) {
  2681. // Get the source and destination types
  2682. Type *SrcTy = I.getOperand(0)->getType();
  2683. Type *DestTy = I.getType();
  2684. bool SrcVec = SrcTy->isVectorTy();
  2685. bool DstVec = DestTy->isVectorTy();
  2686. Check(SrcVec == DstVec,
  2687. "FPToSI source and dest must both be vector or scalar", &I);
  2688. Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
  2689. Check(DestTy->isIntOrIntVectorTy(),
  2690. "FPToSI result must be integer or integer vector", &I);
  2691. if (SrcVec && DstVec)
  2692. Check(cast<VectorType>(SrcTy)->getElementCount() ==
  2693. cast<VectorType>(DestTy)->getElementCount(),
  2694. "FPToSI source and dest vector length mismatch", &I);
  2695. visitInstruction(I);
  2696. }
  2697. void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
  2698. // Get the source and destination types
  2699. Type *SrcTy = I.getOperand(0)->getType();
  2700. Type *DestTy = I.getType();
  2701. Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
  2702. Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
  2703. Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
  2704. &I);
  2705. if (SrcTy->isVectorTy()) {
  2706. auto *VSrc = cast<VectorType>(SrcTy);
  2707. auto *VDest = cast<VectorType>(DestTy);
  2708. Check(VSrc->getElementCount() == VDest->getElementCount(),
  2709. "PtrToInt Vector width mismatch", &I);
  2710. }
  2711. visitInstruction(I);
  2712. }
  2713. void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
  2714. // Get the source and destination types
  2715. Type *SrcTy = I.getOperand(0)->getType();
  2716. Type *DestTy = I.getType();
  2717. Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
  2718. Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
  2719. Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
  2720. &I);
  2721. if (SrcTy->isVectorTy()) {
  2722. auto *VSrc = cast<VectorType>(SrcTy);
  2723. auto *VDest = cast<VectorType>(DestTy);
  2724. Check(VSrc->getElementCount() == VDest->getElementCount(),
  2725. "IntToPtr Vector width mismatch", &I);
  2726. }
  2727. visitInstruction(I);
  2728. }
  2729. void Verifier::visitBitCastInst(BitCastInst &I) {
  2730. Check(
  2731. CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
  2732. "Invalid bitcast", &I);
  2733. visitInstruction(I);
  2734. }
  2735. void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
  2736. Type *SrcTy = I.getOperand(0)->getType();
  2737. Type *DestTy = I.getType();
  2738. Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
  2739. &I);
  2740. Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
  2741. &I);
  2742. Check(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
  2743. "AddrSpaceCast must be between different address spaces", &I);
  2744. if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
  2745. Check(SrcVTy->getElementCount() ==
  2746. cast<VectorType>(DestTy)->getElementCount(),
  2747. "AddrSpaceCast vector pointer number of elements mismatch", &I);
  2748. visitInstruction(I);
  2749. }
  2750. /// visitPHINode - Ensure that a PHI node is well formed.
  2751. ///
  2752. void Verifier::visitPHINode(PHINode &PN) {
  2753. // Ensure that the PHI nodes are all grouped together at the top of the block.
  2754. // This can be tested by checking whether the instruction before this is
  2755. // either nonexistent (because this is begin()) or is a PHI node. If not,
  2756. // then there is some other instruction before a PHI.
  2757. Check(&PN == &PN.getParent()->front() ||
  2758. isa<PHINode>(--BasicBlock::iterator(&PN)),
  2759. "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
  2760. // Check that a PHI doesn't yield a Token.
  2761. Check(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
  2762. // Check that all of the values of the PHI node have the same type as the
  2763. // result, and that the incoming blocks are really basic blocks.
  2764. for (Value *IncValue : PN.incoming_values()) {
  2765. Check(PN.getType() == IncValue->getType(),
  2766. "PHI node operands are not the same type as the result!", &PN);
  2767. }
  2768. // All other PHI node constraints are checked in the visitBasicBlock method.
  2769. visitInstruction(PN);
  2770. }
  2771. void Verifier::visitCallBase(CallBase &Call) {
  2772. Check(Call.getCalledOperand()->getType()->isPointerTy(),
  2773. "Called function must be a pointer!", Call);
  2774. PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType());
  2775. Check(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType()),
  2776. "Called function is not the same type as the call!", Call);
  2777. FunctionType *FTy = Call.getFunctionType();
  2778. // Verify that the correct number of arguments are being passed
  2779. if (FTy->isVarArg())
  2780. Check(Call.arg_size() >= FTy->getNumParams(),
  2781. "Called function requires more parameters than were provided!", Call);
  2782. else
  2783. Check(Call.arg_size() == FTy->getNumParams(),
  2784. "Incorrect number of arguments passed to called function!", Call);
  2785. // Verify that all arguments to the call match the function type.
  2786. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  2787. Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
  2788. "Call parameter type does not match function signature!",
  2789. Call.getArgOperand(i), FTy->getParamType(i), Call);
  2790. AttributeList Attrs = Call.getAttributes();
  2791. Check(verifyAttributeCount(Attrs, Call.arg_size()),
  2792. "Attribute after last parameter!", Call);
  2793. Function *Callee =
  2794. dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
  2795. bool IsIntrinsic = Callee && Callee->isIntrinsic();
  2796. if (IsIntrinsic)
  2797. Check(Callee->getValueType() == FTy,
  2798. "Intrinsic called with incompatible signature", Call);
  2799. auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
  2800. if (!Ty->isSized())
  2801. return;
  2802. Align ABIAlign = DL.getABITypeAlign(Ty);
  2803. Align MaxAlign(ParamMaxAlignment);
  2804. Check(ABIAlign <= MaxAlign,
  2805. "Incorrect alignment of " + Message + " to called function!", Call);
  2806. };
  2807. if (!IsIntrinsic) {
  2808. VerifyTypeAlign(FTy->getReturnType(), "return type");
  2809. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
  2810. Type *Ty = FTy->getParamType(i);
  2811. VerifyTypeAlign(Ty, "argument passed");
  2812. }
  2813. }
  2814. if (Attrs.hasFnAttr(Attribute::Speculatable)) {
  2815. // Don't allow speculatable on call sites, unless the underlying function
  2816. // declaration is also speculatable.
  2817. Check(Callee && Callee->isSpeculatable(),
  2818. "speculatable attribute may not apply to call sites", Call);
  2819. }
  2820. if (Attrs.hasFnAttr(Attribute::Preallocated)) {
  2821. Check(Call.getCalledFunction()->getIntrinsicID() ==
  2822. Intrinsic::call_preallocated_arg,
  2823. "preallocated as a call site attribute can only be on "
  2824. "llvm.call.preallocated.arg");
  2825. }
  2826. // Verify call attributes.
  2827. verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
  2828. // Conservatively check the inalloca argument.
  2829. // We have a bug if we can find that there is an underlying alloca without
  2830. // inalloca.
  2831. if (Call.hasInAllocaArgument()) {
  2832. Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
  2833. if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
  2834. Check(AI->isUsedWithInAlloca(),
  2835. "inalloca argument for call has mismatched alloca", AI, Call);
  2836. }
  2837. // For each argument of the callsite, if it has the swifterror argument,
  2838. // make sure the underlying alloca/parameter it comes from has a swifterror as
  2839. // well.
  2840. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
  2841. if (Call.paramHasAttr(i, Attribute::SwiftError)) {
  2842. Value *SwiftErrorArg = Call.getArgOperand(i);
  2843. if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
  2844. Check(AI->isSwiftError(),
  2845. "swifterror argument for call has mismatched alloca", AI, Call);
  2846. continue;
  2847. }
  2848. auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
  2849. Check(ArgI, "swifterror argument should come from an alloca or parameter",
  2850. SwiftErrorArg, Call);
  2851. Check(ArgI->hasSwiftErrorAttr(),
  2852. "swifterror argument for call has mismatched parameter", ArgI,
  2853. Call);
  2854. }
  2855. if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
  2856. // Don't allow immarg on call sites, unless the underlying declaration
  2857. // also has the matching immarg.
  2858. Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
  2859. "immarg may not apply only to call sites", Call.getArgOperand(i),
  2860. Call);
  2861. }
  2862. if (Call.paramHasAttr(i, Attribute::ImmArg)) {
  2863. Value *ArgVal = Call.getArgOperand(i);
  2864. Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
  2865. "immarg operand has non-immediate parameter", ArgVal, Call);
  2866. }
  2867. if (Call.paramHasAttr(i, Attribute::Preallocated)) {
  2868. Value *ArgVal = Call.getArgOperand(i);
  2869. bool hasOB =
  2870. Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
  2871. bool isMustTail = Call.isMustTailCall();
  2872. Check(hasOB != isMustTail,
  2873. "preallocated operand either requires a preallocated bundle or "
  2874. "the call to be musttail (but not both)",
  2875. ArgVal, Call);
  2876. }
  2877. }
  2878. if (FTy->isVarArg()) {
  2879. // FIXME? is 'nest' even legal here?
  2880. bool SawNest = false;
  2881. bool SawReturned = false;
  2882. for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
  2883. if (Attrs.hasParamAttr(Idx, Attribute::Nest))
  2884. SawNest = true;
  2885. if (Attrs.hasParamAttr(Idx, Attribute::Returned))
  2886. SawReturned = true;
  2887. }
  2888. // Check attributes on the varargs part.
  2889. for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
  2890. Type *Ty = Call.getArgOperand(Idx)->getType();
  2891. AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
  2892. verifyParameterAttrs(ArgAttrs, Ty, &Call);
  2893. if (ArgAttrs.hasAttribute(Attribute::Nest)) {
  2894. Check(!SawNest, "More than one parameter has attribute nest!", Call);
  2895. SawNest = true;
  2896. }
  2897. if (ArgAttrs.hasAttribute(Attribute::Returned)) {
  2898. Check(!SawReturned, "More than one parameter has attribute returned!",
  2899. Call);
  2900. Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
  2901. "Incompatible argument and return types for 'returned' "
  2902. "attribute",
  2903. Call);
  2904. SawReturned = true;
  2905. }
  2906. // Statepoint intrinsic is vararg but the wrapped function may be not.
  2907. // Allow sret here and check the wrapped function in verifyStatepoint.
  2908. if (!Call.getCalledFunction() ||
  2909. Call.getCalledFunction()->getIntrinsicID() !=
  2910. Intrinsic::experimental_gc_statepoint)
  2911. Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
  2912. "Attribute 'sret' cannot be used for vararg call arguments!",
  2913. Call);
  2914. if (ArgAttrs.hasAttribute(Attribute::InAlloca))
  2915. Check(Idx == Call.arg_size() - 1,
  2916. "inalloca isn't on the last argument!", Call);
  2917. }
  2918. }
  2919. // Verify that there's no metadata unless it's a direct call to an intrinsic.
  2920. if (!IsIntrinsic) {
  2921. for (Type *ParamTy : FTy->params()) {
  2922. Check(!ParamTy->isMetadataTy(),
  2923. "Function has metadata parameter but isn't an intrinsic", Call);
  2924. Check(!ParamTy->isTokenTy(),
  2925. "Function has token parameter but isn't an intrinsic", Call);
  2926. }
  2927. }
  2928. // Verify that indirect calls don't return tokens.
  2929. if (!Call.getCalledFunction()) {
  2930. Check(!FTy->getReturnType()->isTokenTy(),
  2931. "Return type cannot be token for indirect call!");
  2932. Check(!FTy->getReturnType()->isX86_AMXTy(),
  2933. "Return type cannot be x86_amx for indirect call!");
  2934. }
  2935. if (Function *F = Call.getCalledFunction())
  2936. if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
  2937. visitIntrinsicCall(ID, Call);
  2938. // Verify that a callsite has at most one "deopt", at most one "funclet", at
  2939. // most one "gc-transition", at most one "cfguardtarget", at most one
  2940. // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
  2941. bool FoundDeoptBundle = false, FoundFuncletBundle = false,
  2942. FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
  2943. FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
  2944. FoundPtrauthBundle = false, FoundKCFIBundle = false,
  2945. FoundAttachedCallBundle = false;
  2946. for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
  2947. OperandBundleUse BU = Call.getOperandBundleAt(i);
  2948. uint32_t Tag = BU.getTagID();
  2949. if (Tag == LLVMContext::OB_deopt) {
  2950. Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
  2951. FoundDeoptBundle = true;
  2952. } else if (Tag == LLVMContext::OB_gc_transition) {
  2953. Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
  2954. Call);
  2955. FoundGCTransitionBundle = true;
  2956. } else if (Tag == LLVMContext::OB_funclet) {
  2957. Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
  2958. FoundFuncletBundle = true;
  2959. Check(BU.Inputs.size() == 1,
  2960. "Expected exactly one funclet bundle operand", Call);
  2961. Check(isa<FuncletPadInst>(BU.Inputs.front()),
  2962. "Funclet bundle operands should correspond to a FuncletPadInst",
  2963. Call);
  2964. } else if (Tag == LLVMContext::OB_cfguardtarget) {
  2965. Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
  2966. Call);
  2967. FoundCFGuardTargetBundle = true;
  2968. Check(BU.Inputs.size() == 1,
  2969. "Expected exactly one cfguardtarget bundle operand", Call);
  2970. } else if (Tag == LLVMContext::OB_ptrauth) {
  2971. Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
  2972. FoundPtrauthBundle = true;
  2973. Check(BU.Inputs.size() == 2,
  2974. "Expected exactly two ptrauth bundle operands", Call);
  2975. Check(isa<ConstantInt>(BU.Inputs[0]) &&
  2976. BU.Inputs[0]->getType()->isIntegerTy(32),
  2977. "Ptrauth bundle key operand must be an i32 constant", Call);
  2978. Check(BU.Inputs[1]->getType()->isIntegerTy(64),
  2979. "Ptrauth bundle discriminator operand must be an i64", Call);
  2980. } else if (Tag == LLVMContext::OB_kcfi) {
  2981. Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
  2982. FoundKCFIBundle = true;
  2983. Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
  2984. Call);
  2985. Check(isa<ConstantInt>(BU.Inputs[0]) &&
  2986. BU.Inputs[0]->getType()->isIntegerTy(32),
  2987. "Kcfi bundle operand must be an i32 constant", Call);
  2988. } else if (Tag == LLVMContext::OB_preallocated) {
  2989. Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
  2990. Call);
  2991. FoundPreallocatedBundle = true;
  2992. Check(BU.Inputs.size() == 1,
  2993. "Expected exactly one preallocated bundle operand", Call);
  2994. auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
  2995. Check(Input &&
  2996. Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
  2997. "\"preallocated\" argument must be a token from "
  2998. "llvm.call.preallocated.setup",
  2999. Call);
  3000. } else if (Tag == LLVMContext::OB_gc_live) {
  3001. Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
  3002. FoundGCLiveBundle = true;
  3003. } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
  3004. Check(!FoundAttachedCallBundle,
  3005. "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
  3006. FoundAttachedCallBundle = true;
  3007. verifyAttachedCallBundle(Call, BU);
  3008. }
  3009. }
  3010. // Verify that callee and callsite agree on whether to use pointer auth.
  3011. Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
  3012. "Direct call cannot have a ptrauth bundle", Call);
  3013. // Verify that each inlinable callsite of a debug-info-bearing function in a
  3014. // debug-info-bearing function has a debug location attached to it. Failure to
  3015. // do so causes assertion failures when the inliner sets up inline scope info
  3016. // (Interposable functions are not inlinable, neither are functions without
  3017. // definitions.)
  3018. if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
  3019. !Call.getCalledFunction()->isInterposable() &&
  3020. !Call.getCalledFunction()->isDeclaration() &&
  3021. Call.getCalledFunction()->getSubprogram())
  3022. CheckDI(Call.getDebugLoc(),
  3023. "inlinable function call in a function with "
  3024. "debug info must have a !dbg location",
  3025. Call);
  3026. if (Call.isInlineAsm())
  3027. verifyInlineAsmCall(Call);
  3028. visitInstruction(Call);
  3029. }
  3030. void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
  3031. StringRef Context) {
  3032. Check(!Attrs.contains(Attribute::InAlloca),
  3033. Twine("inalloca attribute not allowed in ") + Context);
  3034. Check(!Attrs.contains(Attribute::InReg),
  3035. Twine("inreg attribute not allowed in ") + Context);
  3036. Check(!Attrs.contains(Attribute::SwiftError),
  3037. Twine("swifterror attribute not allowed in ") + Context);
  3038. Check(!Attrs.contains(Attribute::Preallocated),
  3039. Twine("preallocated attribute not allowed in ") + Context);
  3040. Check(!Attrs.contains(Attribute::ByRef),
  3041. Twine("byref attribute not allowed in ") + Context);
  3042. }
  3043. /// Two types are "congruent" if they are identical, or if they are both pointer
  3044. /// types with different pointee types and the same address space.
  3045. static bool isTypeCongruent(Type *L, Type *R) {
  3046. if (L == R)
  3047. return true;
  3048. PointerType *PL = dyn_cast<PointerType>(L);
  3049. PointerType *PR = dyn_cast<PointerType>(R);
  3050. if (!PL || !PR)
  3051. return false;
  3052. return PL->getAddressSpace() == PR->getAddressSpace();
  3053. }
  3054. static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
  3055. static const Attribute::AttrKind ABIAttrs[] = {
  3056. Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
  3057. Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
  3058. Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
  3059. Attribute::ByRef};
  3060. AttrBuilder Copy(C);
  3061. for (auto AK : ABIAttrs) {
  3062. Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
  3063. if (Attr.isValid())
  3064. Copy.addAttribute(Attr);
  3065. }
  3066. // `align` is ABI-affecting only in combination with `byval` or `byref`.
  3067. if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
  3068. (Attrs.hasParamAttr(I, Attribute::ByVal) ||
  3069. Attrs.hasParamAttr(I, Attribute::ByRef)))
  3070. Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
  3071. return Copy;
  3072. }
  3073. void Verifier::verifyMustTailCall(CallInst &CI) {
  3074. Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
  3075. Function *F = CI.getParent()->getParent();
  3076. FunctionType *CallerTy = F->getFunctionType();
  3077. FunctionType *CalleeTy = CI.getFunctionType();
  3078. Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
  3079. "cannot guarantee tail call due to mismatched varargs", &CI);
  3080. Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
  3081. "cannot guarantee tail call due to mismatched return types", &CI);
  3082. // - The calling conventions of the caller and callee must match.
  3083. Check(F->getCallingConv() == CI.getCallingConv(),
  3084. "cannot guarantee tail call due to mismatched calling conv", &CI);
  3085. // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
  3086. // or a pointer bitcast followed by a ret instruction.
  3087. // - The ret instruction must return the (possibly bitcasted) value
  3088. // produced by the call or void.
  3089. Value *RetVal = &CI;
  3090. Instruction *Next = CI.getNextNode();
  3091. // Handle the optional bitcast.
  3092. if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
  3093. Check(BI->getOperand(0) == RetVal,
  3094. "bitcast following musttail call must use the call", BI);
  3095. RetVal = BI;
  3096. Next = BI->getNextNode();
  3097. }
  3098. // Check the return.
  3099. ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
  3100. Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
  3101. Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
  3102. isa<UndefValue>(Ret->getReturnValue()),
  3103. "musttail call result must be returned", Ret);
  3104. AttributeList CallerAttrs = F->getAttributes();
  3105. AttributeList CalleeAttrs = CI.getAttributes();
  3106. if (CI.getCallingConv() == CallingConv::SwiftTail ||
  3107. CI.getCallingConv() == CallingConv::Tail) {
  3108. StringRef CCName =
  3109. CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
  3110. // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
  3111. // are allowed in swifttailcc call
  3112. for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
  3113. AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
  3114. SmallString<32> Context{CCName, StringRef(" musttail caller")};
  3115. verifyTailCCMustTailAttrs(ABIAttrs, Context);
  3116. }
  3117. for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
  3118. AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
  3119. SmallString<32> Context{CCName, StringRef(" musttail callee")};
  3120. verifyTailCCMustTailAttrs(ABIAttrs, Context);
  3121. }
  3122. // - Varargs functions are not allowed
  3123. Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
  3124. " tail call for varargs function");
  3125. return;
  3126. }
  3127. // - The caller and callee prototypes must match. Pointer types of
  3128. // parameters or return types may differ in pointee type, but not
  3129. // address space.
  3130. if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
  3131. Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
  3132. "cannot guarantee tail call due to mismatched parameter counts", &CI);
  3133. for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
  3134. Check(
  3135. isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
  3136. "cannot guarantee tail call due to mismatched parameter types", &CI);
  3137. }
  3138. }
  3139. // - All ABI-impacting function attributes, such as sret, byval, inreg,
  3140. // returned, preallocated, and inalloca, must match.
  3141. for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
  3142. AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
  3143. AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
  3144. Check(CallerABIAttrs == CalleeABIAttrs,
  3145. "cannot guarantee tail call due to mismatched ABI impacting "
  3146. "function attributes",
  3147. &CI, CI.getOperand(I));
  3148. }
  3149. }
  3150. void Verifier::visitCallInst(CallInst &CI) {
  3151. visitCallBase(CI);
  3152. if (CI.isMustTailCall())
  3153. verifyMustTailCall(CI);
  3154. }
  3155. void Verifier::visitInvokeInst(InvokeInst &II) {
  3156. visitCallBase(II);
  3157. // Verify that the first non-PHI instruction of the unwind destination is an
  3158. // exception handling instruction.
  3159. Check(
  3160. II.getUnwindDest()->isEHPad(),
  3161. "The unwind destination does not have an exception handling instruction!",
  3162. &II);
  3163. visitTerminator(II);
  3164. }
  3165. /// visitUnaryOperator - Check the argument to the unary operator.
  3166. ///
  3167. void Verifier::visitUnaryOperator(UnaryOperator &U) {
  3168. Check(U.getType() == U.getOperand(0)->getType(),
  3169. "Unary operators must have same type for"
  3170. "operands and result!",
  3171. &U);
  3172. switch (U.getOpcode()) {
  3173. // Check that floating-point arithmetic operators are only used with
  3174. // floating-point operands.
  3175. case Instruction::FNeg:
  3176. Check(U.getType()->isFPOrFPVectorTy(),
  3177. "FNeg operator only works with float types!", &U);
  3178. break;
  3179. default:
  3180. llvm_unreachable("Unknown UnaryOperator opcode!");
  3181. }
  3182. visitInstruction(U);
  3183. }
  3184. /// visitBinaryOperator - Check that both arguments to the binary operator are
  3185. /// of the same type!
  3186. ///
  3187. void Verifier::visitBinaryOperator(BinaryOperator &B) {
  3188. Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
  3189. "Both operands to a binary operator are not of the same type!", &B);
  3190. switch (B.getOpcode()) {
  3191. // Check that integer arithmetic operators are only used with
  3192. // integral operands.
  3193. case Instruction::Add:
  3194. case Instruction::Sub:
  3195. case Instruction::Mul:
  3196. case Instruction::SDiv:
  3197. case Instruction::UDiv:
  3198. case Instruction::SRem:
  3199. case Instruction::URem:
  3200. Check(B.getType()->isIntOrIntVectorTy(),
  3201. "Integer arithmetic operators only work with integral types!", &B);
  3202. Check(B.getType() == B.getOperand(0)->getType(),
  3203. "Integer arithmetic operators must have same type "
  3204. "for operands and result!",
  3205. &B);
  3206. break;
  3207. // Check that floating-point arithmetic operators are only used with
  3208. // floating-point operands.
  3209. case Instruction::FAdd:
  3210. case Instruction::FSub:
  3211. case Instruction::FMul:
  3212. case Instruction::FDiv:
  3213. case Instruction::FRem:
  3214. Check(B.getType()->isFPOrFPVectorTy(),
  3215. "Floating-point arithmetic operators only work with "
  3216. "floating-point types!",
  3217. &B);
  3218. Check(B.getType() == B.getOperand(0)->getType(),
  3219. "Floating-point arithmetic operators must have same type "
  3220. "for operands and result!",
  3221. &B);
  3222. break;
  3223. // Check that logical operators are only used with integral operands.
  3224. case Instruction::And:
  3225. case Instruction::Or:
  3226. case Instruction::Xor:
  3227. Check(B.getType()->isIntOrIntVectorTy(),
  3228. "Logical operators only work with integral types!", &B);
  3229. Check(B.getType() == B.getOperand(0)->getType(),
  3230. "Logical operators must have same type for operands and result!", &B);
  3231. break;
  3232. case Instruction::Shl:
  3233. case Instruction::LShr:
  3234. case Instruction::AShr:
  3235. Check(B.getType()->isIntOrIntVectorTy(),
  3236. "Shifts only work with integral types!", &B);
  3237. Check(B.getType() == B.getOperand(0)->getType(),
  3238. "Shift return type must be same as operands!", &B);
  3239. break;
  3240. default:
  3241. llvm_unreachable("Unknown BinaryOperator opcode!");
  3242. }
  3243. visitInstruction(B);
  3244. }
  3245. void Verifier::visitICmpInst(ICmpInst &IC) {
  3246. // Check that the operands are the same type
  3247. Type *Op0Ty = IC.getOperand(0)->getType();
  3248. Type *Op1Ty = IC.getOperand(1)->getType();
  3249. Check(Op0Ty == Op1Ty,
  3250. "Both operands to ICmp instruction are not of the same type!", &IC);
  3251. // Check that the operands are the right type
  3252. Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
  3253. "Invalid operand types for ICmp instruction", &IC);
  3254. // Check that the predicate is valid.
  3255. Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
  3256. visitInstruction(IC);
  3257. }
  3258. void Verifier::visitFCmpInst(FCmpInst &FC) {
  3259. // Check that the operands are the same type
  3260. Type *Op0Ty = FC.getOperand(0)->getType();
  3261. Type *Op1Ty = FC.getOperand(1)->getType();
  3262. Check(Op0Ty == Op1Ty,
  3263. "Both operands to FCmp instruction are not of the same type!", &FC);
  3264. // Check that the operands are the right type
  3265. Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
  3266. &FC);
  3267. // Check that the predicate is valid.
  3268. Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
  3269. visitInstruction(FC);
  3270. }
  3271. void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
  3272. Check(ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
  3273. "Invalid extractelement operands!", &EI);
  3274. visitInstruction(EI);
  3275. }
  3276. void Verifier::visitInsertElementInst(InsertElementInst &IE) {
  3277. Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
  3278. IE.getOperand(2)),
  3279. "Invalid insertelement operands!", &IE);
  3280. visitInstruction(IE);
  3281. }
  3282. void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
  3283. Check(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
  3284. SV.getShuffleMask()),
  3285. "Invalid shufflevector operands!", &SV);
  3286. visitInstruction(SV);
  3287. }
  3288. void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
  3289. Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
  3290. Check(isa<PointerType>(TargetTy),
  3291. "GEP base pointer is not a vector or a vector of pointers", &GEP);
  3292. Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
  3293. SmallVector<Value *, 16> Idxs(GEP.indices());
  3294. Check(
  3295. all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
  3296. "GEP indexes must be integers", &GEP);
  3297. Type *ElTy =
  3298. GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
  3299. Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
  3300. Check(GEP.getType()->isPtrOrPtrVectorTy() &&
  3301. GEP.getResultElementType() == ElTy,
  3302. "GEP is not of right type for indices!", &GEP, ElTy);
  3303. if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
  3304. // Additional checks for vector GEPs.
  3305. ElementCount GEPWidth = GEPVTy->getElementCount();
  3306. if (GEP.getPointerOperandType()->isVectorTy())
  3307. Check(
  3308. GEPWidth ==
  3309. cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
  3310. "Vector GEP result width doesn't match operand's", &GEP);
  3311. for (Value *Idx : Idxs) {
  3312. Type *IndexTy = Idx->getType();
  3313. if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
  3314. ElementCount IndexWidth = IndexVTy->getElementCount();
  3315. Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
  3316. }
  3317. Check(IndexTy->isIntOrIntVectorTy(),
  3318. "All GEP indices should be of integer type");
  3319. }
  3320. }
  3321. if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
  3322. Check(GEP.getAddressSpace() == PTy->getAddressSpace(),
  3323. "GEP address space doesn't match type", &GEP);
  3324. }
  3325. visitInstruction(GEP);
  3326. }
  3327. static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
  3328. return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
  3329. }
  3330. void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
  3331. assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
  3332. "precondition violation");
  3333. unsigned NumOperands = Range->getNumOperands();
  3334. Check(NumOperands % 2 == 0, "Unfinished range!", Range);
  3335. unsigned NumRanges = NumOperands / 2;
  3336. Check(NumRanges >= 1, "It should have at least one range!", Range);
  3337. ConstantRange LastRange(1, true); // Dummy initial value
  3338. for (unsigned i = 0; i < NumRanges; ++i) {
  3339. ConstantInt *Low =
  3340. mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
  3341. Check(Low, "The lower limit must be an integer!", Low);
  3342. ConstantInt *High =
  3343. mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
  3344. Check(High, "The upper limit must be an integer!", High);
  3345. Check(High->getType() == Low->getType() && High->getType() == Ty,
  3346. "Range types must match instruction type!", &I);
  3347. APInt HighV = High->getValue();
  3348. APInt LowV = Low->getValue();
  3349. ConstantRange CurRange(LowV, HighV);
  3350. Check(!CurRange.isEmptySet() && !CurRange.isFullSet(),
  3351. "Range must not be empty!", Range);
  3352. if (i != 0) {
  3353. Check(CurRange.intersectWith(LastRange).isEmptySet(),
  3354. "Intervals are overlapping", Range);
  3355. Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
  3356. Range);
  3357. Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
  3358. Range);
  3359. }
  3360. LastRange = ConstantRange(LowV, HighV);
  3361. }
  3362. if (NumRanges > 2) {
  3363. APInt FirstLow =
  3364. mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
  3365. APInt FirstHigh =
  3366. mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
  3367. ConstantRange FirstRange(FirstLow, FirstHigh);
  3368. Check(FirstRange.intersectWith(LastRange).isEmptySet(),
  3369. "Intervals are overlapping", Range);
  3370. Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
  3371. Range);
  3372. }
  3373. }
  3374. void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
  3375. unsigned Size = DL.getTypeSizeInBits(Ty);
  3376. Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
  3377. Check(!(Size & (Size - 1)),
  3378. "atomic memory access' operand must have a power-of-two size", Ty, I);
  3379. }
  3380. void Verifier::visitLoadInst(LoadInst &LI) {
  3381. PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
  3382. Check(PTy, "Load operand must be a pointer.", &LI);
  3383. Type *ElTy = LI.getType();
  3384. if (MaybeAlign A = LI.getAlign()) {
  3385. Check(A->value() <= Value::MaximumAlignment,
  3386. "huge alignment values are unsupported", &LI);
  3387. }
  3388. Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
  3389. if (LI.isAtomic()) {
  3390. Check(LI.getOrdering() != AtomicOrdering::Release &&
  3391. LI.getOrdering() != AtomicOrdering::AcquireRelease,
  3392. "Load cannot have Release ordering", &LI);
  3393. Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
  3394. "atomic load operand must have integer, pointer, or floating point "
  3395. "type!",
  3396. ElTy, &LI);
  3397. checkAtomicMemAccessSize(ElTy, &LI);
  3398. } else {
  3399. Check(LI.getSyncScopeID() == SyncScope::System,
  3400. "Non-atomic load cannot have SynchronizationScope specified", &LI);
  3401. }
  3402. visitInstruction(LI);
  3403. }
  3404. void Verifier::visitStoreInst(StoreInst &SI) {
  3405. PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
  3406. Check(PTy, "Store operand must be a pointer.", &SI);
  3407. Type *ElTy = SI.getOperand(0)->getType();
  3408. Check(PTy->isOpaqueOrPointeeTypeMatches(ElTy),
  3409. "Stored value type does not match pointer operand type!", &SI, ElTy);
  3410. if (MaybeAlign A = SI.getAlign()) {
  3411. Check(A->value() <= Value::MaximumAlignment,
  3412. "huge alignment values are unsupported", &SI);
  3413. }
  3414. Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
  3415. if (SI.isAtomic()) {
  3416. Check(SI.getOrdering() != AtomicOrdering::Acquire &&
  3417. SI.getOrdering() != AtomicOrdering::AcquireRelease,
  3418. "Store cannot have Acquire ordering", &SI);
  3419. Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
  3420. "atomic store operand must have integer, pointer, or floating point "
  3421. "type!",
  3422. ElTy, &SI);
  3423. checkAtomicMemAccessSize(ElTy, &SI);
  3424. } else {
  3425. Check(SI.getSyncScopeID() == SyncScope::System,
  3426. "Non-atomic store cannot have SynchronizationScope specified", &SI);
  3427. }
  3428. visitInstruction(SI);
  3429. }
  3430. /// Check that SwiftErrorVal is used as a swifterror argument in CS.
  3431. void Verifier::verifySwiftErrorCall(CallBase &Call,
  3432. const Value *SwiftErrorVal) {
  3433. for (const auto &I : llvm::enumerate(Call.args())) {
  3434. if (I.value() == SwiftErrorVal) {
  3435. Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
  3436. "swifterror value when used in a callsite should be marked "
  3437. "with swifterror attribute",
  3438. SwiftErrorVal, Call);
  3439. }
  3440. }
  3441. }
  3442. void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
  3443. // Check that swifterror value is only used by loads, stores, or as
  3444. // a swifterror argument.
  3445. for (const User *U : SwiftErrorVal->users()) {
  3446. Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
  3447. isa<InvokeInst>(U),
  3448. "swifterror value can only be loaded and stored from, or "
  3449. "as a swifterror argument!",
  3450. SwiftErrorVal, U);
  3451. // If it is used by a store, check it is the second operand.
  3452. if (auto StoreI = dyn_cast<StoreInst>(U))
  3453. Check(StoreI->getOperand(1) == SwiftErrorVal,
  3454. "swifterror value should be the second operand when used "
  3455. "by stores",
  3456. SwiftErrorVal, U);
  3457. if (auto *Call = dyn_cast<CallBase>(U))
  3458. verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
  3459. }
  3460. }
  3461. void Verifier::visitAllocaInst(AllocaInst &AI) {
  3462. SmallPtrSet<Type*, 4> Visited;
  3463. Check(AI.getAllocatedType()->isSized(&Visited),
  3464. "Cannot allocate unsized type", &AI);
  3465. Check(AI.getArraySize()->getType()->isIntegerTy(),
  3466. "Alloca array size must have integer type", &AI);
  3467. if (MaybeAlign A = AI.getAlign()) {
  3468. Check(A->value() <= Value::MaximumAlignment,
  3469. "huge alignment values are unsupported", &AI);
  3470. }
  3471. if (AI.isSwiftError()) {
  3472. Check(AI.getAllocatedType()->isPointerTy(),
  3473. "swifterror alloca must have pointer type", &AI);
  3474. Check(!AI.isArrayAllocation(),
  3475. "swifterror alloca must not be array allocation", &AI);
  3476. verifySwiftErrorValue(&AI);
  3477. }
  3478. visitInstruction(AI);
  3479. }
  3480. void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
  3481. Type *ElTy = CXI.getOperand(1)->getType();
  3482. Check(ElTy->isIntOrPtrTy(),
  3483. "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
  3484. checkAtomicMemAccessSize(ElTy, &CXI);
  3485. visitInstruction(CXI);
  3486. }
  3487. void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
  3488. Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
  3489. "atomicrmw instructions cannot be unordered.", &RMWI);
  3490. auto Op = RMWI.getOperation();
  3491. Type *ElTy = RMWI.getOperand(1)->getType();
  3492. if (Op == AtomicRMWInst::Xchg) {
  3493. Check(ElTy->isIntegerTy() || ElTy->isFloatingPointTy() ||
  3494. ElTy->isPointerTy(),
  3495. "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
  3496. " operand must have integer or floating point type!",
  3497. &RMWI, ElTy);
  3498. } else if (AtomicRMWInst::isFPOperation(Op)) {
  3499. Check(ElTy->isFloatingPointTy(),
  3500. "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
  3501. " operand must have floating point type!",
  3502. &RMWI, ElTy);
  3503. } else {
  3504. Check(ElTy->isIntegerTy(),
  3505. "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
  3506. " operand must have integer type!",
  3507. &RMWI, ElTy);
  3508. }
  3509. checkAtomicMemAccessSize(ElTy, &RMWI);
  3510. Check(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
  3511. "Invalid binary operation!", &RMWI);
  3512. visitInstruction(RMWI);
  3513. }
  3514. void Verifier::visitFenceInst(FenceInst &FI) {
  3515. const AtomicOrdering Ordering = FI.getOrdering();
  3516. Check(Ordering == AtomicOrdering::Acquire ||
  3517. Ordering == AtomicOrdering::Release ||
  3518. Ordering == AtomicOrdering::AcquireRelease ||
  3519. Ordering == AtomicOrdering::SequentiallyConsistent,
  3520. "fence instructions may only have acquire, release, acq_rel, or "
  3521. "seq_cst ordering.",
  3522. &FI);
  3523. visitInstruction(FI);
  3524. }
  3525. void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
  3526. Check(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
  3527. EVI.getIndices()) == EVI.getType(),
  3528. "Invalid ExtractValueInst operands!", &EVI);
  3529. visitInstruction(EVI);
  3530. }
  3531. void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
  3532. Check(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
  3533. IVI.getIndices()) ==
  3534. IVI.getOperand(1)->getType(),
  3535. "Invalid InsertValueInst operands!", &IVI);
  3536. visitInstruction(IVI);
  3537. }
  3538. static Value *getParentPad(Value *EHPad) {
  3539. if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
  3540. return FPI->getParentPad();
  3541. return cast<CatchSwitchInst>(EHPad)->getParentPad();
  3542. }
  3543. void Verifier::visitEHPadPredecessors(Instruction &I) {
  3544. assert(I.isEHPad());
  3545. BasicBlock *BB = I.getParent();
  3546. Function *F = BB->getParent();
  3547. Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
  3548. if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
  3549. // The landingpad instruction defines its parent as a landing pad block. The
  3550. // landing pad block may be branched to only by the unwind edge of an
  3551. // invoke.
  3552. for (BasicBlock *PredBB : predecessors(BB)) {
  3553. const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
  3554. Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
  3555. "Block containing LandingPadInst must be jumped to "
  3556. "only by the unwind edge of an invoke.",
  3557. LPI);
  3558. }
  3559. return;
  3560. }
  3561. if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
  3562. if (!pred_empty(BB))
  3563. Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
  3564. "Block containg CatchPadInst must be jumped to "
  3565. "only by its catchswitch.",
  3566. CPI);
  3567. Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
  3568. "Catchswitch cannot unwind to one of its catchpads",
  3569. CPI->getCatchSwitch(), CPI);
  3570. return;
  3571. }
  3572. // Verify that each pred has a legal terminator with a legal to/from EH
  3573. // pad relationship.
  3574. Instruction *ToPad = &I;
  3575. Value *ToPadParent = getParentPad(ToPad);
  3576. for (BasicBlock *PredBB : predecessors(BB)) {
  3577. Instruction *TI = PredBB->getTerminator();
  3578. Value *FromPad;
  3579. if (auto *II = dyn_cast<InvokeInst>(TI)) {
  3580. Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
  3581. "EH pad must be jumped to via an unwind edge", ToPad, II);
  3582. if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
  3583. FromPad = Bundle->Inputs[0];
  3584. else
  3585. FromPad = ConstantTokenNone::get(II->getContext());
  3586. } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
  3587. FromPad = CRI->getOperand(0);
  3588. Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
  3589. } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
  3590. FromPad = CSI;
  3591. } else {
  3592. Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
  3593. }
  3594. // The edge may exit from zero or more nested pads.
  3595. SmallSet<Value *, 8> Seen;
  3596. for (;; FromPad = getParentPad(FromPad)) {
  3597. Check(FromPad != ToPad,
  3598. "EH pad cannot handle exceptions raised within it", FromPad, TI);
  3599. if (FromPad == ToPadParent) {
  3600. // This is a legal unwind edge.
  3601. break;
  3602. }
  3603. Check(!isa<ConstantTokenNone>(FromPad),
  3604. "A single unwind edge may only enter one EH pad", TI);
  3605. Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
  3606. FromPad);
  3607. // This will be diagnosed on the corresponding instruction already. We
  3608. // need the extra check here to make sure getParentPad() works.
  3609. Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
  3610. "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
  3611. }
  3612. }
  3613. }
  3614. void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
  3615. // The landingpad instruction is ill-formed if it doesn't have any clauses and
  3616. // isn't a cleanup.
  3617. Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
  3618. "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
  3619. visitEHPadPredecessors(LPI);
  3620. if (!LandingPadResultTy)
  3621. LandingPadResultTy = LPI.getType();
  3622. else
  3623. Check(LandingPadResultTy == LPI.getType(),
  3624. "The landingpad instruction should have a consistent result type "
  3625. "inside a function.",
  3626. &LPI);
  3627. Function *F = LPI.getParent()->getParent();
  3628. Check(F->hasPersonalityFn(),
  3629. "LandingPadInst needs to be in a function with a personality.", &LPI);
  3630. // The landingpad instruction must be the first non-PHI instruction in the
  3631. // block.
  3632. Check(LPI.getParent()->getLandingPadInst() == &LPI,
  3633. "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
  3634. for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
  3635. Constant *Clause = LPI.getClause(i);
  3636. if (LPI.isCatch(i)) {
  3637. Check(isa<PointerType>(Clause->getType()),
  3638. "Catch operand does not have pointer type!", &LPI);
  3639. } else {
  3640. Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
  3641. Check(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
  3642. "Filter operand is not an array of constants!", &LPI);
  3643. }
  3644. }
  3645. visitInstruction(LPI);
  3646. }
  3647. void Verifier::visitResumeInst(ResumeInst &RI) {
  3648. Check(RI.getFunction()->hasPersonalityFn(),
  3649. "ResumeInst needs to be in a function with a personality.", &RI);
  3650. if (!LandingPadResultTy)
  3651. LandingPadResultTy = RI.getValue()->getType();
  3652. else
  3653. Check(LandingPadResultTy == RI.getValue()->getType(),
  3654. "The resume instruction should have a consistent result type "
  3655. "inside a function.",
  3656. &RI);
  3657. visitTerminator(RI);
  3658. }
  3659. void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
  3660. BasicBlock *BB = CPI.getParent();
  3661. Function *F = BB->getParent();
  3662. Check(F->hasPersonalityFn(),
  3663. "CatchPadInst needs to be in a function with a personality.", &CPI);
  3664. Check(isa<CatchSwitchInst>(CPI.getParentPad()),
  3665. "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
  3666. CPI.getParentPad());
  3667. // The catchpad instruction must be the first non-PHI instruction in the
  3668. // block.
  3669. Check(BB->getFirstNonPHI() == &CPI,
  3670. "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
  3671. visitEHPadPredecessors(CPI);
  3672. visitFuncletPadInst(CPI);
  3673. }
  3674. void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
  3675. Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
  3676. "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
  3677. CatchReturn.getOperand(0));
  3678. visitTerminator(CatchReturn);
  3679. }
  3680. void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
  3681. BasicBlock *BB = CPI.getParent();
  3682. Function *F = BB->getParent();
  3683. Check(F->hasPersonalityFn(),
  3684. "CleanupPadInst needs to be in a function with a personality.", &CPI);
  3685. // The cleanuppad instruction must be the first non-PHI instruction in the
  3686. // block.
  3687. Check(BB->getFirstNonPHI() == &CPI,
  3688. "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
  3689. auto *ParentPad = CPI.getParentPad();
  3690. Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
  3691. "CleanupPadInst has an invalid parent.", &CPI);
  3692. visitEHPadPredecessors(CPI);
  3693. visitFuncletPadInst(CPI);
  3694. }
  3695. void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
  3696. User *FirstUser = nullptr;
  3697. Value *FirstUnwindPad = nullptr;
  3698. SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
  3699. SmallSet<FuncletPadInst *, 8> Seen;
  3700. while (!Worklist.empty()) {
  3701. FuncletPadInst *CurrentPad = Worklist.pop_back_val();
  3702. Check(Seen.insert(CurrentPad).second,
  3703. "FuncletPadInst must not be nested within itself", CurrentPad);
  3704. Value *UnresolvedAncestorPad = nullptr;
  3705. for (User *U : CurrentPad->users()) {
  3706. BasicBlock *UnwindDest;
  3707. if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
  3708. UnwindDest = CRI->getUnwindDest();
  3709. } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
  3710. // We allow catchswitch unwind to caller to nest
  3711. // within an outer pad that unwinds somewhere else,
  3712. // because catchswitch doesn't have a nounwind variant.
  3713. // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
  3714. if (CSI->unwindsToCaller())
  3715. continue;
  3716. UnwindDest = CSI->getUnwindDest();
  3717. } else if (auto *II = dyn_cast<InvokeInst>(U)) {
  3718. UnwindDest = II->getUnwindDest();
  3719. } else if (isa<CallInst>(U)) {
  3720. // Calls which don't unwind may be found inside funclet
  3721. // pads that unwind somewhere else. We don't *require*
  3722. // such calls to be annotated nounwind.
  3723. continue;
  3724. } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
  3725. // The unwind dest for a cleanup can only be found by
  3726. // recursive search. Add it to the worklist, and we'll
  3727. // search for its first use that determines where it unwinds.
  3728. Worklist.push_back(CPI);
  3729. continue;
  3730. } else {
  3731. Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
  3732. continue;
  3733. }
  3734. Value *UnwindPad;
  3735. bool ExitsFPI;
  3736. if (UnwindDest) {
  3737. UnwindPad = UnwindDest->getFirstNonPHI();
  3738. if (!cast<Instruction>(UnwindPad)->isEHPad())
  3739. continue;
  3740. Value *UnwindParent = getParentPad(UnwindPad);
  3741. // Ignore unwind edges that don't exit CurrentPad.
  3742. if (UnwindParent == CurrentPad)
  3743. continue;
  3744. // Determine whether the original funclet pad is exited,
  3745. // and if we are scanning nested pads determine how many
  3746. // of them are exited so we can stop searching their
  3747. // children.
  3748. Value *ExitedPad = CurrentPad;
  3749. ExitsFPI = false;
  3750. do {
  3751. if (ExitedPad == &FPI) {
  3752. ExitsFPI = true;
  3753. // Now we can resolve any ancestors of CurrentPad up to
  3754. // FPI, but not including FPI since we need to make sure
  3755. // to check all direct users of FPI for consistency.
  3756. UnresolvedAncestorPad = &FPI;
  3757. break;
  3758. }
  3759. Value *ExitedParent = getParentPad(ExitedPad);
  3760. if (ExitedParent == UnwindParent) {
  3761. // ExitedPad is the ancestor-most pad which this unwind
  3762. // edge exits, so we can resolve up to it, meaning that
  3763. // ExitedParent is the first ancestor still unresolved.
  3764. UnresolvedAncestorPad = ExitedParent;
  3765. break;
  3766. }
  3767. ExitedPad = ExitedParent;
  3768. } while (!isa<ConstantTokenNone>(ExitedPad));
  3769. } else {
  3770. // Unwinding to caller exits all pads.
  3771. UnwindPad = ConstantTokenNone::get(FPI.getContext());
  3772. ExitsFPI = true;
  3773. UnresolvedAncestorPad = &FPI;
  3774. }
  3775. if (ExitsFPI) {
  3776. // This unwind edge exits FPI. Make sure it agrees with other
  3777. // such edges.
  3778. if (FirstUser) {
  3779. Check(UnwindPad == FirstUnwindPad,
  3780. "Unwind edges out of a funclet "
  3781. "pad must have the same unwind "
  3782. "dest",
  3783. &FPI, U, FirstUser);
  3784. } else {
  3785. FirstUser = U;
  3786. FirstUnwindPad = UnwindPad;
  3787. // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
  3788. if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
  3789. getParentPad(UnwindPad) == getParentPad(&FPI))
  3790. SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
  3791. }
  3792. }
  3793. // Make sure we visit all uses of FPI, but for nested pads stop as
  3794. // soon as we know where they unwind to.
  3795. if (CurrentPad != &FPI)
  3796. break;
  3797. }
  3798. if (UnresolvedAncestorPad) {
  3799. if (CurrentPad == UnresolvedAncestorPad) {
  3800. // When CurrentPad is FPI itself, we don't mark it as resolved even if
  3801. // we've found an unwind edge that exits it, because we need to verify
  3802. // all direct uses of FPI.
  3803. assert(CurrentPad == &FPI);
  3804. continue;
  3805. }
  3806. // Pop off the worklist any nested pads that we've found an unwind
  3807. // destination for. The pads on the worklist are the uncles,
  3808. // great-uncles, etc. of CurrentPad. We've found an unwind destination
  3809. // for all ancestors of CurrentPad up to but not including
  3810. // UnresolvedAncestorPad.
  3811. Value *ResolvedPad = CurrentPad;
  3812. while (!Worklist.empty()) {
  3813. Value *UnclePad = Worklist.back();
  3814. Value *AncestorPad = getParentPad(UnclePad);
  3815. // Walk ResolvedPad up the ancestor list until we either find the
  3816. // uncle's parent or the last resolved ancestor.
  3817. while (ResolvedPad != AncestorPad) {
  3818. Value *ResolvedParent = getParentPad(ResolvedPad);
  3819. if (ResolvedParent == UnresolvedAncestorPad) {
  3820. break;
  3821. }
  3822. ResolvedPad = ResolvedParent;
  3823. }
  3824. // If the resolved ancestor search didn't find the uncle's parent,
  3825. // then the uncle is not yet resolved.
  3826. if (ResolvedPad != AncestorPad)
  3827. break;
  3828. // This uncle is resolved, so pop it from the worklist.
  3829. Worklist.pop_back();
  3830. }
  3831. }
  3832. }
  3833. if (FirstUnwindPad) {
  3834. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
  3835. BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
  3836. Value *SwitchUnwindPad;
  3837. if (SwitchUnwindDest)
  3838. SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
  3839. else
  3840. SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
  3841. Check(SwitchUnwindPad == FirstUnwindPad,
  3842. "Unwind edges out of a catch must have the same unwind dest as "
  3843. "the parent catchswitch",
  3844. &FPI, FirstUser, CatchSwitch);
  3845. }
  3846. }
  3847. visitInstruction(FPI);
  3848. }
  3849. void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
  3850. BasicBlock *BB = CatchSwitch.getParent();
  3851. Function *F = BB->getParent();
  3852. Check(F->hasPersonalityFn(),
  3853. "CatchSwitchInst needs to be in a function with a personality.",
  3854. &CatchSwitch);
  3855. // The catchswitch instruction must be the first non-PHI instruction in the
  3856. // block.
  3857. Check(BB->getFirstNonPHI() == &CatchSwitch,
  3858. "CatchSwitchInst not the first non-PHI instruction in the block.",
  3859. &CatchSwitch);
  3860. auto *ParentPad = CatchSwitch.getParentPad();
  3861. Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
  3862. "CatchSwitchInst has an invalid parent.", ParentPad);
  3863. if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
  3864. Instruction *I = UnwindDest->getFirstNonPHI();
  3865. Check(I->isEHPad() && !isa<LandingPadInst>(I),
  3866. "CatchSwitchInst must unwind to an EH block which is not a "
  3867. "landingpad.",
  3868. &CatchSwitch);
  3869. // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
  3870. if (getParentPad(I) == ParentPad)
  3871. SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
  3872. }
  3873. Check(CatchSwitch.getNumHandlers() != 0,
  3874. "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
  3875. for (BasicBlock *Handler : CatchSwitch.handlers()) {
  3876. Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
  3877. "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
  3878. }
  3879. visitEHPadPredecessors(CatchSwitch);
  3880. visitTerminator(CatchSwitch);
  3881. }
  3882. void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
  3883. Check(isa<CleanupPadInst>(CRI.getOperand(0)),
  3884. "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
  3885. CRI.getOperand(0));
  3886. if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
  3887. Instruction *I = UnwindDest->getFirstNonPHI();
  3888. Check(I->isEHPad() && !isa<LandingPadInst>(I),
  3889. "CleanupReturnInst must unwind to an EH block which is not a "
  3890. "landingpad.",
  3891. &CRI);
  3892. }
  3893. visitTerminator(CRI);
  3894. }
  3895. void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
  3896. Instruction *Op = cast<Instruction>(I.getOperand(i));
  3897. // If the we have an invalid invoke, don't try to compute the dominance.
  3898. // We already reject it in the invoke specific checks and the dominance
  3899. // computation doesn't handle multiple edges.
  3900. if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
  3901. if (II->getNormalDest() == II->getUnwindDest())
  3902. return;
  3903. }
  3904. // Quick check whether the def has already been encountered in the same block.
  3905. // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
  3906. // uses are defined to happen on the incoming edge, not at the instruction.
  3907. //
  3908. // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
  3909. // wrapping an SSA value, assert that we've already encountered it. See
  3910. // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
  3911. if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
  3912. return;
  3913. const Use &U = I.getOperandUse(i);
  3914. Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
  3915. }
  3916. void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
  3917. Check(I.getType()->isPointerTy(),
  3918. "dereferenceable, dereferenceable_or_null "
  3919. "apply only to pointer types",
  3920. &I);
  3921. Check((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
  3922. "dereferenceable, dereferenceable_or_null apply only to load"
  3923. " and inttoptr instructions, use attributes for calls or invokes",
  3924. &I);
  3925. Check(MD->getNumOperands() == 1,
  3926. "dereferenceable, dereferenceable_or_null "
  3927. "take one operand!",
  3928. &I);
  3929. ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
  3930. Check(CI && CI->getType()->isIntegerTy(64),
  3931. "dereferenceable, "
  3932. "dereferenceable_or_null metadata value must be an i64!",
  3933. &I);
  3934. }
  3935. void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
  3936. Check(MD->getNumOperands() >= 2,
  3937. "!prof annotations should have no less than 2 operands", MD);
  3938. // Check first operand.
  3939. Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
  3940. Check(isa<MDString>(MD->getOperand(0)),
  3941. "expected string with name of the !prof annotation", MD);
  3942. MDString *MDS = cast<MDString>(MD->getOperand(0));
  3943. StringRef ProfName = MDS->getString();
  3944. // Check consistency of !prof branch_weights metadata.
  3945. if (ProfName.equals("branch_weights")) {
  3946. if (isa<InvokeInst>(&I)) {
  3947. Check(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
  3948. "Wrong number of InvokeInst branch_weights operands", MD);
  3949. } else {
  3950. unsigned ExpectedNumOperands = 0;
  3951. if (BranchInst *BI = dyn_cast<BranchInst>(&I))
  3952. ExpectedNumOperands = BI->getNumSuccessors();
  3953. else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
  3954. ExpectedNumOperands = SI->getNumSuccessors();
  3955. else if (isa<CallInst>(&I))
  3956. ExpectedNumOperands = 1;
  3957. else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
  3958. ExpectedNumOperands = IBI->getNumDestinations();
  3959. else if (isa<SelectInst>(&I))
  3960. ExpectedNumOperands = 2;
  3961. else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
  3962. ExpectedNumOperands = CI->getNumSuccessors();
  3963. else
  3964. CheckFailed("!prof branch_weights are not allowed for this instruction",
  3965. MD);
  3966. Check(MD->getNumOperands() == 1 + ExpectedNumOperands,
  3967. "Wrong number of operands", MD);
  3968. }
  3969. for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
  3970. auto &MDO = MD->getOperand(i);
  3971. Check(MDO, "second operand should not be null", MD);
  3972. Check(mdconst::dyn_extract<ConstantInt>(MDO),
  3973. "!prof brunch_weights operand is not a const int");
  3974. }
  3975. }
  3976. }
  3977. void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
  3978. assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
  3979. bool ExpectedInstTy =
  3980. isa<AllocaInst>(I) || isa<StoreInst>(I) || isa<MemIntrinsic>(I);
  3981. CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
  3982. I, MD);
  3983. // Iterate over the MetadataAsValue uses of the DIAssignID - these should
  3984. // only be found as DbgAssignIntrinsic operands.
  3985. if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
  3986. for (auto *User : AsValue->users()) {
  3987. CheckDI(isa<DbgAssignIntrinsic>(User),
  3988. "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
  3989. MD, User);
  3990. // All of the dbg.assign intrinsics should be in the same function as I.
  3991. if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
  3992. CheckDI(DAI->getFunction() == I.getFunction(),
  3993. "dbg.assign not in same function as inst", DAI, &I);
  3994. }
  3995. }
  3996. }
  3997. void Verifier::visitCallStackMetadata(MDNode *MD) {
  3998. // Call stack metadata should consist of a list of at least 1 constant int
  3999. // (representing a hash of the location).
  4000. Check(MD->getNumOperands() >= 1,
  4001. "call stack metadata should have at least 1 operand", MD);
  4002. for (const auto &Op : MD->operands())
  4003. Check(mdconst::dyn_extract_or_null<ConstantInt>(Op),
  4004. "call stack metadata operand should be constant integer", Op);
  4005. }
  4006. void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
  4007. Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
  4008. Check(MD->getNumOperands() >= 1,
  4009. "!memprof annotations should have at least 1 metadata operand "
  4010. "(MemInfoBlock)",
  4011. MD);
  4012. // Check each MIB
  4013. for (auto &MIBOp : MD->operands()) {
  4014. MDNode *MIB = dyn_cast<MDNode>(MIBOp);
  4015. // The first operand of an MIB should be the call stack metadata.
  4016. // There rest of the operands should be MDString tags, and there should be
  4017. // at least one.
  4018. Check(MIB->getNumOperands() >= 2,
  4019. "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
  4020. // Check call stack metadata (first operand).
  4021. Check(MIB->getOperand(0) != nullptr,
  4022. "!memprof MemInfoBlock first operand should not be null", MIB);
  4023. Check(isa<MDNode>(MIB->getOperand(0)),
  4024. "!memprof MemInfoBlock first operand should be an MDNode", MIB);
  4025. MDNode *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
  4026. visitCallStackMetadata(StackMD);
  4027. // Check that remaining operands are MDString.
  4028. Check(llvm::all_of(llvm::drop_begin(MIB->operands()),
  4029. [](const MDOperand &Op) { return isa<MDString>(Op); }),
  4030. "Not all !memprof MemInfoBlock operands 1 to N are MDString", MIB);
  4031. }
  4032. }
  4033. void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
  4034. Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
  4035. // Verify the partial callstack annotated from memprof profiles. This callsite
  4036. // is a part of a profiled allocation callstack.
  4037. visitCallStackMetadata(MD);
  4038. }
  4039. void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
  4040. Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
  4041. Check(Annotation->getNumOperands() >= 1,
  4042. "annotation must have at least one operand");
  4043. for (const MDOperand &Op : Annotation->operands())
  4044. Check(isa<MDString>(Op.get()), "operands must be strings");
  4045. }
  4046. void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
  4047. unsigned NumOps = MD->getNumOperands();
  4048. Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
  4049. MD);
  4050. Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
  4051. "first scope operand must be self-referential or string", MD);
  4052. if (NumOps == 3)
  4053. Check(isa<MDString>(MD->getOperand(2)),
  4054. "third scope operand must be string (if used)", MD);
  4055. MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
  4056. Check(Domain != nullptr, "second scope operand must be MDNode", MD);
  4057. unsigned NumDomainOps = Domain->getNumOperands();
  4058. Check(NumDomainOps >= 1 && NumDomainOps <= 2,
  4059. "domain must have one or two operands", Domain);
  4060. Check(Domain->getOperand(0).get() == Domain ||
  4061. isa<MDString>(Domain->getOperand(0)),
  4062. "first domain operand must be self-referential or string", Domain);
  4063. if (NumDomainOps == 2)
  4064. Check(isa<MDString>(Domain->getOperand(1)),
  4065. "second domain operand must be string (if used)", Domain);
  4066. }
  4067. void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
  4068. for (const MDOperand &Op : MD->operands()) {
  4069. const MDNode *OpMD = dyn_cast<MDNode>(Op);
  4070. Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
  4071. visitAliasScopeMetadata(OpMD);
  4072. }
  4073. }
  4074. void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
  4075. auto IsValidAccessScope = [](const MDNode *MD) {
  4076. return MD->getNumOperands() == 0 && MD->isDistinct();
  4077. };
  4078. // It must be either an access scope itself...
  4079. if (IsValidAccessScope(MD))
  4080. return;
  4081. // ...or a list of access scopes.
  4082. for (const MDOperand &Op : MD->operands()) {
  4083. const MDNode *OpMD = dyn_cast<MDNode>(Op);
  4084. Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
  4085. Check(IsValidAccessScope(OpMD),
  4086. "Access scope list contains invalid access scope", MD);
  4087. }
  4088. }
  4089. /// verifyInstruction - Verify that an instruction is well formed.
  4090. ///
  4091. void Verifier::visitInstruction(Instruction &I) {
  4092. BasicBlock *BB = I.getParent();
  4093. Check(BB, "Instruction not embedded in basic block!", &I);
  4094. if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
  4095. for (User *U : I.users()) {
  4096. Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
  4097. "Only PHI nodes may reference their own value!", &I);
  4098. }
  4099. }
  4100. // Check that void typed values don't have names
  4101. Check(!I.getType()->isVoidTy() || !I.hasName(),
  4102. "Instruction has a name, but provides a void value!", &I);
  4103. // Check that the return value of the instruction is either void or a legal
  4104. // value type.
  4105. Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
  4106. "Instruction returns a non-scalar type!", &I);
  4107. // Check that the instruction doesn't produce metadata. Calls are already
  4108. // checked against the callee type.
  4109. Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
  4110. "Invalid use of metadata!", &I);
  4111. // Check that all uses of the instruction, if they are instructions
  4112. // themselves, actually have parent basic blocks. If the use is not an
  4113. // instruction, it is an error!
  4114. for (Use &U : I.uses()) {
  4115. if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
  4116. Check(Used->getParent() != nullptr,
  4117. "Instruction referencing"
  4118. " instruction not embedded in a basic block!",
  4119. &I, Used);
  4120. else {
  4121. CheckFailed("Use of instruction is not an instruction!", U);
  4122. return;
  4123. }
  4124. }
  4125. // Get a pointer to the call base of the instruction if it is some form of
  4126. // call.
  4127. const CallBase *CBI = dyn_cast<CallBase>(&I);
  4128. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
  4129. Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
  4130. // Check to make sure that only first-class-values are operands to
  4131. // instructions.
  4132. if (!I.getOperand(i)->getType()->isFirstClassType()) {
  4133. Check(false, "Instruction operands must be first-class values!", &I);
  4134. }
  4135. if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
  4136. // This code checks whether the function is used as the operand of a
  4137. // clang_arc_attachedcall operand bundle.
  4138. auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
  4139. int Idx) {
  4140. return CBI && CBI->isOperandBundleOfType(
  4141. LLVMContext::OB_clang_arc_attachedcall, Idx);
  4142. };
  4143. // Check to make sure that the "address of" an intrinsic function is never
  4144. // taken. Ignore cases where the address of the intrinsic function is used
  4145. // as the argument of operand bundle "clang.arc.attachedcall" as those
  4146. // cases are handled in verifyAttachedCallBundle.
  4147. Check((!F->isIntrinsic() ||
  4148. (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
  4149. IsAttachedCallOperand(F, CBI, i)),
  4150. "Cannot take the address of an intrinsic!", &I);
  4151. Check(!F->isIntrinsic() || isa<CallInst>(I) ||
  4152. F->getIntrinsicID() == Intrinsic::donothing ||
  4153. F->getIntrinsicID() == Intrinsic::seh_try_begin ||
  4154. F->getIntrinsicID() == Intrinsic::seh_try_end ||
  4155. F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
  4156. F->getIntrinsicID() == Intrinsic::seh_scope_end ||
  4157. F->getIntrinsicID() == Intrinsic::coro_resume ||
  4158. F->getIntrinsicID() == Intrinsic::coro_destroy ||
  4159. F->getIntrinsicID() ==
  4160. Intrinsic::experimental_patchpoint_void ||
  4161. F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
  4162. F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
  4163. F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
  4164. IsAttachedCallOperand(F, CBI, i),
  4165. "Cannot invoke an intrinsic other than donothing, patchpoint, "
  4166. "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
  4167. &I);
  4168. Check(F->getParent() == &M, "Referencing function in another module!", &I,
  4169. &M, F, F->getParent());
  4170. } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
  4171. Check(OpBB->getParent() == BB->getParent(),
  4172. "Referring to a basic block in another function!", &I);
  4173. } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
  4174. Check(OpArg->getParent() == BB->getParent(),
  4175. "Referring to an argument in another function!", &I);
  4176. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
  4177. Check(GV->getParent() == &M, "Referencing global in another module!", &I,
  4178. &M, GV, GV->getParent());
  4179. } else if (isa<Instruction>(I.getOperand(i))) {
  4180. verifyDominatesUse(I, i);
  4181. } else if (isa<InlineAsm>(I.getOperand(i))) {
  4182. Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
  4183. "Cannot take the address of an inline asm!", &I);
  4184. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
  4185. if (CE->getType()->isPtrOrPtrVectorTy()) {
  4186. // If we have a ConstantExpr pointer, we need to see if it came from an
  4187. // illegal bitcast.
  4188. visitConstantExprsRecursively(CE);
  4189. }
  4190. }
  4191. }
  4192. if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
  4193. Check(I.getType()->isFPOrFPVectorTy(),
  4194. "fpmath requires a floating point result!", &I);
  4195. Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
  4196. if (ConstantFP *CFP0 =
  4197. mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
  4198. const APFloat &Accuracy = CFP0->getValueAPF();
  4199. Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
  4200. "fpmath accuracy must have float type", &I);
  4201. Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
  4202. "fpmath accuracy not a positive number!", &I);
  4203. } else {
  4204. Check(false, "invalid fpmath accuracy!", &I);
  4205. }
  4206. }
  4207. if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
  4208. Check(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
  4209. "Ranges are only for loads, calls and invokes!", &I);
  4210. visitRangeMetadata(I, Range, I.getType());
  4211. }
  4212. if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
  4213. Check(isa<LoadInst>(I) || isa<StoreInst>(I),
  4214. "invariant.group metadata is only for loads and stores", &I);
  4215. }
  4216. if (MDNode *MD = I.getMetadata(LLVMContext::MD_nonnull)) {
  4217. Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
  4218. &I);
  4219. Check(isa<LoadInst>(I),
  4220. "nonnull applies only to load instructions, use attributes"
  4221. " for calls or invokes",
  4222. &I);
  4223. Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
  4224. }
  4225. if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
  4226. visitDereferenceableMetadata(I, MD);
  4227. if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
  4228. visitDereferenceableMetadata(I, MD);
  4229. if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
  4230. TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
  4231. if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
  4232. visitAliasScopeListMetadata(MD);
  4233. if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
  4234. visitAliasScopeListMetadata(MD);
  4235. if (MDNode *MD = I.getMetadata(LLVMContext::MD_access_group))
  4236. visitAccessGroupMetadata(MD);
  4237. if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
  4238. Check(I.getType()->isPointerTy(), "align applies only to pointer types",
  4239. &I);
  4240. Check(isa<LoadInst>(I),
  4241. "align applies only to load instructions, "
  4242. "use attributes for calls or invokes",
  4243. &I);
  4244. Check(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
  4245. ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
  4246. Check(CI && CI->getType()->isIntegerTy(64),
  4247. "align metadata value must be an i64!", &I);
  4248. uint64_t Align = CI->getZExtValue();
  4249. Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
  4250. &I);
  4251. Check(Align <= Value::MaximumAlignment,
  4252. "alignment is larger that implementation defined limit", &I);
  4253. }
  4254. if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
  4255. visitProfMetadata(I, MD);
  4256. if (MDNode *MD = I.getMetadata(LLVMContext::MD_memprof))
  4257. visitMemProfMetadata(I, MD);
  4258. if (MDNode *MD = I.getMetadata(LLVMContext::MD_callsite))
  4259. visitCallsiteMetadata(I, MD);
  4260. if (MDNode *MD = I.getMetadata(LLVMContext::MD_DIAssignID))
  4261. visitDIAssignIDMetadata(I, MD);
  4262. if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
  4263. visitAnnotationMetadata(Annotation);
  4264. if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
  4265. CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
  4266. visitMDNode(*N, AreDebugLocsAllowed::Yes);
  4267. }
  4268. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
  4269. verifyFragmentExpression(*DII);
  4270. verifyNotEntryValue(*DII);
  4271. }
  4272. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  4273. I.getAllMetadata(MDs);
  4274. for (auto Attachment : MDs) {
  4275. unsigned Kind = Attachment.first;
  4276. auto AllowLocs =
  4277. (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
  4278. ? AreDebugLocsAllowed::Yes
  4279. : AreDebugLocsAllowed::No;
  4280. visitMDNode(*Attachment.second, AllowLocs);
  4281. }
  4282. InstsInThisBlock.insert(&I);
  4283. }
  4284. /// Allow intrinsics to be verified in different ways.
  4285. void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
  4286. Function *IF = Call.getCalledFunction();
  4287. Check(IF->isDeclaration(), "Intrinsic functions should never be defined!",
  4288. IF);
  4289. // Verify that the intrinsic prototype lines up with what the .td files
  4290. // describe.
  4291. FunctionType *IFTy = IF->getFunctionType();
  4292. bool IsVarArg = IFTy->isVarArg();
  4293. SmallVector<Intrinsic::IITDescriptor, 8> Table;
  4294. getIntrinsicInfoTableEntries(ID, Table);
  4295. ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
  4296. // Walk the descriptors to extract overloaded types.
  4297. SmallVector<Type *, 4> ArgTys;
  4298. Intrinsic::MatchIntrinsicTypesResult Res =
  4299. Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
  4300. Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
  4301. "Intrinsic has incorrect return type!", IF);
  4302. Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
  4303. "Intrinsic has incorrect argument type!", IF);
  4304. // Verify if the intrinsic call matches the vararg property.
  4305. if (IsVarArg)
  4306. Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
  4307. "Intrinsic was not defined with variable arguments!", IF);
  4308. else
  4309. Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
  4310. "Callsite was not defined with variable arguments!", IF);
  4311. // All descriptors should be absorbed by now.
  4312. Check(TableRef.empty(), "Intrinsic has too few arguments!", IF);
  4313. // Now that we have the intrinsic ID and the actual argument types (and we
  4314. // know they are legal for the intrinsic!) get the intrinsic name through the
  4315. // usual means. This allows us to verify the mangling of argument types into
  4316. // the name.
  4317. const std::string ExpectedName =
  4318. Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
  4319. Check(ExpectedName == IF->getName(),
  4320. "Intrinsic name not mangled correctly for type arguments! "
  4321. "Should be: " +
  4322. ExpectedName,
  4323. IF);
  4324. // If the intrinsic takes MDNode arguments, verify that they are either global
  4325. // or are local to *this* function.
  4326. for (Value *V : Call.args()) {
  4327. if (auto *MD = dyn_cast<MetadataAsValue>(V))
  4328. visitMetadataAsValue(*MD, Call.getCaller());
  4329. if (auto *Const = dyn_cast<Constant>(V))
  4330. Check(!Const->getType()->isX86_AMXTy(),
  4331. "const x86_amx is not allowed in argument!");
  4332. }
  4333. switch (ID) {
  4334. default:
  4335. break;
  4336. case Intrinsic::assume: {
  4337. for (auto &Elem : Call.bundle_op_infos()) {
  4338. unsigned ArgCount = Elem.End - Elem.Begin;
  4339. // Separate storage assumptions are special insofar as they're the only
  4340. // operand bundles allowed on assumes that aren't parameter attributes.
  4341. if (Elem.Tag->getKey() == "separate_storage") {
  4342. Check(ArgCount == 2,
  4343. "separate_storage assumptions should have 2 arguments", Call);
  4344. Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy() &&
  4345. Call.getOperand(Elem.Begin + 1)->getType()->isPointerTy(),
  4346. "arguments to separate_storage assumptions should be pointers",
  4347. Call);
  4348. return;
  4349. }
  4350. Check(Elem.Tag->getKey() == "ignore" ||
  4351. Attribute::isExistingAttribute(Elem.Tag->getKey()),
  4352. "tags must be valid attribute names", Call);
  4353. Attribute::AttrKind Kind =
  4354. Attribute::getAttrKindFromName(Elem.Tag->getKey());
  4355. if (Kind == Attribute::Alignment) {
  4356. Check(ArgCount <= 3 && ArgCount >= 2,
  4357. "alignment assumptions should have 2 or 3 arguments", Call);
  4358. Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
  4359. "first argument should be a pointer", Call);
  4360. Check(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
  4361. "second argument should be an integer", Call);
  4362. if (ArgCount == 3)
  4363. Check(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
  4364. "third argument should be an integer if present", Call);
  4365. return;
  4366. }
  4367. Check(ArgCount <= 2, "too many arguments", Call);
  4368. if (Kind == Attribute::None)
  4369. break;
  4370. if (Attribute::isIntAttrKind(Kind)) {
  4371. Check(ArgCount == 2, "this attribute should have 2 arguments", Call);
  4372. Check(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
  4373. "the second argument should be a constant integral value", Call);
  4374. } else if (Attribute::canUseAsParamAttr(Kind)) {
  4375. Check((ArgCount) == 1, "this attribute should have one argument", Call);
  4376. } else if (Attribute::canUseAsFnAttr(Kind)) {
  4377. Check((ArgCount) == 0, "this attribute has no argument", Call);
  4378. }
  4379. }
  4380. break;
  4381. }
  4382. case Intrinsic::coro_id: {
  4383. auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
  4384. if (isa<ConstantPointerNull>(InfoArg))
  4385. break;
  4386. auto *GV = dyn_cast<GlobalVariable>(InfoArg);
  4387. Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
  4388. "info argument of llvm.coro.id must refer to an initialized "
  4389. "constant");
  4390. Constant *Init = GV->getInitializer();
  4391. Check(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
  4392. "info argument of llvm.coro.id must refer to either a struct or "
  4393. "an array");
  4394. break;
  4395. }
  4396. case Intrinsic::is_fpclass: {
  4397. const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
  4398. Check((TestMask->getZExtValue() & ~fcAllFlags) == 0,
  4399. "unsupported bits for llvm.is.fpclass test mask");
  4400. break;
  4401. }
  4402. case Intrinsic::fptrunc_round: {
  4403. // Check the rounding mode
  4404. Metadata *MD = nullptr;
  4405. auto *MAV = dyn_cast<MetadataAsValue>(Call.getOperand(1));
  4406. if (MAV)
  4407. MD = MAV->getMetadata();
  4408. Check(MD != nullptr, "missing rounding mode argument", Call);
  4409. Check(isa<MDString>(MD),
  4410. ("invalid value for llvm.fptrunc.round metadata operand"
  4411. " (the operand should be a string)"),
  4412. MD);
  4413. std::optional<RoundingMode> RoundMode =
  4414. convertStrToRoundingMode(cast<MDString>(MD)->getString());
  4415. Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
  4416. "unsupported rounding mode argument", Call);
  4417. break;
  4418. }
  4419. #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
  4420. #include "llvm/IR/VPIntrinsics.def"
  4421. visitVPIntrinsic(cast<VPIntrinsic>(Call));
  4422. break;
  4423. #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
  4424. case Intrinsic::INTRINSIC:
  4425. #include "llvm/IR/ConstrainedOps.def"
  4426. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
  4427. break;
  4428. case Intrinsic::dbg_declare: // llvm.dbg.declare
  4429. Check(isa<MetadataAsValue>(Call.getArgOperand(0)),
  4430. "invalid llvm.dbg.declare intrinsic call 1", Call);
  4431. visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
  4432. break;
  4433. case Intrinsic::dbg_addr: // llvm.dbg.addr
  4434. visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
  4435. break;
  4436. case Intrinsic::dbg_value: // llvm.dbg.value
  4437. visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
  4438. break;
  4439. case Intrinsic::dbg_assign: // llvm.dbg.assign
  4440. visitDbgIntrinsic("assign", cast<DbgVariableIntrinsic>(Call));
  4441. break;
  4442. case Intrinsic::dbg_label: // llvm.dbg.label
  4443. visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
  4444. break;
  4445. case Intrinsic::memcpy:
  4446. case Intrinsic::memcpy_inline:
  4447. case Intrinsic::memmove:
  4448. case Intrinsic::memset:
  4449. case Intrinsic::memset_inline: {
  4450. break;
  4451. }
  4452. case Intrinsic::memcpy_element_unordered_atomic:
  4453. case Intrinsic::memmove_element_unordered_atomic:
  4454. case Intrinsic::memset_element_unordered_atomic: {
  4455. const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
  4456. ConstantInt *ElementSizeCI =
  4457. cast<ConstantInt>(AMI->getRawElementSizeInBytes());
  4458. const APInt &ElementSizeVal = ElementSizeCI->getValue();
  4459. Check(ElementSizeVal.isPowerOf2(),
  4460. "element size of the element-wise atomic memory intrinsic "
  4461. "must be a power of 2",
  4462. Call);
  4463. auto IsValidAlignment = [&](MaybeAlign Alignment) {
  4464. return Alignment && ElementSizeVal.ule(Alignment->value());
  4465. };
  4466. Check(IsValidAlignment(AMI->getDestAlign()),
  4467. "incorrect alignment of the destination argument", Call);
  4468. if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
  4469. Check(IsValidAlignment(AMT->getSourceAlign()),
  4470. "incorrect alignment of the source argument", Call);
  4471. }
  4472. break;
  4473. }
  4474. case Intrinsic::call_preallocated_setup: {
  4475. auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
  4476. Check(NumArgs != nullptr,
  4477. "llvm.call.preallocated.setup argument must be a constant");
  4478. bool FoundCall = false;
  4479. for (User *U : Call.users()) {
  4480. auto *UseCall = dyn_cast<CallBase>(U);
  4481. Check(UseCall != nullptr,
  4482. "Uses of llvm.call.preallocated.setup must be calls");
  4483. const Function *Fn = UseCall->getCalledFunction();
  4484. if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
  4485. auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
  4486. Check(AllocArgIndex != nullptr,
  4487. "llvm.call.preallocated.alloc arg index must be a constant");
  4488. auto AllocArgIndexInt = AllocArgIndex->getValue();
  4489. Check(AllocArgIndexInt.sge(0) &&
  4490. AllocArgIndexInt.slt(NumArgs->getValue()),
  4491. "llvm.call.preallocated.alloc arg index must be between 0 and "
  4492. "corresponding "
  4493. "llvm.call.preallocated.setup's argument count");
  4494. } else if (Fn && Fn->getIntrinsicID() ==
  4495. Intrinsic::call_preallocated_teardown) {
  4496. // nothing to do
  4497. } else {
  4498. Check(!FoundCall, "Can have at most one call corresponding to a "
  4499. "llvm.call.preallocated.setup");
  4500. FoundCall = true;
  4501. size_t NumPreallocatedArgs = 0;
  4502. for (unsigned i = 0; i < UseCall->arg_size(); i++) {
  4503. if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
  4504. ++NumPreallocatedArgs;
  4505. }
  4506. }
  4507. Check(NumPreallocatedArgs != 0,
  4508. "cannot use preallocated intrinsics on a call without "
  4509. "preallocated arguments");
  4510. Check(NumArgs->equalsInt(NumPreallocatedArgs),
  4511. "llvm.call.preallocated.setup arg size must be equal to number "
  4512. "of preallocated arguments "
  4513. "at call site",
  4514. Call, *UseCall);
  4515. // getOperandBundle() cannot be called if more than one of the operand
  4516. // bundle exists. There is already a check elsewhere for this, so skip
  4517. // here if we see more than one.
  4518. if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
  4519. 1) {
  4520. return;
  4521. }
  4522. auto PreallocatedBundle =
  4523. UseCall->getOperandBundle(LLVMContext::OB_preallocated);
  4524. Check(PreallocatedBundle,
  4525. "Use of llvm.call.preallocated.setup outside intrinsics "
  4526. "must be in \"preallocated\" operand bundle");
  4527. Check(PreallocatedBundle->Inputs.front().get() == &Call,
  4528. "preallocated bundle must have token from corresponding "
  4529. "llvm.call.preallocated.setup");
  4530. }
  4531. }
  4532. break;
  4533. }
  4534. case Intrinsic::call_preallocated_arg: {
  4535. auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
  4536. Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
  4537. Intrinsic::call_preallocated_setup,
  4538. "llvm.call.preallocated.arg token argument must be a "
  4539. "llvm.call.preallocated.setup");
  4540. Check(Call.hasFnAttr(Attribute::Preallocated),
  4541. "llvm.call.preallocated.arg must be called with a \"preallocated\" "
  4542. "call site attribute");
  4543. break;
  4544. }
  4545. case Intrinsic::call_preallocated_teardown: {
  4546. auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
  4547. Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
  4548. Intrinsic::call_preallocated_setup,
  4549. "llvm.call.preallocated.teardown token argument must be a "
  4550. "llvm.call.preallocated.setup");
  4551. break;
  4552. }
  4553. case Intrinsic::gcroot:
  4554. case Intrinsic::gcwrite:
  4555. case Intrinsic::gcread:
  4556. if (ID == Intrinsic::gcroot) {
  4557. AllocaInst *AI =
  4558. dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
  4559. Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
  4560. Check(isa<Constant>(Call.getArgOperand(1)),
  4561. "llvm.gcroot parameter #2 must be a constant.", Call);
  4562. if (!AI->getAllocatedType()->isPointerTy()) {
  4563. Check(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
  4564. "llvm.gcroot parameter #1 must either be a pointer alloca, "
  4565. "or argument #2 must be a non-null constant.",
  4566. Call);
  4567. }
  4568. }
  4569. Check(Call.getParent()->getParent()->hasGC(),
  4570. "Enclosing function does not use GC.", Call);
  4571. break;
  4572. case Intrinsic::init_trampoline:
  4573. Check(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
  4574. "llvm.init_trampoline parameter #2 must resolve to a function.",
  4575. Call);
  4576. break;
  4577. case Intrinsic::prefetch:
  4578. Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
  4579. "rw argument to llvm.prefetch must be 0-1", Call);
  4580. Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
  4581. "locality argument to llvm.prefetch must be 0-4", Call);
  4582. Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
  4583. "cache type argument to llvm.prefetch must be 0-1", Call);
  4584. break;
  4585. case Intrinsic::stackprotector:
  4586. Check(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
  4587. "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
  4588. break;
  4589. case Intrinsic::localescape: {
  4590. BasicBlock *BB = Call.getParent();
  4591. Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
  4592. Call);
  4593. Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
  4594. Call);
  4595. for (Value *Arg : Call.args()) {
  4596. if (isa<ConstantPointerNull>(Arg))
  4597. continue; // Null values are allowed as placeholders.
  4598. auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
  4599. Check(AI && AI->isStaticAlloca(),
  4600. "llvm.localescape only accepts static allocas", Call);
  4601. }
  4602. FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
  4603. SawFrameEscape = true;
  4604. break;
  4605. }
  4606. case Intrinsic::localrecover: {
  4607. Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
  4608. Function *Fn = dyn_cast<Function>(FnArg);
  4609. Check(Fn && !Fn->isDeclaration(),
  4610. "llvm.localrecover first "
  4611. "argument must be function defined in this module",
  4612. Call);
  4613. auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
  4614. auto &Entry = FrameEscapeInfo[Fn];
  4615. Entry.second = unsigned(
  4616. std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
  4617. break;
  4618. }
  4619. case Intrinsic::experimental_gc_statepoint:
  4620. if (auto *CI = dyn_cast<CallInst>(&Call))
  4621. Check(!CI->isInlineAsm(),
  4622. "gc.statepoint support for inline assembly unimplemented", CI);
  4623. Check(Call.getParent()->getParent()->hasGC(),
  4624. "Enclosing function does not use GC.", Call);
  4625. verifyStatepoint(Call);
  4626. break;
  4627. case Intrinsic::experimental_gc_result: {
  4628. Check(Call.getParent()->getParent()->hasGC(),
  4629. "Enclosing function does not use GC.", Call);
  4630. auto *Statepoint = Call.getArgOperand(0);
  4631. if (isa<UndefValue>(Statepoint))
  4632. break;
  4633. // Are we tied to a statepoint properly?
  4634. const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
  4635. const Function *StatepointFn =
  4636. StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
  4637. Check(StatepointFn && StatepointFn->isDeclaration() &&
  4638. StatepointFn->getIntrinsicID() ==
  4639. Intrinsic::experimental_gc_statepoint,
  4640. "gc.result operand #1 must be from a statepoint", Call,
  4641. Call.getArgOperand(0));
  4642. // Check that result type matches wrapped callee.
  4643. auto *TargetFuncType =
  4644. cast<FunctionType>(StatepointCall->getParamElementType(2));
  4645. Check(Call.getType() == TargetFuncType->getReturnType(),
  4646. "gc.result result type does not match wrapped callee", Call);
  4647. break;
  4648. }
  4649. case Intrinsic::experimental_gc_relocate: {
  4650. Check(Call.arg_size() == 3, "wrong number of arguments", Call);
  4651. Check(isa<PointerType>(Call.getType()->getScalarType()),
  4652. "gc.relocate must return a pointer or a vector of pointers", Call);
  4653. // Check that this relocate is correctly tied to the statepoint
  4654. // This is case for relocate on the unwinding path of an invoke statepoint
  4655. if (LandingPadInst *LandingPad =
  4656. dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
  4657. const BasicBlock *InvokeBB =
  4658. LandingPad->getParent()->getUniquePredecessor();
  4659. // Landingpad relocates should have only one predecessor with invoke
  4660. // statepoint terminator
  4661. Check(InvokeBB, "safepoints should have unique landingpads",
  4662. LandingPad->getParent());
  4663. Check(InvokeBB->getTerminator(), "safepoint block should be well formed",
  4664. InvokeBB);
  4665. Check(isa<GCStatepointInst>(InvokeBB->getTerminator()),
  4666. "gc relocate should be linked to a statepoint", InvokeBB);
  4667. } else {
  4668. // In all other cases relocate should be tied to the statepoint directly.
  4669. // This covers relocates on a normal return path of invoke statepoint and
  4670. // relocates of a call statepoint.
  4671. auto *Token = Call.getArgOperand(0);
  4672. Check(isa<GCStatepointInst>(Token) || isa<UndefValue>(Token),
  4673. "gc relocate is incorrectly tied to the statepoint", Call, Token);
  4674. }
  4675. // Verify rest of the relocate arguments.
  4676. const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
  4677. // Both the base and derived must be piped through the safepoint.
  4678. Value *Base = Call.getArgOperand(1);
  4679. Check(isa<ConstantInt>(Base),
  4680. "gc.relocate operand #2 must be integer offset", Call);
  4681. Value *Derived = Call.getArgOperand(2);
  4682. Check(isa<ConstantInt>(Derived),
  4683. "gc.relocate operand #3 must be integer offset", Call);
  4684. const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
  4685. const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
  4686. // Check the bounds
  4687. if (isa<UndefValue>(StatepointCall))
  4688. break;
  4689. if (auto Opt = cast<GCStatepointInst>(StatepointCall)
  4690. .getOperandBundle(LLVMContext::OB_gc_live)) {
  4691. Check(BaseIndex < Opt->Inputs.size(),
  4692. "gc.relocate: statepoint base index out of bounds", Call);
  4693. Check(DerivedIndex < Opt->Inputs.size(),
  4694. "gc.relocate: statepoint derived index out of bounds", Call);
  4695. }
  4696. // Relocated value must be either a pointer type or vector-of-pointer type,
  4697. // but gc_relocate does not need to return the same pointer type as the
  4698. // relocated pointer. It can be casted to the correct type later if it's
  4699. // desired. However, they must have the same address space and 'vectorness'
  4700. GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
  4701. auto *ResultType = Call.getType();
  4702. auto *DerivedType = Relocate.getDerivedPtr()->getType();
  4703. auto *BaseType = Relocate.getBasePtr()->getType();
  4704. Check(BaseType->isPtrOrPtrVectorTy(),
  4705. "gc.relocate: relocated value must be a pointer", Call);
  4706. Check(DerivedType->isPtrOrPtrVectorTy(),
  4707. "gc.relocate: relocated value must be a pointer", Call);
  4708. Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
  4709. "gc.relocate: vector relocates to vector and pointer to pointer",
  4710. Call);
  4711. Check(
  4712. ResultType->getPointerAddressSpace() ==
  4713. DerivedType->getPointerAddressSpace(),
  4714. "gc.relocate: relocating a pointer shouldn't change its address space",
  4715. Call);
  4716. auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
  4717. Check(GC, "gc.relocate: calling function must have GCStrategy",
  4718. Call.getFunction());
  4719. if (GC) {
  4720. auto isGCPtr = [&GC](Type *PTy) {
  4721. return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
  4722. };
  4723. Check(isGCPtr(ResultType), "gc.relocate: must return gc pointer", Call);
  4724. Check(isGCPtr(BaseType),
  4725. "gc.relocate: relocated value must be a gc pointer", Call);
  4726. Check(isGCPtr(DerivedType),
  4727. "gc.relocate: relocated value must be a gc pointer", Call);
  4728. }
  4729. break;
  4730. }
  4731. case Intrinsic::eh_exceptioncode:
  4732. case Intrinsic::eh_exceptionpointer: {
  4733. Check(isa<CatchPadInst>(Call.getArgOperand(0)),
  4734. "eh.exceptionpointer argument must be a catchpad", Call);
  4735. break;
  4736. }
  4737. case Intrinsic::get_active_lane_mask: {
  4738. Check(Call.getType()->isVectorTy(),
  4739. "get_active_lane_mask: must return a "
  4740. "vector",
  4741. Call);
  4742. auto *ElemTy = Call.getType()->getScalarType();
  4743. Check(ElemTy->isIntegerTy(1),
  4744. "get_active_lane_mask: element type is not "
  4745. "i1",
  4746. Call);
  4747. break;
  4748. }
  4749. case Intrinsic::masked_load: {
  4750. Check(Call.getType()->isVectorTy(), "masked_load: must return a vector",
  4751. Call);
  4752. Value *Ptr = Call.getArgOperand(0);
  4753. ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
  4754. Value *Mask = Call.getArgOperand(2);
  4755. Value *PassThru = Call.getArgOperand(3);
  4756. Check(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
  4757. Call);
  4758. Check(Alignment->getValue().isPowerOf2(),
  4759. "masked_load: alignment must be a power of 2", Call);
  4760. PointerType *PtrTy = cast<PointerType>(Ptr->getType());
  4761. Check(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType()),
  4762. "masked_load: return must match pointer type", Call);
  4763. Check(PassThru->getType() == Call.getType(),
  4764. "masked_load: pass through and return type must match", Call);
  4765. Check(cast<VectorType>(Mask->getType())->getElementCount() ==
  4766. cast<VectorType>(Call.getType())->getElementCount(),
  4767. "masked_load: vector mask must be same length as return", Call);
  4768. break;
  4769. }
  4770. case Intrinsic::masked_store: {
  4771. Value *Val = Call.getArgOperand(0);
  4772. Value *Ptr = Call.getArgOperand(1);
  4773. ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
  4774. Value *Mask = Call.getArgOperand(3);
  4775. Check(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
  4776. Call);
  4777. Check(Alignment->getValue().isPowerOf2(),
  4778. "masked_store: alignment must be a power of 2", Call);
  4779. PointerType *PtrTy = cast<PointerType>(Ptr->getType());
  4780. Check(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType()),
  4781. "masked_store: storee must match pointer type", Call);
  4782. Check(cast<VectorType>(Mask->getType())->getElementCount() ==
  4783. cast<VectorType>(Val->getType())->getElementCount(),
  4784. "masked_store: vector mask must be same length as value", Call);
  4785. break;
  4786. }
  4787. case Intrinsic::masked_gather: {
  4788. const APInt &Alignment =
  4789. cast<ConstantInt>(Call.getArgOperand(1))->getValue();
  4790. Check(Alignment.isZero() || Alignment.isPowerOf2(),
  4791. "masked_gather: alignment must be 0 or a power of 2", Call);
  4792. break;
  4793. }
  4794. case Intrinsic::masked_scatter: {
  4795. const APInt &Alignment =
  4796. cast<ConstantInt>(Call.getArgOperand(2))->getValue();
  4797. Check(Alignment.isZero() || Alignment.isPowerOf2(),
  4798. "masked_scatter: alignment must be 0 or a power of 2", Call);
  4799. break;
  4800. }
  4801. case Intrinsic::experimental_guard: {
  4802. Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
  4803. Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
  4804. "experimental_guard must have exactly one "
  4805. "\"deopt\" operand bundle");
  4806. break;
  4807. }
  4808. case Intrinsic::experimental_deoptimize: {
  4809. Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
  4810. Call);
  4811. Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
  4812. "experimental_deoptimize must have exactly one "
  4813. "\"deopt\" operand bundle");
  4814. Check(Call.getType() == Call.getFunction()->getReturnType(),
  4815. "experimental_deoptimize return type must match caller return type");
  4816. if (isa<CallInst>(Call)) {
  4817. auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
  4818. Check(RI,
  4819. "calls to experimental_deoptimize must be followed by a return");
  4820. if (!Call.getType()->isVoidTy() && RI)
  4821. Check(RI->getReturnValue() == &Call,
  4822. "calls to experimental_deoptimize must be followed by a return "
  4823. "of the value computed by experimental_deoptimize");
  4824. }
  4825. break;
  4826. }
  4827. case Intrinsic::vector_reduce_and:
  4828. case Intrinsic::vector_reduce_or:
  4829. case Intrinsic::vector_reduce_xor:
  4830. case Intrinsic::vector_reduce_add:
  4831. case Intrinsic::vector_reduce_mul:
  4832. case Intrinsic::vector_reduce_smax:
  4833. case Intrinsic::vector_reduce_smin:
  4834. case Intrinsic::vector_reduce_umax:
  4835. case Intrinsic::vector_reduce_umin: {
  4836. Type *ArgTy = Call.getArgOperand(0)->getType();
  4837. Check(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
  4838. "Intrinsic has incorrect argument type!");
  4839. break;
  4840. }
  4841. case Intrinsic::vector_reduce_fmax:
  4842. case Intrinsic::vector_reduce_fmin: {
  4843. Type *ArgTy = Call.getArgOperand(0)->getType();
  4844. Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
  4845. "Intrinsic has incorrect argument type!");
  4846. break;
  4847. }
  4848. case Intrinsic::vector_reduce_fadd:
  4849. case Intrinsic::vector_reduce_fmul: {
  4850. // Unlike the other reductions, the first argument is a start value. The
  4851. // second argument is the vector to be reduced.
  4852. Type *ArgTy = Call.getArgOperand(1)->getType();
  4853. Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
  4854. "Intrinsic has incorrect argument type!");
  4855. break;
  4856. }
  4857. case Intrinsic::smul_fix:
  4858. case Intrinsic::smul_fix_sat:
  4859. case Intrinsic::umul_fix:
  4860. case Intrinsic::umul_fix_sat:
  4861. case Intrinsic::sdiv_fix:
  4862. case Intrinsic::sdiv_fix_sat:
  4863. case Intrinsic::udiv_fix:
  4864. case Intrinsic::udiv_fix_sat: {
  4865. Value *Op1 = Call.getArgOperand(0);
  4866. Value *Op2 = Call.getArgOperand(1);
  4867. Check(Op1->getType()->isIntOrIntVectorTy(),
  4868. "first operand of [us][mul|div]_fix[_sat] must be an int type or "
  4869. "vector of ints");
  4870. Check(Op2->getType()->isIntOrIntVectorTy(),
  4871. "second operand of [us][mul|div]_fix[_sat] must be an int type or "
  4872. "vector of ints");
  4873. auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
  4874. Check(Op3->getType()->getBitWidth() <= 32,
  4875. "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
  4876. if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
  4877. ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
  4878. Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
  4879. "the scale of s[mul|div]_fix[_sat] must be less than the width of "
  4880. "the operands");
  4881. } else {
  4882. Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
  4883. "the scale of u[mul|div]_fix[_sat] must be less than or equal "
  4884. "to the width of the operands");
  4885. }
  4886. break;
  4887. }
  4888. case Intrinsic::lround:
  4889. case Intrinsic::llround:
  4890. case Intrinsic::lrint:
  4891. case Intrinsic::llrint: {
  4892. Type *ValTy = Call.getArgOperand(0)->getType();
  4893. Type *ResultTy = Call.getType();
  4894. Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
  4895. "Intrinsic does not support vectors", &Call);
  4896. break;
  4897. }
  4898. case Intrinsic::bswap: {
  4899. Type *Ty = Call.getType();
  4900. unsigned Size = Ty->getScalarSizeInBits();
  4901. Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
  4902. break;
  4903. }
  4904. case Intrinsic::invariant_start: {
  4905. ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
  4906. Check(InvariantSize &&
  4907. (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
  4908. "invariant_start parameter must be -1, 0 or a positive number",
  4909. &Call);
  4910. break;
  4911. }
  4912. case Intrinsic::matrix_multiply:
  4913. case Intrinsic::matrix_transpose:
  4914. case Intrinsic::matrix_column_major_load:
  4915. case Intrinsic::matrix_column_major_store: {
  4916. Function *IF = Call.getCalledFunction();
  4917. ConstantInt *Stride = nullptr;
  4918. ConstantInt *NumRows;
  4919. ConstantInt *NumColumns;
  4920. VectorType *ResultTy;
  4921. Type *Op0ElemTy = nullptr;
  4922. Type *Op1ElemTy = nullptr;
  4923. switch (ID) {
  4924. case Intrinsic::matrix_multiply:
  4925. NumRows = cast<ConstantInt>(Call.getArgOperand(2));
  4926. NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
  4927. ResultTy = cast<VectorType>(Call.getType());
  4928. Op0ElemTy =
  4929. cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
  4930. Op1ElemTy =
  4931. cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
  4932. break;
  4933. case Intrinsic::matrix_transpose:
  4934. NumRows = cast<ConstantInt>(Call.getArgOperand(1));
  4935. NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
  4936. ResultTy = cast<VectorType>(Call.getType());
  4937. Op0ElemTy =
  4938. cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
  4939. break;
  4940. case Intrinsic::matrix_column_major_load: {
  4941. Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
  4942. NumRows = cast<ConstantInt>(Call.getArgOperand(3));
  4943. NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
  4944. ResultTy = cast<VectorType>(Call.getType());
  4945. PointerType *Op0PtrTy =
  4946. cast<PointerType>(Call.getArgOperand(0)->getType());
  4947. if (!Op0PtrTy->isOpaque())
  4948. Op0ElemTy = Op0PtrTy->getNonOpaquePointerElementType();
  4949. break;
  4950. }
  4951. case Intrinsic::matrix_column_major_store: {
  4952. Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
  4953. NumRows = cast<ConstantInt>(Call.getArgOperand(4));
  4954. NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
  4955. ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
  4956. Op0ElemTy =
  4957. cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
  4958. PointerType *Op1PtrTy =
  4959. cast<PointerType>(Call.getArgOperand(1)->getType());
  4960. if (!Op1PtrTy->isOpaque())
  4961. Op1ElemTy = Op1PtrTy->getNonOpaquePointerElementType();
  4962. break;
  4963. }
  4964. default:
  4965. llvm_unreachable("unexpected intrinsic");
  4966. }
  4967. Check(ResultTy->getElementType()->isIntegerTy() ||
  4968. ResultTy->getElementType()->isFloatingPointTy(),
  4969. "Result type must be an integer or floating-point type!", IF);
  4970. if (Op0ElemTy)
  4971. Check(ResultTy->getElementType() == Op0ElemTy,
  4972. "Vector element type mismatch of the result and first operand "
  4973. "vector!",
  4974. IF);
  4975. if (Op1ElemTy)
  4976. Check(ResultTy->getElementType() == Op1ElemTy,
  4977. "Vector element type mismatch of the result and second operand "
  4978. "vector!",
  4979. IF);
  4980. Check(cast<FixedVectorType>(ResultTy)->getNumElements() ==
  4981. NumRows->getZExtValue() * NumColumns->getZExtValue(),
  4982. "Result of a matrix operation does not fit in the returned vector!");
  4983. if (Stride)
  4984. Check(Stride->getZExtValue() >= NumRows->getZExtValue(),
  4985. "Stride must be greater or equal than the number of rows!", IF);
  4986. break;
  4987. }
  4988. case Intrinsic::experimental_vector_splice: {
  4989. VectorType *VecTy = cast<VectorType>(Call.getType());
  4990. int64_t Idx = cast<ConstantInt>(Call.getArgOperand(2))->getSExtValue();
  4991. int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
  4992. if (Call.getParent() && Call.getParent()->getParent()) {
  4993. AttributeList Attrs = Call.getParent()->getParent()->getAttributes();
  4994. if (Attrs.hasFnAttr(Attribute::VScaleRange))
  4995. KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
  4996. }
  4997. Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
  4998. (Idx >= 0 && Idx < KnownMinNumElements),
  4999. "The splice index exceeds the range [-VL, VL-1] where VL is the "
  5000. "known minimum number of elements in the vector. For scalable "
  5001. "vectors the minimum number of elements is determined from "
  5002. "vscale_range.",
  5003. &Call);
  5004. break;
  5005. }
  5006. case Intrinsic::experimental_stepvector: {
  5007. VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
  5008. Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
  5009. VecTy->getScalarSizeInBits() >= 8,
  5010. "experimental_stepvector only supported for vectors of integers "
  5011. "with a bitwidth of at least 8.",
  5012. &Call);
  5013. break;
  5014. }
  5015. case Intrinsic::vector_insert: {
  5016. Value *Vec = Call.getArgOperand(0);
  5017. Value *SubVec = Call.getArgOperand(1);
  5018. Value *Idx = Call.getArgOperand(2);
  5019. unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
  5020. VectorType *VecTy = cast<VectorType>(Vec->getType());
  5021. VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
  5022. ElementCount VecEC = VecTy->getElementCount();
  5023. ElementCount SubVecEC = SubVecTy->getElementCount();
  5024. Check(VecTy->getElementType() == SubVecTy->getElementType(),
  5025. "vector_insert parameters must have the same element "
  5026. "type.",
  5027. &Call);
  5028. Check(IdxN % SubVecEC.getKnownMinValue() == 0,
  5029. "vector_insert index must be a constant multiple of "
  5030. "the subvector's known minimum vector length.");
  5031. // If this insertion is not the 'mixed' case where a fixed vector is
  5032. // inserted into a scalable vector, ensure that the insertion of the
  5033. // subvector does not overrun the parent vector.
  5034. if (VecEC.isScalable() == SubVecEC.isScalable()) {
  5035. Check(IdxN < VecEC.getKnownMinValue() &&
  5036. IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
  5037. "subvector operand of vector_insert would overrun the "
  5038. "vector being inserted into.");
  5039. }
  5040. break;
  5041. }
  5042. case Intrinsic::vector_extract: {
  5043. Value *Vec = Call.getArgOperand(0);
  5044. Value *Idx = Call.getArgOperand(1);
  5045. unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
  5046. VectorType *ResultTy = cast<VectorType>(Call.getType());
  5047. VectorType *VecTy = cast<VectorType>(Vec->getType());
  5048. ElementCount VecEC = VecTy->getElementCount();
  5049. ElementCount ResultEC = ResultTy->getElementCount();
  5050. Check(ResultTy->getElementType() == VecTy->getElementType(),
  5051. "vector_extract result must have the same element "
  5052. "type as the input vector.",
  5053. &Call);
  5054. Check(IdxN % ResultEC.getKnownMinValue() == 0,
  5055. "vector_extract index must be a constant multiple of "
  5056. "the result type's known minimum vector length.");
  5057. // If this extraction is not the 'mixed' case where a fixed vector is is
  5058. // extracted from a scalable vector, ensure that the extraction does not
  5059. // overrun the parent vector.
  5060. if (VecEC.isScalable() == ResultEC.isScalable()) {
  5061. Check(IdxN < VecEC.getKnownMinValue() &&
  5062. IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
  5063. "vector_extract would overrun.");
  5064. }
  5065. break;
  5066. }
  5067. case Intrinsic::experimental_noalias_scope_decl: {
  5068. NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
  5069. break;
  5070. }
  5071. case Intrinsic::preserve_array_access_index:
  5072. case Intrinsic::preserve_struct_access_index:
  5073. case Intrinsic::aarch64_ldaxr:
  5074. case Intrinsic::aarch64_ldxr:
  5075. case Intrinsic::arm_ldaex:
  5076. case Intrinsic::arm_ldrex: {
  5077. Type *ElemTy = Call.getParamElementType(0);
  5078. Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
  5079. &Call);
  5080. break;
  5081. }
  5082. case Intrinsic::aarch64_stlxr:
  5083. case Intrinsic::aarch64_stxr:
  5084. case Intrinsic::arm_stlex:
  5085. case Intrinsic::arm_strex: {
  5086. Type *ElemTy = Call.getAttributes().getParamElementType(1);
  5087. Check(ElemTy,
  5088. "Intrinsic requires elementtype attribute on second argument.",
  5089. &Call);
  5090. break;
  5091. }
  5092. case Intrinsic::aarch64_prefetch: {
  5093. Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
  5094. "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
  5095. Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
  5096. "target argument to llvm.aarch64.prefetch must be 0-3", Call);
  5097. Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
  5098. "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
  5099. Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
  5100. "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
  5101. break;
  5102. }
  5103. };
  5104. }
  5105. /// Carefully grab the subprogram from a local scope.
  5106. ///
  5107. /// This carefully grabs the subprogram from a local scope, avoiding the
  5108. /// built-in assertions that would typically fire.
  5109. static DISubprogram *getSubprogram(Metadata *LocalScope) {
  5110. if (!LocalScope)
  5111. return nullptr;
  5112. if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
  5113. return SP;
  5114. if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
  5115. return getSubprogram(LB->getRawScope());
  5116. // Just return null; broken scope chains are checked elsewhere.
  5117. assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
  5118. return nullptr;
  5119. }
  5120. void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
  5121. if (auto *VPCast = dyn_cast<VPCastIntrinsic>(&VPI)) {
  5122. auto *RetTy = cast<VectorType>(VPCast->getType());
  5123. auto *ValTy = cast<VectorType>(VPCast->getOperand(0)->getType());
  5124. Check(RetTy->getElementCount() == ValTy->getElementCount(),
  5125. "VP cast intrinsic first argument and result vector lengths must be "
  5126. "equal",
  5127. *VPCast);
  5128. switch (VPCast->getIntrinsicID()) {
  5129. default:
  5130. llvm_unreachable("Unknown VP cast intrinsic");
  5131. case Intrinsic::vp_trunc:
  5132. Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
  5133. "llvm.vp.trunc intrinsic first argument and result element type "
  5134. "must be integer",
  5135. *VPCast);
  5136. Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
  5137. "llvm.vp.trunc intrinsic the bit size of first argument must be "
  5138. "larger than the bit size of the return type",
  5139. *VPCast);
  5140. break;
  5141. case Intrinsic::vp_zext:
  5142. case Intrinsic::vp_sext:
  5143. Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
  5144. "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
  5145. "element type must be integer",
  5146. *VPCast);
  5147. Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
  5148. "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
  5149. "argument must be smaller than the bit size of the return type",
  5150. *VPCast);
  5151. break;
  5152. case Intrinsic::vp_fptoui:
  5153. case Intrinsic::vp_fptosi:
  5154. Check(
  5155. RetTy->isIntOrIntVectorTy() && ValTy->isFPOrFPVectorTy(),
  5156. "llvm.vp.fptoui or llvm.vp.fptosi intrinsic first argument element "
  5157. "type must be floating-point and result element type must be integer",
  5158. *VPCast);
  5159. break;
  5160. case Intrinsic::vp_uitofp:
  5161. case Intrinsic::vp_sitofp:
  5162. Check(
  5163. RetTy->isFPOrFPVectorTy() && ValTy->isIntOrIntVectorTy(),
  5164. "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
  5165. "type must be integer and result element type must be floating-point",
  5166. *VPCast);
  5167. break;
  5168. case Intrinsic::vp_fptrunc:
  5169. Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
  5170. "llvm.vp.fptrunc intrinsic first argument and result element type "
  5171. "must be floating-point",
  5172. *VPCast);
  5173. Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
  5174. "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
  5175. "larger than the bit size of the return type",
  5176. *VPCast);
  5177. break;
  5178. case Intrinsic::vp_fpext:
  5179. Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
  5180. "llvm.vp.fpext intrinsic first argument and result element type "
  5181. "must be floating-point",
  5182. *VPCast);
  5183. Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
  5184. "llvm.vp.fpext intrinsic the bit size of first argument must be "
  5185. "smaller than the bit size of the return type",
  5186. *VPCast);
  5187. break;
  5188. case Intrinsic::vp_ptrtoint:
  5189. Check(RetTy->isIntOrIntVectorTy() && ValTy->isPtrOrPtrVectorTy(),
  5190. "llvm.vp.ptrtoint intrinsic first argument element type must be "
  5191. "pointer and result element type must be integer",
  5192. *VPCast);
  5193. break;
  5194. case Intrinsic::vp_inttoptr:
  5195. Check(RetTy->isPtrOrPtrVectorTy() && ValTy->isIntOrIntVectorTy(),
  5196. "llvm.vp.inttoptr intrinsic first argument element type must be "
  5197. "integer and result element type must be pointer",
  5198. *VPCast);
  5199. break;
  5200. }
  5201. }
  5202. if (VPI.getIntrinsicID() == Intrinsic::vp_fcmp) {
  5203. auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
  5204. Check(CmpInst::isFPPredicate(Pred),
  5205. "invalid predicate for VP FP comparison intrinsic", &VPI);
  5206. }
  5207. if (VPI.getIntrinsicID() == Intrinsic::vp_icmp) {
  5208. auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
  5209. Check(CmpInst::isIntPredicate(Pred),
  5210. "invalid predicate for VP integer comparison intrinsic", &VPI);
  5211. }
  5212. }
  5213. void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
  5214. unsigned NumOperands;
  5215. bool HasRoundingMD;
  5216. switch (FPI.getIntrinsicID()) {
  5217. #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
  5218. case Intrinsic::INTRINSIC: \
  5219. NumOperands = NARG; \
  5220. HasRoundingMD = ROUND_MODE; \
  5221. break;
  5222. #include "llvm/IR/ConstrainedOps.def"
  5223. default:
  5224. llvm_unreachable("Invalid constrained FP intrinsic!");
  5225. }
  5226. NumOperands += (1 + HasRoundingMD);
  5227. // Compare intrinsics carry an extra predicate metadata operand.
  5228. if (isa<ConstrainedFPCmpIntrinsic>(FPI))
  5229. NumOperands += 1;
  5230. Check((FPI.arg_size() == NumOperands),
  5231. "invalid arguments for constrained FP intrinsic", &FPI);
  5232. switch (FPI.getIntrinsicID()) {
  5233. case Intrinsic::experimental_constrained_lrint:
  5234. case Intrinsic::experimental_constrained_llrint: {
  5235. Type *ValTy = FPI.getArgOperand(0)->getType();
  5236. Type *ResultTy = FPI.getType();
  5237. Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
  5238. "Intrinsic does not support vectors", &FPI);
  5239. }
  5240. break;
  5241. case Intrinsic::experimental_constrained_lround:
  5242. case Intrinsic::experimental_constrained_llround: {
  5243. Type *ValTy = FPI.getArgOperand(0)->getType();
  5244. Type *ResultTy = FPI.getType();
  5245. Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
  5246. "Intrinsic does not support vectors", &FPI);
  5247. break;
  5248. }
  5249. case Intrinsic::experimental_constrained_fcmp:
  5250. case Intrinsic::experimental_constrained_fcmps: {
  5251. auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
  5252. Check(CmpInst::isFPPredicate(Pred),
  5253. "invalid predicate for constrained FP comparison intrinsic", &FPI);
  5254. break;
  5255. }
  5256. case Intrinsic::experimental_constrained_fptosi:
  5257. case Intrinsic::experimental_constrained_fptoui: {
  5258. Value *Operand = FPI.getArgOperand(0);
  5259. uint64_t NumSrcElem = 0;
  5260. Check(Operand->getType()->isFPOrFPVectorTy(),
  5261. "Intrinsic first argument must be floating point", &FPI);
  5262. if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
  5263. NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
  5264. }
  5265. Operand = &FPI;
  5266. Check((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
  5267. "Intrinsic first argument and result disagree on vector use", &FPI);
  5268. Check(Operand->getType()->isIntOrIntVectorTy(),
  5269. "Intrinsic result must be an integer", &FPI);
  5270. if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
  5271. Check(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
  5272. "Intrinsic first argument and result vector lengths must be equal",
  5273. &FPI);
  5274. }
  5275. }
  5276. break;
  5277. case Intrinsic::experimental_constrained_sitofp:
  5278. case Intrinsic::experimental_constrained_uitofp: {
  5279. Value *Operand = FPI.getArgOperand(0);
  5280. uint64_t NumSrcElem = 0;
  5281. Check(Operand->getType()->isIntOrIntVectorTy(),
  5282. "Intrinsic first argument must be integer", &FPI);
  5283. if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
  5284. NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
  5285. }
  5286. Operand = &FPI;
  5287. Check((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
  5288. "Intrinsic first argument and result disagree on vector use", &FPI);
  5289. Check(Operand->getType()->isFPOrFPVectorTy(),
  5290. "Intrinsic result must be a floating point", &FPI);
  5291. if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
  5292. Check(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
  5293. "Intrinsic first argument and result vector lengths must be equal",
  5294. &FPI);
  5295. }
  5296. } break;
  5297. case Intrinsic::experimental_constrained_fptrunc:
  5298. case Intrinsic::experimental_constrained_fpext: {
  5299. Value *Operand = FPI.getArgOperand(0);
  5300. Type *OperandTy = Operand->getType();
  5301. Value *Result = &FPI;
  5302. Type *ResultTy = Result->getType();
  5303. Check(OperandTy->isFPOrFPVectorTy(),
  5304. "Intrinsic first argument must be FP or FP vector", &FPI);
  5305. Check(ResultTy->isFPOrFPVectorTy(),
  5306. "Intrinsic result must be FP or FP vector", &FPI);
  5307. Check(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
  5308. "Intrinsic first argument and result disagree on vector use", &FPI);
  5309. if (OperandTy->isVectorTy()) {
  5310. Check(cast<FixedVectorType>(OperandTy)->getNumElements() ==
  5311. cast<FixedVectorType>(ResultTy)->getNumElements(),
  5312. "Intrinsic first argument and result vector lengths must be equal",
  5313. &FPI);
  5314. }
  5315. if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
  5316. Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
  5317. "Intrinsic first argument's type must be larger than result type",
  5318. &FPI);
  5319. } else {
  5320. Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
  5321. "Intrinsic first argument's type must be smaller than result type",
  5322. &FPI);
  5323. }
  5324. }
  5325. break;
  5326. default:
  5327. break;
  5328. }
  5329. // If a non-metadata argument is passed in a metadata slot then the
  5330. // error will be caught earlier when the incorrect argument doesn't
  5331. // match the specification in the intrinsic call table. Thus, no
  5332. // argument type check is needed here.
  5333. Check(FPI.getExceptionBehavior().has_value(),
  5334. "invalid exception behavior argument", &FPI);
  5335. if (HasRoundingMD) {
  5336. Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
  5337. &FPI);
  5338. }
  5339. }
  5340. void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
  5341. auto *MD = DII.getRawLocation();
  5342. CheckDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
  5343. (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
  5344. "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
  5345. CheckDI(isa<DILocalVariable>(DII.getRawVariable()),
  5346. "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
  5347. DII.getRawVariable());
  5348. CheckDI(isa<DIExpression>(DII.getRawExpression()),
  5349. "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
  5350. DII.getRawExpression());
  5351. if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&DII)) {
  5352. CheckDI(isa<DIAssignID>(DAI->getRawAssignID()),
  5353. "invalid llvm.dbg.assign intrinsic DIAssignID", &DII,
  5354. DAI->getRawAssignID());
  5355. const auto *RawAddr = DAI->getRawAddress();
  5356. CheckDI(
  5357. isa<ValueAsMetadata>(RawAddr) ||
  5358. (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
  5359. "invalid llvm.dbg.assign intrinsic address", &DII,
  5360. DAI->getRawAddress());
  5361. CheckDI(isa<DIExpression>(DAI->getRawAddressExpression()),
  5362. "invalid llvm.dbg.assign intrinsic address expression", &DII,
  5363. DAI->getRawAddressExpression());
  5364. // All of the linked instructions should be in the same function as DII.
  5365. for (Instruction *I : at::getAssignmentInsts(DAI))
  5366. CheckDI(DAI->getFunction() == I->getFunction(),
  5367. "inst not in same function as dbg.assign", I, DAI);
  5368. }
  5369. // Ignore broken !dbg attachments; they're checked elsewhere.
  5370. if (MDNode *N = DII.getDebugLoc().getAsMDNode())
  5371. if (!isa<DILocation>(N))
  5372. return;
  5373. BasicBlock *BB = DII.getParent();
  5374. Function *F = BB ? BB->getParent() : nullptr;
  5375. // The scopes for variables and !dbg attachments must agree.
  5376. DILocalVariable *Var = DII.getVariable();
  5377. DILocation *Loc = DII.getDebugLoc();
  5378. CheckDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
  5379. &DII, BB, F);
  5380. DISubprogram *VarSP = getSubprogram(Var->getRawScope());
  5381. DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
  5382. if (!VarSP || !LocSP)
  5383. return; // Broken scope chains are checked elsewhere.
  5384. CheckDI(VarSP == LocSP,
  5385. "mismatched subprogram between llvm.dbg." + Kind +
  5386. " variable and !dbg attachment",
  5387. &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
  5388. Loc->getScope()->getSubprogram());
  5389. // This check is redundant with one in visitLocalVariable().
  5390. CheckDI(isType(Var->getRawType()), "invalid type ref", Var,
  5391. Var->getRawType());
  5392. verifyFnArgs(DII);
  5393. }
  5394. void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
  5395. CheckDI(isa<DILabel>(DLI.getRawLabel()),
  5396. "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
  5397. DLI.getRawLabel());
  5398. // Ignore broken !dbg attachments; they're checked elsewhere.
  5399. if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
  5400. if (!isa<DILocation>(N))
  5401. return;
  5402. BasicBlock *BB = DLI.getParent();
  5403. Function *F = BB ? BB->getParent() : nullptr;
  5404. // The scopes for variables and !dbg attachments must agree.
  5405. DILabel *Label = DLI.getLabel();
  5406. DILocation *Loc = DLI.getDebugLoc();
  5407. Check(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", &DLI,
  5408. BB, F);
  5409. DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
  5410. DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
  5411. if (!LabelSP || !LocSP)
  5412. return;
  5413. CheckDI(LabelSP == LocSP,
  5414. "mismatched subprogram between llvm.dbg." + Kind +
  5415. " label and !dbg attachment",
  5416. &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
  5417. Loc->getScope()->getSubprogram());
  5418. }
  5419. void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
  5420. DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
  5421. DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
  5422. // We don't know whether this intrinsic verified correctly.
  5423. if (!V || !E || !E->isValid())
  5424. return;
  5425. // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
  5426. auto Fragment = E->getFragmentInfo();
  5427. if (!Fragment)
  5428. return;
  5429. // The frontend helps out GDB by emitting the members of local anonymous
  5430. // unions as artificial local variables with shared storage. When SROA splits
  5431. // the storage for artificial local variables that are smaller than the entire
  5432. // union, the overhang piece will be outside of the allotted space for the
  5433. // variable and this check fails.
  5434. // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
  5435. if (V->isArtificial())
  5436. return;
  5437. verifyFragmentExpression(*V, *Fragment, &I);
  5438. }
  5439. template <typename ValueOrMetadata>
  5440. void Verifier::verifyFragmentExpression(const DIVariable &V,
  5441. DIExpression::FragmentInfo Fragment,
  5442. ValueOrMetadata *Desc) {
  5443. // If there's no size, the type is broken, but that should be checked
  5444. // elsewhere.
  5445. auto VarSize = V.getSizeInBits();
  5446. if (!VarSize)
  5447. return;
  5448. unsigned FragSize = Fragment.SizeInBits;
  5449. unsigned FragOffset = Fragment.OffsetInBits;
  5450. CheckDI(FragSize + FragOffset <= *VarSize,
  5451. "fragment is larger than or outside of variable", Desc, &V);
  5452. CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
  5453. }
  5454. void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
  5455. // This function does not take the scope of noninlined function arguments into
  5456. // account. Don't run it if current function is nodebug, because it may
  5457. // contain inlined debug intrinsics.
  5458. if (!HasDebugInfo)
  5459. return;
  5460. // For performance reasons only check non-inlined ones.
  5461. if (I.getDebugLoc()->getInlinedAt())
  5462. return;
  5463. DILocalVariable *Var = I.getVariable();
  5464. CheckDI(Var, "dbg intrinsic without variable");
  5465. unsigned ArgNo = Var->getArg();
  5466. if (!ArgNo)
  5467. return;
  5468. // Verify there are no duplicate function argument debug info entries.
  5469. // These will cause hard-to-debug assertions in the DWARF backend.
  5470. if (DebugFnArgs.size() < ArgNo)
  5471. DebugFnArgs.resize(ArgNo, nullptr);
  5472. auto *Prev = DebugFnArgs[ArgNo - 1];
  5473. DebugFnArgs[ArgNo - 1] = Var;
  5474. CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
  5475. Prev, Var);
  5476. }
  5477. void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
  5478. DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
  5479. // We don't know whether this intrinsic verified correctly.
  5480. if (!E || !E->isValid())
  5481. return;
  5482. CheckDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I);
  5483. }
  5484. void Verifier::verifyCompileUnits() {
  5485. // When more than one Module is imported into the same context, such as during
  5486. // an LTO build before linking the modules, ODR type uniquing may cause types
  5487. // to point to a different CU. This check does not make sense in this case.
  5488. if (M.getContext().isODRUniquingDebugTypes())
  5489. return;
  5490. auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
  5491. SmallPtrSet<const Metadata *, 2> Listed;
  5492. if (CUs)
  5493. Listed.insert(CUs->op_begin(), CUs->op_end());
  5494. for (const auto *CU : CUVisited)
  5495. CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
  5496. CUVisited.clear();
  5497. }
  5498. void Verifier::verifyDeoptimizeCallingConvs() {
  5499. if (DeoptimizeDeclarations.empty())
  5500. return;
  5501. const Function *First = DeoptimizeDeclarations[0];
  5502. for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
  5503. Check(First->getCallingConv() == F->getCallingConv(),
  5504. "All llvm.experimental.deoptimize declarations must have the same "
  5505. "calling convention",
  5506. First, F);
  5507. }
  5508. }
  5509. void Verifier::verifyAttachedCallBundle(const CallBase &Call,
  5510. const OperandBundleUse &BU) {
  5511. FunctionType *FTy = Call.getFunctionType();
  5512. Check((FTy->getReturnType()->isPointerTy() ||
  5513. (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
  5514. "a call with operand bundle \"clang.arc.attachedcall\" must call a "
  5515. "function returning a pointer or a non-returning function that has a "
  5516. "void return type",
  5517. Call);
  5518. Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
  5519. "operand bundle \"clang.arc.attachedcall\" requires one function as "
  5520. "an argument",
  5521. Call);
  5522. auto *Fn = cast<Function>(BU.Inputs.front());
  5523. Intrinsic::ID IID = Fn->getIntrinsicID();
  5524. if (IID) {
  5525. Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
  5526. IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
  5527. "invalid function argument", Call);
  5528. } else {
  5529. StringRef FnName = Fn->getName();
  5530. Check((FnName == "objc_retainAutoreleasedReturnValue" ||
  5531. FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
  5532. "invalid function argument", Call);
  5533. }
  5534. }
  5535. void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
  5536. bool HasSource = F.getSource().has_value();
  5537. if (!HasSourceDebugInfo.count(&U))
  5538. HasSourceDebugInfo[&U] = HasSource;
  5539. CheckDI(HasSource == HasSourceDebugInfo[&U],
  5540. "inconsistent use of embedded source");
  5541. }
  5542. void Verifier::verifyNoAliasScopeDecl() {
  5543. if (NoAliasScopeDecls.empty())
  5544. return;
  5545. // only a single scope must be declared at a time.
  5546. for (auto *II : NoAliasScopeDecls) {
  5547. assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
  5548. "Not a llvm.experimental.noalias.scope.decl ?");
  5549. const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
  5550. II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
  5551. Check(ScopeListMV != nullptr,
  5552. "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
  5553. "argument",
  5554. II);
  5555. const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
  5556. Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
  5557. Check(ScopeListMD->getNumOperands() == 1,
  5558. "!id.scope.list must point to a list with a single scope", II);
  5559. visitAliasScopeListMetadata(ScopeListMD);
  5560. }
  5561. // Only check the domination rule when requested. Once all passes have been
  5562. // adapted this option can go away.
  5563. if (!VerifyNoAliasScopeDomination)
  5564. return;
  5565. // Now sort the intrinsics based on the scope MDNode so that declarations of
  5566. // the same scopes are next to each other.
  5567. auto GetScope = [](IntrinsicInst *II) {
  5568. const auto *ScopeListMV = cast<MetadataAsValue>(
  5569. II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
  5570. return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
  5571. };
  5572. // We are sorting on MDNode pointers here. For valid input IR this is ok.
  5573. // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
  5574. auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
  5575. return GetScope(Lhs) < GetScope(Rhs);
  5576. };
  5577. llvm::sort(NoAliasScopeDecls, Compare);
  5578. // Go over the intrinsics and check that for the same scope, they are not
  5579. // dominating each other.
  5580. auto ItCurrent = NoAliasScopeDecls.begin();
  5581. while (ItCurrent != NoAliasScopeDecls.end()) {
  5582. auto CurScope = GetScope(*ItCurrent);
  5583. auto ItNext = ItCurrent;
  5584. do {
  5585. ++ItNext;
  5586. } while (ItNext != NoAliasScopeDecls.end() &&
  5587. GetScope(*ItNext) == CurScope);
  5588. // [ItCurrent, ItNext) represents the declarations for the same scope.
  5589. // Ensure they are not dominating each other.. but only if it is not too
  5590. // expensive.
  5591. if (ItNext - ItCurrent < 32)
  5592. for (auto *I : llvm::make_range(ItCurrent, ItNext))
  5593. for (auto *J : llvm::make_range(ItCurrent, ItNext))
  5594. if (I != J)
  5595. Check(!DT.dominates(I, J),
  5596. "llvm.experimental.noalias.scope.decl dominates another one "
  5597. "with the same scope",
  5598. I);
  5599. ItCurrent = ItNext;
  5600. }
  5601. }
  5602. //===----------------------------------------------------------------------===//
  5603. // Implement the public interfaces to this file...
  5604. //===----------------------------------------------------------------------===//
  5605. bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
  5606. Function &F = const_cast<Function &>(f);
  5607. // Don't use a raw_null_ostream. Printing IR is expensive.
  5608. Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
  5609. // Note that this function's return value is inverted from what you would
  5610. // expect of a function called "verify".
  5611. return !V.verify(F);
  5612. }
  5613. bool llvm::verifyModule(const Module &M, raw_ostream *OS,
  5614. bool *BrokenDebugInfo) {
  5615. // Don't use a raw_null_ostream. Printing IR is expensive.
  5616. Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
  5617. bool Broken = false;
  5618. for (const Function &F : M)
  5619. Broken |= !V.verify(F);
  5620. Broken |= !V.verify();
  5621. if (BrokenDebugInfo)
  5622. *BrokenDebugInfo = V.hasBrokenDebugInfo();
  5623. // Note that this function's return value is inverted from what you would
  5624. // expect of a function called "verify".
  5625. return Broken;
  5626. }
  5627. namespace {
  5628. struct VerifierLegacyPass : public FunctionPass {
  5629. static char ID;
  5630. std::unique_ptr<Verifier> V;
  5631. bool FatalErrors = true;
  5632. VerifierLegacyPass() : FunctionPass(ID) {
  5633. initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
  5634. }
  5635. explicit VerifierLegacyPass(bool FatalErrors)
  5636. : FunctionPass(ID),
  5637. FatalErrors(FatalErrors) {
  5638. initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
  5639. }
  5640. bool doInitialization(Module &M) override {
  5641. V = std::make_unique<Verifier>(
  5642. &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
  5643. return false;
  5644. }
  5645. bool runOnFunction(Function &F) override {
  5646. if (!V->verify(F) && FatalErrors) {
  5647. errs() << "in function " << F.getName() << '\n';
  5648. report_fatal_error("Broken function found, compilation aborted!");
  5649. }
  5650. return false;
  5651. }
  5652. bool doFinalization(Module &M) override {
  5653. bool HasErrors = false;
  5654. for (Function &F : M)
  5655. if (F.isDeclaration())
  5656. HasErrors |= !V->verify(F);
  5657. HasErrors |= !V->verify();
  5658. if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
  5659. report_fatal_error("Broken module found, compilation aborted!");
  5660. return false;
  5661. }
  5662. void getAnalysisUsage(AnalysisUsage &AU) const override {
  5663. AU.setPreservesAll();
  5664. }
  5665. };
  5666. } // end anonymous namespace
  5667. /// Helper to issue failure from the TBAA verification
  5668. template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
  5669. if (Diagnostic)
  5670. return Diagnostic->CheckFailed(Args...);
  5671. }
  5672. #define CheckTBAA(C, ...) \
  5673. do { \
  5674. if (!(C)) { \
  5675. CheckFailed(__VA_ARGS__); \
  5676. return false; \
  5677. } \
  5678. } while (false)
  5679. /// Verify that \p BaseNode can be used as the "base type" in the struct-path
  5680. /// TBAA scheme. This means \p BaseNode is either a scalar node, or a
  5681. /// struct-type node describing an aggregate data structure (like a struct).
  5682. TBAAVerifier::TBAABaseNodeSummary
  5683. TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
  5684. bool IsNewFormat) {
  5685. if (BaseNode->getNumOperands() < 2) {
  5686. CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
  5687. return {true, ~0u};
  5688. }
  5689. auto Itr = TBAABaseNodes.find(BaseNode);
  5690. if (Itr != TBAABaseNodes.end())
  5691. return Itr->second;
  5692. auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
  5693. auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
  5694. (void)InsertResult;
  5695. assert(InsertResult.second && "We just checked!");
  5696. return Result;
  5697. }
  5698. TBAAVerifier::TBAABaseNodeSummary
  5699. TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
  5700. bool IsNewFormat) {
  5701. const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
  5702. if (BaseNode->getNumOperands() == 2) {
  5703. // Scalar nodes can only be accessed at offset 0.
  5704. return isValidScalarTBAANode(BaseNode)
  5705. ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
  5706. : InvalidNode;
  5707. }
  5708. if (IsNewFormat) {
  5709. if (BaseNode->getNumOperands() % 3 != 0) {
  5710. CheckFailed("Access tag nodes must have the number of operands that is a "
  5711. "multiple of 3!", BaseNode);
  5712. return InvalidNode;
  5713. }
  5714. } else {
  5715. if (BaseNode->getNumOperands() % 2 != 1) {
  5716. CheckFailed("Struct tag nodes must have an odd number of operands!",
  5717. BaseNode);
  5718. return InvalidNode;
  5719. }
  5720. }
  5721. // Check the type size field.
  5722. if (IsNewFormat) {
  5723. auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
  5724. BaseNode->getOperand(1));
  5725. if (!TypeSizeNode) {
  5726. CheckFailed("Type size nodes must be constants!", &I, BaseNode);
  5727. return InvalidNode;
  5728. }
  5729. }
  5730. // Check the type name field. In the new format it can be anything.
  5731. if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
  5732. CheckFailed("Struct tag nodes have a string as their first operand",
  5733. BaseNode);
  5734. return InvalidNode;
  5735. }
  5736. bool Failed = false;
  5737. std::optional<APInt> PrevOffset;
  5738. unsigned BitWidth = ~0u;
  5739. // We've already checked that BaseNode is not a degenerate root node with one
  5740. // operand in \c verifyTBAABaseNode, so this loop should run at least once.
  5741. unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
  5742. unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
  5743. for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
  5744. Idx += NumOpsPerField) {
  5745. const MDOperand &FieldTy = BaseNode->getOperand(Idx);
  5746. const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
  5747. if (!isa<MDNode>(FieldTy)) {
  5748. CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
  5749. Failed = true;
  5750. continue;
  5751. }
  5752. auto *OffsetEntryCI =
  5753. mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
  5754. if (!OffsetEntryCI) {
  5755. CheckFailed("Offset entries must be constants!", &I, BaseNode);
  5756. Failed = true;
  5757. continue;
  5758. }
  5759. if (BitWidth == ~0u)
  5760. BitWidth = OffsetEntryCI->getBitWidth();
  5761. if (OffsetEntryCI->getBitWidth() != BitWidth) {
  5762. CheckFailed(
  5763. "Bitwidth between the offsets and struct type entries must match", &I,
  5764. BaseNode);
  5765. Failed = true;
  5766. continue;
  5767. }
  5768. // NB! As far as I can tell, we generate a non-strictly increasing offset
  5769. // sequence only from structs that have zero size bit fields. When
  5770. // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
  5771. // pick the field lexically the latest in struct type metadata node. This
  5772. // mirrors the actual behavior of the alias analysis implementation.
  5773. bool IsAscending =
  5774. !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
  5775. if (!IsAscending) {
  5776. CheckFailed("Offsets must be increasing!", &I, BaseNode);
  5777. Failed = true;
  5778. }
  5779. PrevOffset = OffsetEntryCI->getValue();
  5780. if (IsNewFormat) {
  5781. auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
  5782. BaseNode->getOperand(Idx + 2));
  5783. if (!MemberSizeNode) {
  5784. CheckFailed("Member size entries must be constants!", &I, BaseNode);
  5785. Failed = true;
  5786. continue;
  5787. }
  5788. }
  5789. }
  5790. return Failed ? InvalidNode
  5791. : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
  5792. }
  5793. static bool IsRootTBAANode(const MDNode *MD) {
  5794. return MD->getNumOperands() < 2;
  5795. }
  5796. static bool IsScalarTBAANodeImpl(const MDNode *MD,
  5797. SmallPtrSetImpl<const MDNode *> &Visited) {
  5798. if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
  5799. return false;
  5800. if (!isa<MDString>(MD->getOperand(0)))
  5801. return false;
  5802. if (MD->getNumOperands() == 3) {
  5803. auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
  5804. if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
  5805. return false;
  5806. }
  5807. auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
  5808. return Parent && Visited.insert(Parent).second &&
  5809. (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
  5810. }
  5811. bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
  5812. auto ResultIt = TBAAScalarNodes.find(MD);
  5813. if (ResultIt != TBAAScalarNodes.end())
  5814. return ResultIt->second;
  5815. SmallPtrSet<const MDNode *, 4> Visited;
  5816. bool Result = IsScalarTBAANodeImpl(MD, Visited);
  5817. auto InsertResult = TBAAScalarNodes.insert({MD, Result});
  5818. (void)InsertResult;
  5819. assert(InsertResult.second && "Just checked!");
  5820. return Result;
  5821. }
  5822. /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
  5823. /// Offset in place to be the offset within the field node returned.
  5824. ///
  5825. /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
  5826. MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
  5827. const MDNode *BaseNode,
  5828. APInt &Offset,
  5829. bool IsNewFormat) {
  5830. assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
  5831. // Scalar nodes have only one possible "field" -- their parent in the access
  5832. // hierarchy. Offset must be zero at this point, but our caller is supposed
  5833. // to check that.
  5834. if (BaseNode->getNumOperands() == 2)
  5835. return cast<MDNode>(BaseNode->getOperand(1));
  5836. unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
  5837. unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
  5838. for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
  5839. Idx += NumOpsPerField) {
  5840. auto *OffsetEntryCI =
  5841. mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
  5842. if (OffsetEntryCI->getValue().ugt(Offset)) {
  5843. if (Idx == FirstFieldOpNo) {
  5844. CheckFailed("Could not find TBAA parent in struct type node", &I,
  5845. BaseNode, &Offset);
  5846. return nullptr;
  5847. }
  5848. unsigned PrevIdx = Idx - NumOpsPerField;
  5849. auto *PrevOffsetEntryCI =
  5850. mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
  5851. Offset -= PrevOffsetEntryCI->getValue();
  5852. return cast<MDNode>(BaseNode->getOperand(PrevIdx));
  5853. }
  5854. }
  5855. unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
  5856. auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
  5857. BaseNode->getOperand(LastIdx + 1));
  5858. Offset -= LastOffsetEntryCI->getValue();
  5859. return cast<MDNode>(BaseNode->getOperand(LastIdx));
  5860. }
  5861. static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
  5862. if (!Type || Type->getNumOperands() < 3)
  5863. return false;
  5864. // In the new format type nodes shall have a reference to the parent type as
  5865. // its first operand.
  5866. return isa_and_nonnull<MDNode>(Type->getOperand(0));
  5867. }
  5868. bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
  5869. CheckTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
  5870. isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
  5871. isa<AtomicCmpXchgInst>(I),
  5872. "This instruction shall not have a TBAA access tag!", &I);
  5873. bool IsStructPathTBAA =
  5874. isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
  5875. CheckTBAA(IsStructPathTBAA,
  5876. "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
  5877. &I);
  5878. MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
  5879. MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
  5880. bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
  5881. if (IsNewFormat) {
  5882. CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
  5883. "Access tag metadata must have either 4 or 5 operands", &I, MD);
  5884. } else {
  5885. CheckTBAA(MD->getNumOperands() < 5,
  5886. "Struct tag metadata must have either 3 or 4 operands", &I, MD);
  5887. }
  5888. // Check the access size field.
  5889. if (IsNewFormat) {
  5890. auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
  5891. MD->getOperand(3));
  5892. CheckTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
  5893. }
  5894. // Check the immutability flag.
  5895. unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
  5896. if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
  5897. auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
  5898. MD->getOperand(ImmutabilityFlagOpNo));
  5899. CheckTBAA(IsImmutableCI,
  5900. "Immutability tag on struct tag metadata must be a constant", &I,
  5901. MD);
  5902. CheckTBAA(
  5903. IsImmutableCI->isZero() || IsImmutableCI->isOne(),
  5904. "Immutability part of the struct tag metadata must be either 0 or 1",
  5905. &I, MD);
  5906. }
  5907. CheckTBAA(BaseNode && AccessType,
  5908. "Malformed struct tag metadata: base and access-type "
  5909. "should be non-null and point to Metadata nodes",
  5910. &I, MD, BaseNode, AccessType);
  5911. if (!IsNewFormat) {
  5912. CheckTBAA(isValidScalarTBAANode(AccessType),
  5913. "Access type node must be a valid scalar type", &I, MD,
  5914. AccessType);
  5915. }
  5916. auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
  5917. CheckTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
  5918. APInt Offset = OffsetCI->getValue();
  5919. bool SeenAccessTypeInPath = false;
  5920. SmallPtrSet<MDNode *, 4> StructPath;
  5921. for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
  5922. BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
  5923. IsNewFormat)) {
  5924. if (!StructPath.insert(BaseNode).second) {
  5925. CheckFailed("Cycle detected in struct path", &I, MD);
  5926. return false;
  5927. }
  5928. bool Invalid;
  5929. unsigned BaseNodeBitWidth;
  5930. std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
  5931. IsNewFormat);
  5932. // If the base node is invalid in itself, then we've already printed all the
  5933. // errors we wanted to print.
  5934. if (Invalid)
  5935. return false;
  5936. SeenAccessTypeInPath |= BaseNode == AccessType;
  5937. if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
  5938. CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access",
  5939. &I, MD, &Offset);
  5940. CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
  5941. (BaseNodeBitWidth == 0 && Offset == 0) ||
  5942. (IsNewFormat && BaseNodeBitWidth == ~0u),
  5943. "Access bit-width not the same as description bit-width", &I, MD,
  5944. BaseNodeBitWidth, Offset.getBitWidth());
  5945. if (IsNewFormat && SeenAccessTypeInPath)
  5946. break;
  5947. }
  5948. CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", &I,
  5949. MD);
  5950. return true;
  5951. }
  5952. char VerifierLegacyPass::ID = 0;
  5953. INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
  5954. FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
  5955. return new VerifierLegacyPass(FatalErrors);
  5956. }
  5957. AnalysisKey VerifierAnalysis::Key;
  5958. VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
  5959. ModuleAnalysisManager &) {
  5960. Result Res;
  5961. Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
  5962. return Res;
  5963. }
  5964. VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
  5965. FunctionAnalysisManager &) {
  5966. return { llvm::verifyFunction(F, &dbgs()), false };
  5967. }
  5968. PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
  5969. auto Res = AM.getResult<VerifierAnalysis>(M);
  5970. if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
  5971. report_fatal_error("Broken module found, compilation aborted!");
  5972. return PreservedAnalyses::all();
  5973. }
  5974. PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
  5975. auto res = AM.getResult<VerifierAnalysis>(F);
  5976. if (res.IRBroken && FatalErrors)
  5977. report_fatal_error("Broken function found, compilation aborted!");
  5978. return PreservedAnalyses::all();
  5979. }