Verifier.cpp 208 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510
  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. // sanity 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. // * PHI nodes must have at least one entry
  27. // * All basic blocks should only end with terminator insts, not contain them
  28. // * The entry node to a function must not have predecessors
  29. // * All Instructions must be embedded into a basic block
  30. // * Functions cannot take a void-typed parameter
  31. // * Verify that a function's argument list agrees with it's declared type.
  32. // * It is illegal to specify a name for a void value.
  33. // * It is illegal to have a internal global value with no initializer
  34. // * It is illegal to have a ret instruction that returns a value that does not
  35. // agree with the function return value type.
  36. // * Function call argument types match the function prototype
  37. // * A landing pad is defined by a landingpad instruction, and can be jumped to
  38. // only by the unwind edge of an invoke instruction.
  39. // * A landingpad instruction must be the first non-PHI instruction in the
  40. // block.
  41. // * Landingpad instructions must be in a function with a personality function.
  42. // * All other things that are tested by asserts spread about the code...
  43. //
  44. //===----------------------------------------------------------------------===//
  45. #include "llvm/IR/Verifier.h"
  46. #include "llvm/ADT/APFloat.h"
  47. #include "llvm/ADT/APInt.h"
  48. #include "llvm/ADT/ArrayRef.h"
  49. #include "llvm/ADT/DenseMap.h"
  50. #include "llvm/ADT/MapVector.h"
  51. #include "llvm/ADT/Optional.h"
  52. #include "llvm/ADT/STLExtras.h"
  53. #include "llvm/ADT/SmallPtrSet.h"
  54. #include "llvm/ADT/SmallSet.h"
  55. #include "llvm/ADT/SmallVector.h"
  56. #include "llvm/ADT/StringExtras.h"
  57. #include "llvm/ADT/StringMap.h"
  58. #include "llvm/ADT/StringRef.h"
  59. #include "llvm/ADT/Twine.h"
  60. #include "llvm/ADT/ilist.h"
  61. #include "llvm/BinaryFormat/Dwarf.h"
  62. #include "llvm/IR/Argument.h"
  63. #include "llvm/IR/Attributes.h"
  64. #include "llvm/IR/BasicBlock.h"
  65. #include "llvm/IR/CFG.h"
  66. #include "llvm/IR/CallingConv.h"
  67. #include "llvm/IR/Comdat.h"
  68. #include "llvm/IR/Constant.h"
  69. #include "llvm/IR/ConstantRange.h"
  70. #include "llvm/IR/Constants.h"
  71. #include "llvm/IR/DataLayout.h"
  72. #include "llvm/IR/DebugInfo.h"
  73. #include "llvm/IR/DebugInfoMetadata.h"
  74. #include "llvm/IR/DebugLoc.h"
  75. #include "llvm/IR/DerivedTypes.h"
  76. #include "llvm/IR/Dominators.h"
  77. #include "llvm/IR/Function.h"
  78. #include "llvm/IR/GlobalAlias.h"
  79. #include "llvm/IR/GlobalValue.h"
  80. #include "llvm/IR/GlobalVariable.h"
  81. #include "llvm/IR/InlineAsm.h"
  82. #include "llvm/IR/InstVisitor.h"
  83. #include "llvm/IR/InstrTypes.h"
  84. #include "llvm/IR/Instruction.h"
  85. #include "llvm/IR/Instructions.h"
  86. #include "llvm/IR/IntrinsicInst.h"
  87. #include "llvm/IR/Intrinsics.h"
  88. #include "llvm/IR/LLVMContext.h"
  89. #include "llvm/IR/Metadata.h"
  90. #include "llvm/IR/Module.h"
  91. #include "llvm/IR/ModuleSlotTracker.h"
  92. #include "llvm/IR/PassManager.h"
  93. #include "llvm/IR/Statepoint.h"
  94. #include "llvm/IR/Type.h"
  95. #include "llvm/IR/Use.h"
  96. #include "llvm/IR/User.h"
  97. #include "llvm/IR/Value.h"
  98. #include "llvm/Pass.h"
  99. #include "llvm/Support/AtomicOrdering.h"
  100. #include "llvm/Support/Casting.h"
  101. #include "llvm/Support/CommandLine.h"
  102. #include "llvm/Support/Debug.h"
  103. #include "llvm/Support/ErrorHandling.h"
  104. #include "llvm/Support/MathExtras.h"
  105. #include "llvm/Support/raw_ostream.h"
  106. #include <algorithm>
  107. #include <cassert>
  108. #include <cstdint>
  109. #include <memory>
  110. #include <string>
  111. #include <utility>
  112. using namespace llvm;
  113. namespace llvm {
  114. struct VerifierSupport {
  115. raw_ostream *OS;
  116. const Module &M;
  117. ModuleSlotTracker MST;
  118. Triple TT;
  119. const DataLayout &DL;
  120. LLVMContext &Context;
  121. /// Track the brokenness of the module while recursively visiting.
  122. bool Broken = false;
  123. /// Broken debug info can be "recovered" from by stripping the debug info.
  124. bool BrokenDebugInfo = false;
  125. /// Whether to treat broken debug info as an error.
  126. bool TreatBrokenDebugInfoAsError = true;
  127. explicit VerifierSupport(raw_ostream *OS, const Module &M)
  128. : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
  129. Context(M.getContext()) {}
  130. private:
  131. void Write(const Module *M) {
  132. *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
  133. }
  134. void Write(const Value *V) {
  135. if (V)
  136. Write(*V);
  137. }
  138. void Write(const Value &V) {
  139. if (isa<Instruction>(V)) {
  140. V.print(*OS, MST);
  141. *OS << '\n';
  142. } else {
  143. V.printAsOperand(*OS, true, MST);
  144. *OS << '\n';
  145. }
  146. }
  147. void Write(const Metadata *MD) {
  148. if (!MD)
  149. return;
  150. MD->print(*OS, MST, &M);
  151. *OS << '\n';
  152. }
  153. template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
  154. Write(MD.get());
  155. }
  156. void Write(const NamedMDNode *NMD) {
  157. if (!NMD)
  158. return;
  159. NMD->print(*OS, MST);
  160. *OS << '\n';
  161. }
  162. void Write(Type *T) {
  163. if (!T)
  164. return;
  165. *OS << ' ' << *T;
  166. }
  167. void Write(const Comdat *C) {
  168. if (!C)
  169. return;
  170. *OS << *C;
  171. }
  172. void Write(const APInt *AI) {
  173. if (!AI)
  174. return;
  175. *OS << *AI << '\n';
  176. }
  177. void Write(const unsigned i) { *OS << i << '\n'; }
  178. template <typename T> void Write(ArrayRef<T> Vs) {
  179. for (const T &V : Vs)
  180. Write(V);
  181. }
  182. template <typename T1, typename... Ts>
  183. void WriteTs(const T1 &V1, const Ts &... Vs) {
  184. Write(V1);
  185. WriteTs(Vs...);
  186. }
  187. template <typename... Ts> void WriteTs() {}
  188. public:
  189. /// A check failed, so printout out the condition and the message.
  190. ///
  191. /// This provides a nice place to put a breakpoint if you want to see why
  192. /// something is not correct.
  193. void CheckFailed(const Twine &Message) {
  194. if (OS)
  195. *OS << Message << '\n';
  196. Broken = true;
  197. }
  198. /// A check failed (with values to print).
  199. ///
  200. /// This calls the Message-only version so that the above is easier to set a
  201. /// breakpoint on.
  202. template <typename T1, typename... Ts>
  203. void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
  204. CheckFailed(Message);
  205. if (OS)
  206. WriteTs(V1, Vs...);
  207. }
  208. /// A debug info check failed.
  209. void DebugInfoCheckFailed(const Twine &Message) {
  210. if (OS)
  211. *OS << Message << '\n';
  212. Broken |= TreatBrokenDebugInfoAsError;
  213. BrokenDebugInfo = true;
  214. }
  215. /// A debug info check failed (with values to print).
  216. template <typename T1, typename... Ts>
  217. void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
  218. const Ts &... Vs) {
  219. DebugInfoCheckFailed(Message);
  220. if (OS)
  221. WriteTs(V1, Vs...);
  222. }
  223. };
  224. } // namespace llvm
  225. namespace {
  226. class Verifier : public InstVisitor<Verifier>, VerifierSupport {
  227. friend class InstVisitor<Verifier>;
  228. DominatorTree DT;
  229. /// When verifying a basic block, keep track of all of the
  230. /// instructions we have seen so far.
  231. ///
  232. /// This allows us to do efficient dominance checks for the case when an
  233. /// instruction has an operand that is an instruction in the same block.
  234. SmallPtrSet<Instruction *, 16> InstsInThisBlock;
  235. /// Keep track of the metadata nodes that have been checked already.
  236. SmallPtrSet<const Metadata *, 32> MDNodes;
  237. /// Keep track which DISubprogram is attached to which function.
  238. DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
  239. /// Track all DICompileUnits visited.
  240. SmallPtrSet<const Metadata *, 2> CUVisited;
  241. /// The result type for a landingpad.
  242. Type *LandingPadResultTy;
  243. /// Whether we've seen a call to @llvm.localescape in this function
  244. /// already.
  245. bool SawFrameEscape;
  246. /// Whether the current function has a DISubprogram attached to it.
  247. bool HasDebugInfo = false;
  248. /// Whether source was present on the first DIFile encountered in each CU.
  249. DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
  250. /// Stores the count of how many objects were passed to llvm.localescape for a
  251. /// given function and the largest index passed to llvm.localrecover.
  252. DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
  253. // Maps catchswitches and cleanuppads that unwind to siblings to the
  254. // terminators that indicate the unwind, used to detect cycles therein.
  255. MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
  256. /// Cache of constants visited in search of ConstantExprs.
  257. SmallPtrSet<const Constant *, 32> ConstantExprVisited;
  258. /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
  259. SmallVector<const Function *, 4> DeoptimizeDeclarations;
  260. // Verify that this GlobalValue is only used in this module.
  261. // This map is used to avoid visiting uses twice. We can arrive at a user
  262. // twice, if they have multiple operands. In particular for very large
  263. // constant expressions, we can arrive at a particular user many times.
  264. SmallPtrSet<const Value *, 32> GlobalValueVisited;
  265. // Keeps track of duplicate function argument debug info.
  266. SmallVector<const DILocalVariable *, 16> DebugFnArgs;
  267. TBAAVerifier TBAAVerifyHelper;
  268. void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
  269. public:
  270. explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
  271. const Module &M)
  272. : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
  273. SawFrameEscape(false), TBAAVerifyHelper(this) {
  274. TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
  275. }
  276. bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
  277. bool verify(const Function &F) {
  278. assert(F.getParent() == &M &&
  279. "An instance of this class only works with a specific module!");
  280. // First ensure the function is well-enough formed to compute dominance
  281. // information, and directly compute a dominance tree. We don't rely on the
  282. // pass manager to provide this as it isolates us from a potentially
  283. // out-of-date dominator tree and makes it significantly more complex to run
  284. // this code outside of a pass manager.
  285. // FIXME: It's really gross that we have to cast away constness here.
  286. if (!F.empty())
  287. DT.recalculate(const_cast<Function &>(F));
  288. for (const BasicBlock &BB : F) {
  289. if (!BB.empty() && BB.back().isTerminator())
  290. continue;
  291. if (OS) {
  292. *OS << "Basic Block in function '" << F.getName()
  293. << "' does not have terminator!\n";
  294. BB.printAsOperand(*OS, true, MST);
  295. *OS << "\n";
  296. }
  297. return false;
  298. }
  299. Broken = false;
  300. // FIXME: We strip const here because the inst visitor strips const.
  301. visit(const_cast<Function &>(F));
  302. verifySiblingFuncletUnwinds();
  303. InstsInThisBlock.clear();
  304. DebugFnArgs.clear();
  305. LandingPadResultTy = nullptr;
  306. SawFrameEscape = false;
  307. SiblingFuncletInfo.clear();
  308. return !Broken;
  309. }
  310. /// Verify the module that this instance of \c Verifier was initialized with.
  311. bool verify() {
  312. Broken = false;
  313. // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
  314. for (const Function &F : M)
  315. if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
  316. DeoptimizeDeclarations.push_back(&F);
  317. // Now that we've visited every function, verify that we never asked to
  318. // recover a frame index that wasn't escaped.
  319. verifyFrameRecoverIndices();
  320. for (const GlobalVariable &GV : M.globals())
  321. visitGlobalVariable(GV);
  322. for (const GlobalAlias &GA : M.aliases())
  323. visitGlobalAlias(GA);
  324. for (const NamedMDNode &NMD : M.named_metadata())
  325. visitNamedMDNode(NMD);
  326. for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
  327. visitComdat(SMEC.getValue());
  328. visitModuleFlags(M);
  329. visitModuleIdents(M);
  330. visitModuleCommandLines(M);
  331. verifyCompileUnits();
  332. verifyDeoptimizeCallingConvs();
  333. DISubprogramAttachments.clear();
  334. return !Broken;
  335. }
  336. private:
  337. // Verification methods...
  338. void visitGlobalValue(const GlobalValue &GV);
  339. void visitGlobalVariable(const GlobalVariable &GV);
  340. void visitGlobalAlias(const GlobalAlias &GA);
  341. void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
  342. void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
  343. const GlobalAlias &A, const Constant &C);
  344. void visitNamedMDNode(const NamedMDNode &NMD);
  345. void visitMDNode(const MDNode &MD);
  346. void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
  347. void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
  348. void visitComdat(const Comdat &C);
  349. void visitModuleIdents(const Module &M);
  350. void visitModuleCommandLines(const Module &M);
  351. void visitModuleFlags(const Module &M);
  352. void visitModuleFlag(const MDNode *Op,
  353. DenseMap<const MDString *, const MDNode *> &SeenIDs,
  354. SmallVectorImpl<const MDNode *> &Requirements);
  355. void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
  356. void visitFunction(const Function &F);
  357. void visitBasicBlock(BasicBlock &BB);
  358. void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
  359. void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
  360. void visitProfMetadata(Instruction &I, MDNode *MD);
  361. template <class Ty> bool isValidMetadataArray(const MDTuple &N);
  362. #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
  363. #include "llvm/IR/Metadata.def"
  364. void visitDIScope(const DIScope &N);
  365. void visitDIVariable(const DIVariable &N);
  366. void visitDILexicalBlockBase(const DILexicalBlockBase &N);
  367. void visitDITemplateParameter(const DITemplateParameter &N);
  368. void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
  369. // InstVisitor overrides...
  370. using InstVisitor<Verifier>::visit;
  371. void visit(Instruction &I);
  372. void visitTruncInst(TruncInst &I);
  373. void visitZExtInst(ZExtInst &I);
  374. void visitSExtInst(SExtInst &I);
  375. void visitFPTruncInst(FPTruncInst &I);
  376. void visitFPExtInst(FPExtInst &I);
  377. void visitFPToUIInst(FPToUIInst &I);
  378. void visitFPToSIInst(FPToSIInst &I);
  379. void visitUIToFPInst(UIToFPInst &I);
  380. void visitSIToFPInst(SIToFPInst &I);
  381. void visitIntToPtrInst(IntToPtrInst &I);
  382. void visitPtrToIntInst(PtrToIntInst &I);
  383. void visitBitCastInst(BitCastInst &I);
  384. void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
  385. void visitPHINode(PHINode &PN);
  386. void visitCallBase(CallBase &Call);
  387. void visitUnaryOperator(UnaryOperator &U);
  388. void visitBinaryOperator(BinaryOperator &B);
  389. void visitICmpInst(ICmpInst &IC);
  390. void visitFCmpInst(FCmpInst &FC);
  391. void visitExtractElementInst(ExtractElementInst &EI);
  392. void visitInsertElementInst(InsertElementInst &EI);
  393. void visitShuffleVectorInst(ShuffleVectorInst &EI);
  394. void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
  395. void visitCallInst(CallInst &CI);
  396. void visitInvokeInst(InvokeInst &II);
  397. void visitGetElementPtrInst(GetElementPtrInst &GEP);
  398. void visitLoadInst(LoadInst &LI);
  399. void visitStoreInst(StoreInst &SI);
  400. void verifyDominatesUse(Instruction &I, unsigned i);
  401. void visitInstruction(Instruction &I);
  402. void visitTerminator(Instruction &I);
  403. void visitBranchInst(BranchInst &BI);
  404. void visitReturnInst(ReturnInst &RI);
  405. void visitSwitchInst(SwitchInst &SI);
  406. void visitIndirectBrInst(IndirectBrInst &BI);
  407. void visitCallBrInst(CallBrInst &CBI);
  408. void visitSelectInst(SelectInst &SI);
  409. void visitUserOp1(Instruction &I);
  410. void visitUserOp2(Instruction &I) { visitUserOp1(I); }
  411. void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
  412. void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
  413. void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
  414. void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
  415. void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
  416. void visitAtomicRMWInst(AtomicRMWInst &RMWI);
  417. void visitFenceInst(FenceInst &FI);
  418. void visitAllocaInst(AllocaInst &AI);
  419. void visitExtractValueInst(ExtractValueInst &EVI);
  420. void visitInsertValueInst(InsertValueInst &IVI);
  421. void visitEHPadPredecessors(Instruction &I);
  422. void visitLandingPadInst(LandingPadInst &LPI);
  423. void visitResumeInst(ResumeInst &RI);
  424. void visitCatchPadInst(CatchPadInst &CPI);
  425. void visitCatchReturnInst(CatchReturnInst &CatchReturn);
  426. void visitCleanupPadInst(CleanupPadInst &CPI);
  427. void visitFuncletPadInst(FuncletPadInst &FPI);
  428. void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
  429. void visitCleanupReturnInst(CleanupReturnInst &CRI);
  430. void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
  431. void verifySwiftErrorValue(const Value *SwiftErrorVal);
  432. void verifyMustTailCall(CallInst &CI);
  433. bool performTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
  434. unsigned ArgNo, std::string &Suffix);
  435. bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
  436. void verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
  437. const Value *V);
  438. void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
  439. void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
  440. const Value *V, bool IsIntrinsic);
  441. void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
  442. void visitConstantExprsRecursively(const Constant *EntryC);
  443. void visitConstantExpr(const ConstantExpr *CE);
  444. void verifyStatepoint(const CallBase &Call);
  445. void verifyFrameRecoverIndices();
  446. void verifySiblingFuncletUnwinds();
  447. void verifyFragmentExpression(const DbgVariableIntrinsic &I);
  448. template <typename ValueOrMetadata>
  449. void verifyFragmentExpression(const DIVariable &V,
  450. DIExpression::FragmentInfo Fragment,
  451. ValueOrMetadata *Desc);
  452. void verifyFnArgs(const DbgVariableIntrinsic &I);
  453. /// Module-level debug info verification...
  454. void verifyCompileUnits();
  455. /// Module-level verification that all @llvm.experimental.deoptimize
  456. /// declarations share the same calling convention.
  457. void verifyDeoptimizeCallingConvs();
  458. /// Verify all-or-nothing property of DIFile source attribute within a CU.
  459. void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
  460. };
  461. } // end anonymous namespace
  462. /// We know that cond should be true, if not print an error message.
  463. #define Assert(C, ...) \
  464. do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
  465. /// We know that a debug info condition should be true, if not print
  466. /// an error message.
  467. #define AssertDI(C, ...) \
  468. do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
  469. void Verifier::visit(Instruction &I) {
  470. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  471. Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
  472. InstVisitor<Verifier>::visit(I);
  473. }
  474. // Helper to recursively iterate over indirect users. By
  475. // returning false, the callback can ask to stop recursing
  476. // further.
  477. static void forEachUser(const Value *User,
  478. SmallPtrSet<const Value *, 32> &Visited,
  479. llvm::function_ref<bool(const Value *)> Callback) {
  480. if (!Visited.insert(User).second)
  481. return;
  482. for (const Value *TheNextUser : User->materialized_users())
  483. if (Callback(TheNextUser))
  484. forEachUser(TheNextUser, Visited, Callback);
  485. }
  486. void Verifier::visitGlobalValue(const GlobalValue &GV) {
  487. Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
  488. "Global is external, but doesn't have external or weak linkage!", &GV);
  489. Assert(GV.getAlignment() <= Value::MaximumAlignment,
  490. "huge alignment values are unsupported", &GV);
  491. Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
  492. "Only global variables can have appending linkage!", &GV);
  493. if (GV.hasAppendingLinkage()) {
  494. const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
  495. Assert(GVar && GVar->getValueType()->isArrayTy(),
  496. "Only global arrays can have appending linkage!", GVar);
  497. }
  498. if (GV.isDeclarationForLinker())
  499. Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
  500. if (GV.hasDLLImportStorageClass()) {
  501. Assert(!GV.isDSOLocal(),
  502. "GlobalValue with DLLImport Storage is dso_local!", &GV);
  503. Assert((GV.isDeclaration() && GV.hasExternalLinkage()) ||
  504. GV.hasAvailableExternallyLinkage(),
  505. "Global is marked as dllimport, but not external", &GV);
  506. }
  507. if (GV.hasLocalLinkage())
  508. Assert(GV.isDSOLocal(),
  509. "GlobalValue with private or internal linkage must be dso_local!",
  510. &GV);
  511. if (!GV.hasDefaultVisibility() && !GV.hasExternalWeakLinkage())
  512. Assert(GV.isDSOLocal(),
  513. "GlobalValue with non default visibility must be dso_local!", &GV);
  514. forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
  515. if (const Instruction *I = dyn_cast<Instruction>(V)) {
  516. if (!I->getParent() || !I->getParent()->getParent())
  517. CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
  518. I);
  519. else if (I->getParent()->getParent()->getParent() != &M)
  520. CheckFailed("Global is referenced in a different module!", &GV, &M, I,
  521. I->getParent()->getParent(),
  522. I->getParent()->getParent()->getParent());
  523. return false;
  524. } else if (const Function *F = dyn_cast<Function>(V)) {
  525. if (F->getParent() != &M)
  526. CheckFailed("Global is used by function in a different module", &GV, &M,
  527. F, F->getParent());
  528. return false;
  529. }
  530. return true;
  531. });
  532. }
  533. void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
  534. if (GV.hasInitializer()) {
  535. Assert(GV.getInitializer()->getType() == GV.getValueType(),
  536. "Global variable initializer type does not match global "
  537. "variable type!",
  538. &GV);
  539. // If the global has common linkage, it must have a zero initializer and
  540. // cannot be constant.
  541. if (GV.hasCommonLinkage()) {
  542. Assert(GV.getInitializer()->isNullValue(),
  543. "'common' global must have a zero initializer!", &GV);
  544. Assert(!GV.isConstant(), "'common' global may not be marked constant!",
  545. &GV);
  546. Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
  547. }
  548. }
  549. if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
  550. GV.getName() == "llvm.global_dtors")) {
  551. Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
  552. "invalid linkage for intrinsic global variable", &GV);
  553. // Don't worry about emitting an error for it not being an array,
  554. // visitGlobalValue will complain on appending non-array.
  555. if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
  556. StructType *STy = dyn_cast<StructType>(ATy->getElementType());
  557. PointerType *FuncPtrTy =
  558. FunctionType::get(Type::getVoidTy(Context), false)->
  559. getPointerTo(DL.getProgramAddressSpace());
  560. Assert(STy &&
  561. (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
  562. STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
  563. STy->getTypeAtIndex(1) == FuncPtrTy,
  564. "wrong type for intrinsic global variable", &GV);
  565. Assert(STy->getNumElements() == 3,
  566. "the third field of the element type is mandatory, "
  567. "specify i8* null to migrate from the obsoleted 2-field form");
  568. Type *ETy = STy->getTypeAtIndex(2);
  569. Assert(ETy->isPointerTy() &&
  570. cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
  571. "wrong type for intrinsic global variable", &GV);
  572. }
  573. }
  574. if (GV.hasName() && (GV.getName() == "llvm.used" ||
  575. GV.getName() == "llvm.compiler.used")) {
  576. Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
  577. "invalid linkage for intrinsic global variable", &GV);
  578. Type *GVType = GV.getValueType();
  579. if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
  580. PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
  581. Assert(PTy, "wrong type for intrinsic global variable", &GV);
  582. if (GV.hasInitializer()) {
  583. const Constant *Init = GV.getInitializer();
  584. const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
  585. Assert(InitArray, "wrong initalizer for intrinsic global variable",
  586. Init);
  587. for (Value *Op : InitArray->operands()) {
  588. Value *V = Op->stripPointerCasts();
  589. Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
  590. isa<GlobalAlias>(V),
  591. "invalid llvm.used member", V);
  592. Assert(V->hasName(), "members of llvm.used must be named", V);
  593. }
  594. }
  595. }
  596. }
  597. // Visit any debug info attachments.
  598. SmallVector<MDNode *, 1> MDs;
  599. GV.getMetadata(LLVMContext::MD_dbg, MDs);
  600. for (auto *MD : MDs) {
  601. if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
  602. visitDIGlobalVariableExpression(*GVE);
  603. else
  604. AssertDI(false, "!dbg attachment of global variable must be a "
  605. "DIGlobalVariableExpression");
  606. }
  607. // Scalable vectors cannot be global variables, since we don't know
  608. // the runtime size. If the global is a struct or an array containing
  609. // scalable vectors, that will be caught by the isValidElementType methods
  610. // in StructType or ArrayType instead.
  611. if (auto *VTy = dyn_cast<VectorType>(GV.getValueType()))
  612. Assert(!VTy->isScalable(), "Globals cannot contain scalable vectors", &GV);
  613. if (!GV.hasInitializer()) {
  614. visitGlobalValue(GV);
  615. return;
  616. }
  617. // Walk any aggregate initializers looking for bitcasts between address spaces
  618. visitConstantExprsRecursively(GV.getInitializer());
  619. visitGlobalValue(GV);
  620. }
  621. void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
  622. SmallPtrSet<const GlobalAlias*, 4> Visited;
  623. Visited.insert(&GA);
  624. visitAliaseeSubExpr(Visited, GA, C);
  625. }
  626. void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
  627. const GlobalAlias &GA, const Constant &C) {
  628. if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
  629. Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
  630. &GA);
  631. if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
  632. Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
  633. Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",
  634. &GA);
  635. } else {
  636. // Only continue verifying subexpressions of GlobalAliases.
  637. // Do not recurse into global initializers.
  638. return;
  639. }
  640. }
  641. if (const auto *CE = dyn_cast<ConstantExpr>(&C))
  642. visitConstantExprsRecursively(CE);
  643. for (const Use &U : C.operands()) {
  644. Value *V = &*U;
  645. if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
  646. visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
  647. else if (const auto *C2 = dyn_cast<Constant>(V))
  648. visitAliaseeSubExpr(Visited, GA, *C2);
  649. }
  650. }
  651. void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
  652. Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
  653. "Alias should have private, internal, linkonce, weak, linkonce_odr, "
  654. "weak_odr, or external linkage!",
  655. &GA);
  656. const Constant *Aliasee = GA.getAliasee();
  657. Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
  658. Assert(GA.getType() == Aliasee->getType(),
  659. "Alias and aliasee types should match!", &GA);
  660. Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
  661. "Aliasee should be either GlobalValue or ConstantExpr", &GA);
  662. visitAliaseeSubExpr(GA, *Aliasee);
  663. visitGlobalValue(GA);
  664. }
  665. void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
  666. // There used to be various other llvm.dbg.* nodes, but we don't support
  667. // upgrading them and we want to reserve the namespace for future uses.
  668. if (NMD.getName().startswith("llvm.dbg."))
  669. AssertDI(NMD.getName() == "llvm.dbg.cu",
  670. "unrecognized named metadata node in the llvm.dbg namespace",
  671. &NMD);
  672. for (const MDNode *MD : NMD.operands()) {
  673. if (NMD.getName() == "llvm.dbg.cu")
  674. AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
  675. if (!MD)
  676. continue;
  677. visitMDNode(*MD);
  678. }
  679. }
  680. void Verifier::visitMDNode(const MDNode &MD) {
  681. // Only visit each node once. Metadata can be mutually recursive, so this
  682. // avoids infinite recursion here, as well as being an optimization.
  683. if (!MDNodes.insert(&MD).second)
  684. return;
  685. switch (MD.getMetadataID()) {
  686. default:
  687. llvm_unreachable("Invalid MDNode subclass");
  688. case Metadata::MDTupleKind:
  689. break;
  690. #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
  691. case Metadata::CLASS##Kind: \
  692. visit##CLASS(cast<CLASS>(MD)); \
  693. break;
  694. #include "llvm/IR/Metadata.def"
  695. }
  696. for (const Metadata *Op : MD.operands()) {
  697. if (!Op)
  698. continue;
  699. Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
  700. &MD, Op);
  701. if (auto *N = dyn_cast<MDNode>(Op)) {
  702. visitMDNode(*N);
  703. continue;
  704. }
  705. if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
  706. visitValueAsMetadata(*V, nullptr);
  707. continue;
  708. }
  709. }
  710. // Check these last, so we diagnose problems in operands first.
  711. Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
  712. Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
  713. }
  714. void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
  715. Assert(MD.getValue(), "Expected valid value", &MD);
  716. Assert(!MD.getValue()->getType()->isMetadataTy(),
  717. "Unexpected metadata round-trip through values", &MD, MD.getValue());
  718. auto *L = dyn_cast<LocalAsMetadata>(&MD);
  719. if (!L)
  720. return;
  721. Assert(F, "function-local metadata used outside a function", L);
  722. // If this was an instruction, bb, or argument, verify that it is in the
  723. // function that we expect.
  724. Function *ActualF = nullptr;
  725. if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
  726. Assert(I->getParent(), "function-local metadata not in basic block", L, I);
  727. ActualF = I->getParent()->getParent();
  728. } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
  729. ActualF = BB->getParent();
  730. else if (Argument *A = dyn_cast<Argument>(L->getValue()))
  731. ActualF = A->getParent();
  732. assert(ActualF && "Unimplemented function local metadata case!");
  733. Assert(ActualF == F, "function-local metadata used in wrong function", L);
  734. }
  735. void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
  736. Metadata *MD = MDV.getMetadata();
  737. if (auto *N = dyn_cast<MDNode>(MD)) {
  738. visitMDNode(*N);
  739. return;
  740. }
  741. // Only visit each node once. Metadata can be mutually recursive, so this
  742. // avoids infinite recursion here, as well as being an optimization.
  743. if (!MDNodes.insert(MD).second)
  744. return;
  745. if (auto *V = dyn_cast<ValueAsMetadata>(MD))
  746. visitValueAsMetadata(*V, F);
  747. }
  748. static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
  749. static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
  750. static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
  751. void Verifier::visitDILocation(const DILocation &N) {
  752. AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
  753. "location requires a valid scope", &N, N.getRawScope());
  754. if (auto *IA = N.getRawInlinedAt())
  755. AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
  756. if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
  757. AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
  758. }
  759. void Verifier::visitGenericDINode(const GenericDINode &N) {
  760. AssertDI(N.getTag(), "invalid tag", &N);
  761. }
  762. void Verifier::visitDIScope(const DIScope &N) {
  763. if (auto *F = N.getRawFile())
  764. AssertDI(isa<DIFile>(F), "invalid file", &N, F);
  765. }
  766. void Verifier::visitDISubrange(const DISubrange &N) {
  767. AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
  768. auto Count = N.getCount();
  769. AssertDI(Count, "Count must either be a signed constant or a DIVariable",
  770. &N);
  771. AssertDI(!Count.is<ConstantInt*>() ||
  772. Count.get<ConstantInt*>()->getSExtValue() >= -1,
  773. "invalid subrange count", &N);
  774. }
  775. void Verifier::visitDIEnumerator(const DIEnumerator &N) {
  776. AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
  777. }
  778. void Verifier::visitDIBasicType(const DIBasicType &N) {
  779. AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||
  780. N.getTag() == dwarf::DW_TAG_unspecified_type,
  781. "invalid tag", &N);
  782. AssertDI(!(N.isBigEndian() && N.isLittleEndian()) ,
  783. "has conflicting flags", &N);
  784. }
  785. void Verifier::visitDIDerivedType(const DIDerivedType &N) {
  786. // Common scope checks.
  787. visitDIScope(N);
  788. AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||
  789. N.getTag() == dwarf::DW_TAG_pointer_type ||
  790. N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
  791. N.getTag() == dwarf::DW_TAG_reference_type ||
  792. N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
  793. N.getTag() == dwarf::DW_TAG_const_type ||
  794. N.getTag() == dwarf::DW_TAG_volatile_type ||
  795. N.getTag() == dwarf::DW_TAG_restrict_type ||
  796. N.getTag() == dwarf::DW_TAG_atomic_type ||
  797. N.getTag() == dwarf::DW_TAG_member ||
  798. N.getTag() == dwarf::DW_TAG_inheritance ||
  799. N.getTag() == dwarf::DW_TAG_friend,
  800. "invalid tag", &N);
  801. if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
  802. AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
  803. N.getRawExtraData());
  804. }
  805. AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
  806. AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
  807. N.getRawBaseType());
  808. if (N.getDWARFAddressSpace()) {
  809. AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
  810. N.getTag() == dwarf::DW_TAG_reference_type ||
  811. N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
  812. "DWARF address space only applies to pointer or reference types",
  813. &N);
  814. }
  815. }
  816. /// Detect mutually exclusive flags.
  817. static bool hasConflictingReferenceFlags(unsigned Flags) {
  818. return ((Flags & DINode::FlagLValueReference) &&
  819. (Flags & DINode::FlagRValueReference)) ||
  820. ((Flags & DINode::FlagTypePassByValue) &&
  821. (Flags & DINode::FlagTypePassByReference));
  822. }
  823. void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
  824. auto *Params = dyn_cast<MDTuple>(&RawParams);
  825. AssertDI(Params, "invalid template params", &N, &RawParams);
  826. for (Metadata *Op : Params->operands()) {
  827. AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
  828. &N, Params, Op);
  829. }
  830. }
  831. void Verifier::visitDICompositeType(const DICompositeType &N) {
  832. // Common scope checks.
  833. visitDIScope(N);
  834. AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||
  835. N.getTag() == dwarf::DW_TAG_structure_type ||
  836. N.getTag() == dwarf::DW_TAG_union_type ||
  837. N.getTag() == dwarf::DW_TAG_enumeration_type ||
  838. N.getTag() == dwarf::DW_TAG_class_type ||
  839. N.getTag() == dwarf::DW_TAG_variant_part,
  840. "invalid tag", &N);
  841. AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
  842. AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
  843. N.getRawBaseType());
  844. AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
  845. "invalid composite elements", &N, N.getRawElements());
  846. AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
  847. N.getRawVTableHolder());
  848. AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
  849. "invalid reference flags", &N);
  850. unsigned DIBlockByRefStruct = 1 << 4;
  851. AssertDI((N.getFlags() & DIBlockByRefStruct) == 0,
  852. "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
  853. if (N.isVector()) {
  854. const DINodeArray Elements = N.getElements();
  855. AssertDI(Elements.size() == 1 &&
  856. Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
  857. "invalid vector, expected one element of type subrange", &N);
  858. }
  859. if (auto *Params = N.getRawTemplateParams())
  860. visitTemplateParams(N, *Params);
  861. if (N.getTag() == dwarf::DW_TAG_class_type ||
  862. N.getTag() == dwarf::DW_TAG_union_type) {
  863. AssertDI(N.getFile() && !N.getFile()->getFilename().empty(),
  864. "class/union requires a filename", &N, N.getFile());
  865. }
  866. if (auto *D = N.getRawDiscriminator()) {
  867. AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
  868. "discriminator can only appear on variant part");
  869. }
  870. }
  871. void Verifier::visitDISubroutineType(const DISubroutineType &N) {
  872. AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
  873. if (auto *Types = N.getRawTypeArray()) {
  874. AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
  875. for (Metadata *Ty : N.getTypeArray()->operands()) {
  876. AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
  877. }
  878. }
  879. AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
  880. "invalid reference flags", &N);
  881. }
  882. void Verifier::visitDIFile(const DIFile &N) {
  883. AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
  884. Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
  885. if (Checksum) {
  886. AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
  887. "invalid checksum kind", &N);
  888. size_t Size;
  889. switch (Checksum->Kind) {
  890. case DIFile::CSK_MD5:
  891. Size = 32;
  892. break;
  893. case DIFile::CSK_SHA1:
  894. Size = 40;
  895. break;
  896. }
  897. AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
  898. AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
  899. "invalid checksum", &N);
  900. }
  901. }
  902. void Verifier::visitDICompileUnit(const DICompileUnit &N) {
  903. AssertDI(N.isDistinct(), "compile units must be distinct", &N);
  904. AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
  905. // Don't bother verifying the compilation directory or producer string
  906. // as those could be empty.
  907. AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
  908. N.getRawFile());
  909. AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
  910. N.getFile());
  911. verifySourceDebugInfo(N, *N.getFile());
  912. AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
  913. "invalid emission kind", &N);
  914. if (auto *Array = N.getRawEnumTypes()) {
  915. AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
  916. for (Metadata *Op : N.getEnumTypes()->operands()) {
  917. auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
  918. AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
  919. "invalid enum type", &N, N.getEnumTypes(), Op);
  920. }
  921. }
  922. if (auto *Array = N.getRawRetainedTypes()) {
  923. AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
  924. for (Metadata *Op : N.getRetainedTypes()->operands()) {
  925. AssertDI(Op && (isa<DIType>(Op) ||
  926. (isa<DISubprogram>(Op) &&
  927. !cast<DISubprogram>(Op)->isDefinition())),
  928. "invalid retained type", &N, Op);
  929. }
  930. }
  931. if (auto *Array = N.getRawGlobalVariables()) {
  932. AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
  933. for (Metadata *Op : N.getGlobalVariables()->operands()) {
  934. AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)),
  935. "invalid global variable ref", &N, Op);
  936. }
  937. }
  938. if (auto *Array = N.getRawImportedEntities()) {
  939. AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
  940. for (Metadata *Op : N.getImportedEntities()->operands()) {
  941. AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
  942. &N, Op);
  943. }
  944. }
  945. if (auto *Array = N.getRawMacros()) {
  946. AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
  947. for (Metadata *Op : N.getMacros()->operands()) {
  948. AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
  949. }
  950. }
  951. CUVisited.insert(&N);
  952. }
  953. void Verifier::visitDISubprogram(const DISubprogram &N) {
  954. AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
  955. AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
  956. if (auto *F = N.getRawFile())
  957. AssertDI(isa<DIFile>(F), "invalid file", &N, F);
  958. else
  959. AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
  960. if (auto *T = N.getRawType())
  961. AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
  962. AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,
  963. N.getRawContainingType());
  964. if (auto *Params = N.getRawTemplateParams())
  965. visitTemplateParams(N, *Params);
  966. if (auto *S = N.getRawDeclaration())
  967. AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
  968. "invalid subprogram declaration", &N, S);
  969. if (auto *RawNode = N.getRawRetainedNodes()) {
  970. auto *Node = dyn_cast<MDTuple>(RawNode);
  971. AssertDI(Node, "invalid retained nodes list", &N, RawNode);
  972. for (Metadata *Op : Node->operands()) {
  973. AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
  974. "invalid retained nodes, expected DILocalVariable or DILabel",
  975. &N, Node, Op);
  976. }
  977. }
  978. AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
  979. "invalid reference flags", &N);
  980. auto *Unit = N.getRawUnit();
  981. if (N.isDefinition()) {
  982. // Subprogram definitions (not part of the type hierarchy).
  983. AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
  984. AssertDI(Unit, "subprogram definitions must have a compile unit", &N);
  985. AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
  986. if (N.getFile())
  987. verifySourceDebugInfo(*N.getUnit(), *N.getFile());
  988. } else {
  989. // Subprogram declarations (part of the type hierarchy).
  990. AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N);
  991. }
  992. if (auto *RawThrownTypes = N.getRawThrownTypes()) {
  993. auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
  994. AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
  995. for (Metadata *Op : ThrownTypes->operands())
  996. AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
  997. Op);
  998. }
  999. if (N.areAllCallsDescribed())
  1000. AssertDI(N.isDefinition(),
  1001. "DIFlagAllCallsDescribed must be attached to a definition");
  1002. }
  1003. void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
  1004. AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
  1005. AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
  1006. "invalid local scope", &N, N.getRawScope());
  1007. if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
  1008. AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
  1009. }
  1010. void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
  1011. visitDILexicalBlockBase(N);
  1012. AssertDI(N.getLine() || !N.getColumn(),
  1013. "cannot have column info without line info", &N);
  1014. }
  1015. void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
  1016. visitDILexicalBlockBase(N);
  1017. }
  1018. void Verifier::visitDICommonBlock(const DICommonBlock &N) {
  1019. AssertDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
  1020. if (auto *S = N.getRawScope())
  1021. AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
  1022. if (auto *S = N.getRawDecl())
  1023. AssertDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
  1024. }
  1025. void Verifier::visitDINamespace(const DINamespace &N) {
  1026. AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
  1027. if (auto *S = N.getRawScope())
  1028. AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
  1029. }
  1030. void Verifier::visitDIMacro(const DIMacro &N) {
  1031. AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
  1032. N.getMacinfoType() == dwarf::DW_MACINFO_undef,
  1033. "invalid macinfo type", &N);
  1034. AssertDI(!N.getName().empty(), "anonymous macro", &N);
  1035. if (!N.getValue().empty()) {
  1036. assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
  1037. }
  1038. }
  1039. void Verifier::visitDIMacroFile(const DIMacroFile &N) {
  1040. AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
  1041. "invalid macinfo type", &N);
  1042. if (auto *F = N.getRawFile())
  1043. AssertDI(isa<DIFile>(F), "invalid file", &N, F);
  1044. if (auto *Array = N.getRawElements()) {
  1045. AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
  1046. for (Metadata *Op : N.getElements()->operands()) {
  1047. AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
  1048. }
  1049. }
  1050. }
  1051. void Verifier::visitDIModule(const DIModule &N) {
  1052. AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
  1053. AssertDI(!N.getName().empty(), "anonymous module", &N);
  1054. }
  1055. void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
  1056. AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
  1057. }
  1058. void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
  1059. visitDITemplateParameter(N);
  1060. AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
  1061. &N);
  1062. }
  1063. void Verifier::visitDITemplateValueParameter(
  1064. const DITemplateValueParameter &N) {
  1065. visitDITemplateParameter(N);
  1066. AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
  1067. N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
  1068. N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
  1069. "invalid tag", &N);
  1070. }
  1071. void Verifier::visitDIVariable(const DIVariable &N) {
  1072. if (auto *S = N.getRawScope())
  1073. AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
  1074. if (auto *F = N.getRawFile())
  1075. AssertDI(isa<DIFile>(F), "invalid file", &N, F);
  1076. }
  1077. void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
  1078. // Checks common to all variables.
  1079. visitDIVariable(N);
  1080. AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
  1081. AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
  1082. AssertDI(N.getType(), "missing global variable type", &N);
  1083. if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
  1084. AssertDI(isa<DIDerivedType>(Member),
  1085. "invalid static data member declaration", &N, Member);
  1086. }
  1087. }
  1088. void Verifier::visitDILocalVariable(const DILocalVariable &N) {
  1089. // Checks common to all variables.
  1090. visitDIVariable(N);
  1091. AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
  1092. AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
  1093. AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
  1094. "local variable requires a valid scope", &N, N.getRawScope());
  1095. if (auto Ty = N.getType())
  1096. AssertDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
  1097. }
  1098. void Verifier::visitDILabel(const DILabel &N) {
  1099. if (auto *S = N.getRawScope())
  1100. AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
  1101. if (auto *F = N.getRawFile())
  1102. AssertDI(isa<DIFile>(F), "invalid file", &N, F);
  1103. AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
  1104. AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
  1105. "label requires a valid scope", &N, N.getRawScope());
  1106. }
  1107. void Verifier::visitDIExpression(const DIExpression &N) {
  1108. AssertDI(N.isValid(), "invalid expression", &N);
  1109. }
  1110. void Verifier::visitDIGlobalVariableExpression(
  1111. const DIGlobalVariableExpression &GVE) {
  1112. AssertDI(GVE.getVariable(), "missing variable");
  1113. if (auto *Var = GVE.getVariable())
  1114. visitDIGlobalVariable(*Var);
  1115. if (auto *Expr = GVE.getExpression()) {
  1116. visitDIExpression(*Expr);
  1117. if (auto Fragment = Expr->getFragmentInfo())
  1118. verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
  1119. }
  1120. }
  1121. void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
  1122. AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
  1123. if (auto *T = N.getRawType())
  1124. AssertDI(isType(T), "invalid type ref", &N, T);
  1125. if (auto *F = N.getRawFile())
  1126. AssertDI(isa<DIFile>(F), "invalid file", &N, F);
  1127. }
  1128. void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
  1129. AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||
  1130. N.getTag() == dwarf::DW_TAG_imported_declaration,
  1131. "invalid tag", &N);
  1132. if (auto *S = N.getRawScope())
  1133. AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
  1134. AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
  1135. N.getRawEntity());
  1136. }
  1137. void Verifier::visitComdat(const Comdat &C) {
  1138. // In COFF the Module is invalid if the GlobalValue has private linkage.
  1139. // Entities with private linkage don't have entries in the symbol table.
  1140. if (TT.isOSBinFormatCOFF())
  1141. if (const GlobalValue *GV = M.getNamedValue(C.getName()))
  1142. Assert(!GV->hasPrivateLinkage(),
  1143. "comdat global value has private linkage", GV);
  1144. }
  1145. void Verifier::visitModuleIdents(const Module &M) {
  1146. const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
  1147. if (!Idents)
  1148. return;
  1149. // llvm.ident takes a list of metadata entry. Each entry has only one string.
  1150. // Scan each llvm.ident entry and make sure that this requirement is met.
  1151. for (const MDNode *N : Idents->operands()) {
  1152. Assert(N->getNumOperands() == 1,
  1153. "incorrect number of operands in llvm.ident metadata", N);
  1154. Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
  1155. ("invalid value for llvm.ident metadata entry operand"
  1156. "(the operand should be a string)"),
  1157. N->getOperand(0));
  1158. }
  1159. }
  1160. void Verifier::visitModuleCommandLines(const Module &M) {
  1161. const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
  1162. if (!CommandLines)
  1163. return;
  1164. // llvm.commandline takes a list of metadata entry. Each entry has only one
  1165. // string. Scan each llvm.commandline entry and make sure that this
  1166. // requirement is met.
  1167. for (const MDNode *N : CommandLines->operands()) {
  1168. Assert(N->getNumOperands() == 1,
  1169. "incorrect number of operands in llvm.commandline metadata", N);
  1170. Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
  1171. ("invalid value for llvm.commandline metadata entry operand"
  1172. "(the operand should be a string)"),
  1173. N->getOperand(0));
  1174. }
  1175. }
  1176. void Verifier::visitModuleFlags(const Module &M) {
  1177. const NamedMDNode *Flags = M.getModuleFlagsMetadata();
  1178. if (!Flags) return;
  1179. // Scan each flag, and track the flags and requirements.
  1180. DenseMap<const MDString*, const MDNode*> SeenIDs;
  1181. SmallVector<const MDNode*, 16> Requirements;
  1182. for (const MDNode *MDN : Flags->operands())
  1183. visitModuleFlag(MDN, SeenIDs, Requirements);
  1184. // Validate that the requirements in the module are valid.
  1185. for (const MDNode *Requirement : Requirements) {
  1186. const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
  1187. const Metadata *ReqValue = Requirement->getOperand(1);
  1188. const MDNode *Op = SeenIDs.lookup(Flag);
  1189. if (!Op) {
  1190. CheckFailed("invalid requirement on flag, flag is not present in module",
  1191. Flag);
  1192. continue;
  1193. }
  1194. if (Op->getOperand(2) != ReqValue) {
  1195. CheckFailed(("invalid requirement on flag, "
  1196. "flag does not have the required value"),
  1197. Flag);
  1198. continue;
  1199. }
  1200. }
  1201. }
  1202. void
  1203. Verifier::visitModuleFlag(const MDNode *Op,
  1204. DenseMap<const MDString *, const MDNode *> &SeenIDs,
  1205. SmallVectorImpl<const MDNode *> &Requirements) {
  1206. // Each module flag should have three arguments, the merge behavior (a
  1207. // constant int), the flag ID (an MDString), and the value.
  1208. Assert(Op->getNumOperands() == 3,
  1209. "incorrect number of operands in module flag", Op);
  1210. Module::ModFlagBehavior MFB;
  1211. if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
  1212. Assert(
  1213. mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
  1214. "invalid behavior operand in module flag (expected constant integer)",
  1215. Op->getOperand(0));
  1216. Assert(false,
  1217. "invalid behavior operand in module flag (unexpected constant)",
  1218. Op->getOperand(0));
  1219. }
  1220. MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
  1221. Assert(ID, "invalid ID operand in module flag (expected metadata string)",
  1222. Op->getOperand(1));
  1223. // Sanity check the values for behaviors with additional requirements.
  1224. switch (MFB) {
  1225. case Module::Error:
  1226. case Module::Warning:
  1227. case Module::Override:
  1228. // These behavior types accept any value.
  1229. break;
  1230. case Module::Max: {
  1231. Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
  1232. "invalid value for 'max' module flag (expected constant integer)",
  1233. Op->getOperand(2));
  1234. break;
  1235. }
  1236. case Module::Require: {
  1237. // The value should itself be an MDNode with two operands, a flag ID (an
  1238. // MDString), and a value.
  1239. MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
  1240. Assert(Value && Value->getNumOperands() == 2,
  1241. "invalid value for 'require' module flag (expected metadata pair)",
  1242. Op->getOperand(2));
  1243. Assert(isa<MDString>(Value->getOperand(0)),
  1244. ("invalid value for 'require' module flag "
  1245. "(first value operand should be a string)"),
  1246. Value->getOperand(0));
  1247. // Append it to the list of requirements, to check once all module flags are
  1248. // scanned.
  1249. Requirements.push_back(Value);
  1250. break;
  1251. }
  1252. case Module::Append:
  1253. case Module::AppendUnique: {
  1254. // These behavior types require the operand be an MDNode.
  1255. Assert(isa<MDNode>(Op->getOperand(2)),
  1256. "invalid value for 'append'-type module flag "
  1257. "(expected a metadata node)",
  1258. Op->getOperand(2));
  1259. break;
  1260. }
  1261. }
  1262. // Unless this is a "requires" flag, check the ID is unique.
  1263. if (MFB != Module::Require) {
  1264. bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
  1265. Assert(Inserted,
  1266. "module flag identifiers must be unique (or of 'require' type)", ID);
  1267. }
  1268. if (ID->getString() == "wchar_size") {
  1269. ConstantInt *Value
  1270. = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
  1271. Assert(Value, "wchar_size metadata requires constant integer argument");
  1272. }
  1273. if (ID->getString() == "Linker Options") {
  1274. // If the llvm.linker.options named metadata exists, we assume that the
  1275. // bitcode reader has upgraded the module flag. Otherwise the flag might
  1276. // have been created by a client directly.
  1277. Assert(M.getNamedMetadata("llvm.linker.options"),
  1278. "'Linker Options' named metadata no longer supported");
  1279. }
  1280. if (ID->getString() == "CG Profile") {
  1281. for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
  1282. visitModuleFlagCGProfileEntry(MDO);
  1283. }
  1284. }
  1285. void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
  1286. auto CheckFunction = [&](const MDOperand &FuncMDO) {
  1287. if (!FuncMDO)
  1288. return;
  1289. auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
  1290. Assert(F && isa<Function>(F->getValue()), "expected a Function or null",
  1291. FuncMDO);
  1292. };
  1293. auto Node = dyn_cast_or_null<MDNode>(MDO);
  1294. Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
  1295. CheckFunction(Node->getOperand(0));
  1296. CheckFunction(Node->getOperand(1));
  1297. auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
  1298. Assert(Count && Count->getType()->isIntegerTy(),
  1299. "expected an integer constant", Node->getOperand(2));
  1300. }
  1301. /// Return true if this attribute kind only applies to functions.
  1302. static bool isFuncOnlyAttr(Attribute::AttrKind Kind) {
  1303. switch (Kind) {
  1304. case Attribute::NoReturn:
  1305. case Attribute::NoSync:
  1306. case Attribute::WillReturn:
  1307. case Attribute::NoCfCheck:
  1308. case Attribute::NoUnwind:
  1309. case Attribute::NoInline:
  1310. case Attribute::NoFree:
  1311. case Attribute::AlwaysInline:
  1312. case Attribute::OptimizeForSize:
  1313. case Attribute::StackProtect:
  1314. case Attribute::StackProtectReq:
  1315. case Attribute::StackProtectStrong:
  1316. case Attribute::SafeStack:
  1317. case Attribute::ShadowCallStack:
  1318. case Attribute::NoRedZone:
  1319. case Attribute::NoImplicitFloat:
  1320. case Attribute::Naked:
  1321. case Attribute::InlineHint:
  1322. case Attribute::StackAlignment:
  1323. case Attribute::UWTable:
  1324. case Attribute::NonLazyBind:
  1325. case Attribute::ReturnsTwice:
  1326. case Attribute::SanitizeAddress:
  1327. case Attribute::SanitizeHWAddress:
  1328. case Attribute::SanitizeMemTag:
  1329. case Attribute::SanitizeThread:
  1330. case Attribute::SanitizeMemory:
  1331. case Attribute::MinSize:
  1332. case Attribute::NoDuplicate:
  1333. case Attribute::Builtin:
  1334. case Attribute::NoBuiltin:
  1335. case Attribute::Cold:
  1336. case Attribute::OptForFuzzing:
  1337. case Attribute::OptimizeNone:
  1338. case Attribute::JumpTable:
  1339. case Attribute::Convergent:
  1340. case Attribute::ArgMemOnly:
  1341. case Attribute::NoRecurse:
  1342. case Attribute::InaccessibleMemOnly:
  1343. case Attribute::InaccessibleMemOrArgMemOnly:
  1344. case Attribute::AllocSize:
  1345. case Attribute::SpeculativeLoadHardening:
  1346. case Attribute::Speculatable:
  1347. case Attribute::StrictFP:
  1348. return true;
  1349. default:
  1350. break;
  1351. }
  1352. return false;
  1353. }
  1354. /// Return true if this is a function attribute that can also appear on
  1355. /// arguments.
  1356. static bool isFuncOrArgAttr(Attribute::AttrKind Kind) {
  1357. return Kind == Attribute::ReadOnly || Kind == Attribute::WriteOnly ||
  1358. Kind == Attribute::ReadNone;
  1359. }
  1360. void Verifier::verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
  1361. const Value *V) {
  1362. for (Attribute A : Attrs) {
  1363. if (A.isStringAttribute())
  1364. continue;
  1365. if (isFuncOnlyAttr(A.getKindAsEnum())) {
  1366. if (!IsFunction) {
  1367. CheckFailed("Attribute '" + A.getAsString() +
  1368. "' only applies to functions!",
  1369. V);
  1370. return;
  1371. }
  1372. } else if (IsFunction && !isFuncOrArgAttr(A.getKindAsEnum())) {
  1373. CheckFailed("Attribute '" + A.getAsString() +
  1374. "' does not apply to functions!",
  1375. V);
  1376. return;
  1377. }
  1378. }
  1379. }
  1380. // VerifyParameterAttrs - Check the given attributes for an argument or return
  1381. // value of the specified type. The value V is printed in error messages.
  1382. void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
  1383. const Value *V) {
  1384. if (!Attrs.hasAttributes())
  1385. return;
  1386. verifyAttributeTypes(Attrs, /*IsFunction=*/false, V);
  1387. if (Attrs.hasAttribute(Attribute::ImmArg)) {
  1388. Assert(Attrs.getNumAttributes() == 1,
  1389. "Attribute 'immarg' is incompatible with other attributes", V);
  1390. }
  1391. // Check for mutually incompatible attributes. Only inreg is compatible with
  1392. // sret.
  1393. unsigned AttrCount = 0;
  1394. AttrCount += Attrs.hasAttribute(Attribute::ByVal);
  1395. AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
  1396. AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
  1397. Attrs.hasAttribute(Attribute::InReg);
  1398. AttrCount += Attrs.hasAttribute(Attribute::Nest);
  1399. Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
  1400. "and 'sret' are incompatible!",
  1401. V);
  1402. Assert(!(Attrs.hasAttribute(Attribute::InAlloca) &&
  1403. Attrs.hasAttribute(Attribute::ReadOnly)),
  1404. "Attributes "
  1405. "'inalloca and readonly' are incompatible!",
  1406. V);
  1407. Assert(!(Attrs.hasAttribute(Attribute::StructRet) &&
  1408. Attrs.hasAttribute(Attribute::Returned)),
  1409. "Attributes "
  1410. "'sret and returned' are incompatible!",
  1411. V);
  1412. Assert(!(Attrs.hasAttribute(Attribute::ZExt) &&
  1413. Attrs.hasAttribute(Attribute::SExt)),
  1414. "Attributes "
  1415. "'zeroext and signext' are incompatible!",
  1416. V);
  1417. Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
  1418. Attrs.hasAttribute(Attribute::ReadOnly)),
  1419. "Attributes "
  1420. "'readnone and readonly' are incompatible!",
  1421. V);
  1422. Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
  1423. Attrs.hasAttribute(Attribute::WriteOnly)),
  1424. "Attributes "
  1425. "'readnone and writeonly' are incompatible!",
  1426. V);
  1427. Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
  1428. Attrs.hasAttribute(Attribute::WriteOnly)),
  1429. "Attributes "
  1430. "'readonly and writeonly' are incompatible!",
  1431. V);
  1432. Assert(!(Attrs.hasAttribute(Attribute::NoInline) &&
  1433. Attrs.hasAttribute(Attribute::AlwaysInline)),
  1434. "Attributes "
  1435. "'noinline and alwaysinline' are incompatible!",
  1436. V);
  1437. if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
  1438. Assert(Attrs.getByValType() == cast<PointerType>(Ty)->getElementType(),
  1439. "Attribute 'byval' type does not match parameter!", V);
  1440. }
  1441. AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
  1442. Assert(!AttrBuilder(Attrs).overlaps(IncompatibleAttrs),
  1443. "Wrong types for attribute: " +
  1444. AttributeSet::get(Context, IncompatibleAttrs).getAsString(),
  1445. V);
  1446. if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
  1447. SmallPtrSet<Type*, 4> Visited;
  1448. if (!PTy->getElementType()->isSized(&Visited)) {
  1449. Assert(!Attrs.hasAttribute(Attribute::ByVal) &&
  1450. !Attrs.hasAttribute(Attribute::InAlloca),
  1451. "Attributes 'byval' and 'inalloca' do not support unsized types!",
  1452. V);
  1453. }
  1454. if (!isa<PointerType>(PTy->getElementType()))
  1455. Assert(!Attrs.hasAttribute(Attribute::SwiftError),
  1456. "Attribute 'swifterror' only applies to parameters "
  1457. "with pointer to pointer type!",
  1458. V);
  1459. } else {
  1460. Assert(!Attrs.hasAttribute(Attribute::ByVal),
  1461. "Attribute 'byval' only applies to parameters with pointer type!",
  1462. V);
  1463. Assert(!Attrs.hasAttribute(Attribute::SwiftError),
  1464. "Attribute 'swifterror' only applies to parameters "
  1465. "with pointer type!",
  1466. V);
  1467. }
  1468. }
  1469. // Check parameter attributes against a function type.
  1470. // The value V is printed in error messages.
  1471. void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
  1472. const Value *V, bool IsIntrinsic) {
  1473. if (Attrs.isEmpty())
  1474. return;
  1475. bool SawNest = false;
  1476. bool SawReturned = false;
  1477. bool SawSRet = false;
  1478. bool SawSwiftSelf = false;
  1479. bool SawSwiftError = false;
  1480. // Verify return value attributes.
  1481. AttributeSet RetAttrs = Attrs.getRetAttributes();
  1482. Assert((!RetAttrs.hasAttribute(Attribute::ByVal) &&
  1483. !RetAttrs.hasAttribute(Attribute::Nest) &&
  1484. !RetAttrs.hasAttribute(Attribute::StructRet) &&
  1485. !RetAttrs.hasAttribute(Attribute::NoCapture) &&
  1486. !RetAttrs.hasAttribute(Attribute::Returned) &&
  1487. !RetAttrs.hasAttribute(Attribute::InAlloca) &&
  1488. !RetAttrs.hasAttribute(Attribute::SwiftSelf) &&
  1489. !RetAttrs.hasAttribute(Attribute::SwiftError)),
  1490. "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', "
  1491. "'returned', 'swiftself', and 'swifterror' do not apply to return "
  1492. "values!",
  1493. V);
  1494. Assert((!RetAttrs.hasAttribute(Attribute::ReadOnly) &&
  1495. !RetAttrs.hasAttribute(Attribute::WriteOnly) &&
  1496. !RetAttrs.hasAttribute(Attribute::ReadNone)),
  1497. "Attribute '" + RetAttrs.getAsString() +
  1498. "' does not apply to function returns",
  1499. V);
  1500. verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
  1501. // Verify parameter attributes.
  1502. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1503. Type *Ty = FT->getParamType(i);
  1504. AttributeSet ArgAttrs = Attrs.getParamAttributes(i);
  1505. if (!IsIntrinsic) {
  1506. Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg),
  1507. "immarg attribute only applies to intrinsics",V);
  1508. }
  1509. verifyParameterAttrs(ArgAttrs, Ty, V);
  1510. if (ArgAttrs.hasAttribute(Attribute::Nest)) {
  1511. Assert(!SawNest, "More than one parameter has attribute nest!", V);
  1512. SawNest = true;
  1513. }
  1514. if (ArgAttrs.hasAttribute(Attribute::Returned)) {
  1515. Assert(!SawReturned, "More than one parameter has attribute returned!",
  1516. V);
  1517. Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
  1518. "Incompatible argument and return types for 'returned' attribute",
  1519. V);
  1520. SawReturned = true;
  1521. }
  1522. if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
  1523. Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
  1524. Assert(i == 0 || i == 1,
  1525. "Attribute 'sret' is not on first or second parameter!", V);
  1526. SawSRet = true;
  1527. }
  1528. if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
  1529. Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
  1530. SawSwiftSelf = true;
  1531. }
  1532. if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
  1533. Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",
  1534. V);
  1535. SawSwiftError = true;
  1536. }
  1537. if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
  1538. Assert(i == FT->getNumParams() - 1,
  1539. "inalloca isn't on the last parameter!", V);
  1540. }
  1541. }
  1542. if (!Attrs.hasAttributes(AttributeList::FunctionIndex))
  1543. return;
  1544. verifyAttributeTypes(Attrs.getFnAttributes(), /*IsFunction=*/true, V);
  1545. Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
  1546. Attrs.hasFnAttribute(Attribute::ReadOnly)),
  1547. "Attributes 'readnone and readonly' are incompatible!", V);
  1548. Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
  1549. Attrs.hasFnAttribute(Attribute::WriteOnly)),
  1550. "Attributes 'readnone and writeonly' are incompatible!", V);
  1551. Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) &&
  1552. Attrs.hasFnAttribute(Attribute::WriteOnly)),
  1553. "Attributes 'readonly and writeonly' are incompatible!", V);
  1554. Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
  1555. Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)),
  1556. "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
  1557. "incompatible!",
  1558. V);
  1559. Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
  1560. Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)),
  1561. "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
  1562. Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) &&
  1563. Attrs.hasFnAttribute(Attribute::AlwaysInline)),
  1564. "Attributes 'noinline and alwaysinline' are incompatible!", V);
  1565. if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) {
  1566. Assert(Attrs.hasFnAttribute(Attribute::NoInline),
  1567. "Attribute 'optnone' requires 'noinline'!", V);
  1568. Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize),
  1569. "Attributes 'optsize and optnone' are incompatible!", V);
  1570. Assert(!Attrs.hasFnAttribute(Attribute::MinSize),
  1571. "Attributes 'minsize and optnone' are incompatible!", V);
  1572. }
  1573. if (Attrs.hasFnAttribute(Attribute::JumpTable)) {
  1574. const GlobalValue *GV = cast<GlobalValue>(V);
  1575. Assert(GV->hasGlobalUnnamedAddr(),
  1576. "Attribute 'jumptable' requires 'unnamed_addr'", V);
  1577. }
  1578. if (Attrs.hasFnAttribute(Attribute::AllocSize)) {
  1579. std::pair<unsigned, Optional<unsigned>> Args =
  1580. Attrs.getAllocSizeArgs(AttributeList::FunctionIndex);
  1581. auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
  1582. if (ParamNo >= FT->getNumParams()) {
  1583. CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
  1584. return false;
  1585. }
  1586. if (!FT->getParamType(ParamNo)->isIntegerTy()) {
  1587. CheckFailed("'allocsize' " + Name +
  1588. " argument must refer to an integer parameter",
  1589. V);
  1590. return false;
  1591. }
  1592. return true;
  1593. };
  1594. if (!CheckParam("element size", Args.first))
  1595. return;
  1596. if (Args.second && !CheckParam("number of elements", *Args.second))
  1597. return;
  1598. }
  1599. }
  1600. void Verifier::verifyFunctionMetadata(
  1601. ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
  1602. for (const auto &Pair : MDs) {
  1603. if (Pair.first == LLVMContext::MD_prof) {
  1604. MDNode *MD = Pair.second;
  1605. Assert(MD->getNumOperands() >= 2,
  1606. "!prof annotations should have no less than 2 operands", MD);
  1607. // Check first operand.
  1608. Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
  1609. MD);
  1610. Assert(isa<MDString>(MD->getOperand(0)),
  1611. "expected string with name of the !prof annotation", MD);
  1612. MDString *MDS = cast<MDString>(MD->getOperand(0));
  1613. StringRef ProfName = MDS->getString();
  1614. Assert(ProfName.equals("function_entry_count") ||
  1615. ProfName.equals("synthetic_function_entry_count"),
  1616. "first operand should be 'function_entry_count'"
  1617. " or 'synthetic_function_entry_count'",
  1618. MD);
  1619. // Check second operand.
  1620. Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
  1621. MD);
  1622. Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
  1623. "expected integer argument to function_entry_count", MD);
  1624. }
  1625. }
  1626. }
  1627. void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
  1628. if (!ConstantExprVisited.insert(EntryC).second)
  1629. return;
  1630. SmallVector<const Constant *, 16> Stack;
  1631. Stack.push_back(EntryC);
  1632. while (!Stack.empty()) {
  1633. const Constant *C = Stack.pop_back_val();
  1634. // Check this constant expression.
  1635. if (const auto *CE = dyn_cast<ConstantExpr>(C))
  1636. visitConstantExpr(CE);
  1637. if (const auto *GV = dyn_cast<GlobalValue>(C)) {
  1638. // Global Values get visited separately, but we do need to make sure
  1639. // that the global value is in the correct module
  1640. Assert(GV->getParent() == &M, "Referencing global in another module!",
  1641. EntryC, &M, GV, GV->getParent());
  1642. continue;
  1643. }
  1644. // Visit all sub-expressions.
  1645. for (const Use &U : C->operands()) {
  1646. const auto *OpC = dyn_cast<Constant>(U);
  1647. if (!OpC)
  1648. continue;
  1649. if (!ConstantExprVisited.insert(OpC).second)
  1650. continue;
  1651. Stack.push_back(OpC);
  1652. }
  1653. }
  1654. }
  1655. void Verifier::visitConstantExpr(const ConstantExpr *CE) {
  1656. if (CE->getOpcode() == Instruction::BitCast)
  1657. Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
  1658. CE->getType()),
  1659. "Invalid bitcast", CE);
  1660. if (CE->getOpcode() == Instruction::IntToPtr ||
  1661. CE->getOpcode() == Instruction::PtrToInt) {
  1662. auto *PtrTy = CE->getOpcode() == Instruction::IntToPtr
  1663. ? CE->getType()
  1664. : CE->getOperand(0)->getType();
  1665. StringRef Msg = CE->getOpcode() == Instruction::IntToPtr
  1666. ? "inttoptr not supported for non-integral pointers"
  1667. : "ptrtoint not supported for non-integral pointers";
  1668. Assert(
  1669. !DL.isNonIntegralPointerType(cast<PointerType>(PtrTy->getScalarType())),
  1670. Msg);
  1671. }
  1672. }
  1673. bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
  1674. // There shouldn't be more attribute sets than there are parameters plus the
  1675. // function and return value.
  1676. return Attrs.getNumAttrSets() <= Params + 2;
  1677. }
  1678. /// Verify that statepoint intrinsic is well formed.
  1679. void Verifier::verifyStatepoint(const CallBase &Call) {
  1680. assert(Call.getCalledFunction() &&
  1681. Call.getCalledFunction()->getIntrinsicID() ==
  1682. Intrinsic::experimental_gc_statepoint);
  1683. Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
  1684. !Call.onlyAccessesArgMemory(),
  1685. "gc.statepoint must read and write all memory to preserve "
  1686. "reordering restrictions required by safepoint semantics",
  1687. Call);
  1688. const int64_t NumPatchBytes =
  1689. cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
  1690. assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
  1691. Assert(NumPatchBytes >= 0,
  1692. "gc.statepoint number of patchable bytes must be "
  1693. "positive",
  1694. Call);
  1695. const Value *Target = Call.getArgOperand(2);
  1696. auto *PT = dyn_cast<PointerType>(Target->getType());
  1697. Assert(PT && PT->getElementType()->isFunctionTy(),
  1698. "gc.statepoint callee must be of function pointer type", Call, Target);
  1699. FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
  1700. const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
  1701. Assert(NumCallArgs >= 0,
  1702. "gc.statepoint number of arguments to underlying call "
  1703. "must be positive",
  1704. Call);
  1705. const int NumParams = (int)TargetFuncType->getNumParams();
  1706. if (TargetFuncType->isVarArg()) {
  1707. Assert(NumCallArgs >= NumParams,
  1708. "gc.statepoint mismatch in number of vararg call args", Call);
  1709. // TODO: Remove this limitation
  1710. Assert(TargetFuncType->getReturnType()->isVoidTy(),
  1711. "gc.statepoint doesn't support wrapping non-void "
  1712. "vararg functions yet",
  1713. Call);
  1714. } else
  1715. Assert(NumCallArgs == NumParams,
  1716. "gc.statepoint mismatch in number of call args", Call);
  1717. const uint64_t Flags
  1718. = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
  1719. Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
  1720. "unknown flag used in gc.statepoint flags argument", Call);
  1721. // Verify that the types of the call parameter arguments match
  1722. // the type of the wrapped callee.
  1723. AttributeList Attrs = Call.getAttributes();
  1724. for (int i = 0; i < NumParams; i++) {
  1725. Type *ParamType = TargetFuncType->getParamType(i);
  1726. Type *ArgType = Call.getArgOperand(5 + i)->getType();
  1727. Assert(ArgType == ParamType,
  1728. "gc.statepoint call argument does not match wrapped "
  1729. "function type",
  1730. Call);
  1731. if (TargetFuncType->isVarArg()) {
  1732. AttributeSet ArgAttrs = Attrs.getParamAttributes(5 + i);
  1733. Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
  1734. "Attribute 'sret' cannot be used for vararg call arguments!",
  1735. Call);
  1736. }
  1737. }
  1738. const int EndCallArgsInx = 4 + NumCallArgs;
  1739. const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
  1740. Assert(isa<ConstantInt>(NumTransitionArgsV),
  1741. "gc.statepoint number of transition arguments "
  1742. "must be constant integer",
  1743. Call);
  1744. const int NumTransitionArgs =
  1745. cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
  1746. Assert(NumTransitionArgs >= 0,
  1747. "gc.statepoint number of transition arguments must be positive", Call);
  1748. const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
  1749. const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
  1750. Assert(isa<ConstantInt>(NumDeoptArgsV),
  1751. "gc.statepoint number of deoptimization arguments "
  1752. "must be constant integer",
  1753. Call);
  1754. const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
  1755. Assert(NumDeoptArgs >= 0,
  1756. "gc.statepoint number of deoptimization arguments "
  1757. "must be positive",
  1758. Call);
  1759. const int ExpectedNumArgs =
  1760. 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
  1761. Assert(ExpectedNumArgs <= (int)Call.arg_size(),
  1762. "gc.statepoint too few arguments according to length fields", Call);
  1763. // Check that the only uses of this gc.statepoint are gc.result or
  1764. // gc.relocate calls which are tied to this statepoint and thus part
  1765. // of the same statepoint sequence
  1766. for (const User *U : Call.users()) {
  1767. const CallInst *UserCall = dyn_cast<const CallInst>(U);
  1768. Assert(UserCall, "illegal use of statepoint token", Call, U);
  1769. if (!UserCall)
  1770. continue;
  1771. Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
  1772. "gc.result or gc.relocate are the only value uses "
  1773. "of a gc.statepoint",
  1774. Call, U);
  1775. if (isa<GCResultInst>(UserCall)) {
  1776. Assert(UserCall->getArgOperand(0) == &Call,
  1777. "gc.result connected to wrong gc.statepoint", Call, UserCall);
  1778. } else if (isa<GCRelocateInst>(Call)) {
  1779. Assert(UserCall->getArgOperand(0) == &Call,
  1780. "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
  1781. }
  1782. }
  1783. // Note: It is legal for a single derived pointer to be listed multiple
  1784. // times. It's non-optimal, but it is legal. It can also happen after
  1785. // insertion if we strip a bitcast away.
  1786. // Note: It is really tempting to check that each base is relocated and
  1787. // that a derived pointer is never reused as a base pointer. This turns
  1788. // out to be problematic since optimizations run after safepoint insertion
  1789. // can recognize equality properties that the insertion logic doesn't know
  1790. // about. See example statepoint.ll in the verifier subdirectory
  1791. }
  1792. void Verifier::verifyFrameRecoverIndices() {
  1793. for (auto &Counts : FrameEscapeInfo) {
  1794. Function *F = Counts.first;
  1795. unsigned EscapedObjectCount = Counts.second.first;
  1796. unsigned MaxRecoveredIndex = Counts.second.second;
  1797. Assert(MaxRecoveredIndex <= EscapedObjectCount,
  1798. "all indices passed to llvm.localrecover must be less than the "
  1799. "number of arguments passed to llvm.localescape in the parent "
  1800. "function",
  1801. F);
  1802. }
  1803. }
  1804. static Instruction *getSuccPad(Instruction *Terminator) {
  1805. BasicBlock *UnwindDest;
  1806. if (auto *II = dyn_cast<InvokeInst>(Terminator))
  1807. UnwindDest = II->getUnwindDest();
  1808. else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
  1809. UnwindDest = CSI->getUnwindDest();
  1810. else
  1811. UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
  1812. return UnwindDest->getFirstNonPHI();
  1813. }
  1814. void Verifier::verifySiblingFuncletUnwinds() {
  1815. SmallPtrSet<Instruction *, 8> Visited;
  1816. SmallPtrSet<Instruction *, 8> Active;
  1817. for (const auto &Pair : SiblingFuncletInfo) {
  1818. Instruction *PredPad = Pair.first;
  1819. if (Visited.count(PredPad))
  1820. continue;
  1821. Active.insert(PredPad);
  1822. Instruction *Terminator = Pair.second;
  1823. do {
  1824. Instruction *SuccPad = getSuccPad(Terminator);
  1825. if (Active.count(SuccPad)) {
  1826. // Found a cycle; report error
  1827. Instruction *CyclePad = SuccPad;
  1828. SmallVector<Instruction *, 8> CycleNodes;
  1829. do {
  1830. CycleNodes.push_back(CyclePad);
  1831. Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
  1832. if (CycleTerminator != CyclePad)
  1833. CycleNodes.push_back(CycleTerminator);
  1834. CyclePad = getSuccPad(CycleTerminator);
  1835. } while (CyclePad != SuccPad);
  1836. Assert(false, "EH pads can't handle each other's exceptions",
  1837. ArrayRef<Instruction *>(CycleNodes));
  1838. }
  1839. // Don't re-walk a node we've already checked
  1840. if (!Visited.insert(SuccPad).second)
  1841. break;
  1842. // Walk to this successor if it has a map entry.
  1843. PredPad = SuccPad;
  1844. auto TermI = SiblingFuncletInfo.find(PredPad);
  1845. if (TermI == SiblingFuncletInfo.end())
  1846. break;
  1847. Terminator = TermI->second;
  1848. Active.insert(PredPad);
  1849. } while (true);
  1850. // Each node only has one successor, so we've walked all the active
  1851. // nodes' successors.
  1852. Active.clear();
  1853. }
  1854. }
  1855. // visitFunction - Verify that a function is ok.
  1856. //
  1857. void Verifier::visitFunction(const Function &F) {
  1858. visitGlobalValue(F);
  1859. // Check function arguments.
  1860. FunctionType *FT = F.getFunctionType();
  1861. unsigned NumArgs = F.arg_size();
  1862. Assert(&Context == &F.getContext(),
  1863. "Function context does not match Module context!", &F);
  1864. Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
  1865. Assert(FT->getNumParams() == NumArgs,
  1866. "# formal arguments must match # of arguments for function type!", &F,
  1867. FT);
  1868. Assert(F.getReturnType()->isFirstClassType() ||
  1869. F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
  1870. "Functions cannot return aggregate values!", &F);
  1871. Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
  1872. "Invalid struct return type!", &F);
  1873. AttributeList Attrs = F.getAttributes();
  1874. Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
  1875. "Attribute after last parameter!", &F);
  1876. bool isLLVMdotName = F.getName().size() >= 5 &&
  1877. F.getName().substr(0, 5) == "llvm.";
  1878. // Check function attributes.
  1879. verifyFunctionAttrs(FT, Attrs, &F, isLLVMdotName);
  1880. // On function declarations/definitions, we do not support the builtin
  1881. // attribute. We do not check this in VerifyFunctionAttrs since that is
  1882. // checking for Attributes that can/can not ever be on functions.
  1883. Assert(!Attrs.hasFnAttribute(Attribute::Builtin),
  1884. "Attribute 'builtin' can only be applied to a callsite.", &F);
  1885. // Check that this function meets the restrictions on this calling convention.
  1886. // Sometimes varargs is used for perfectly forwarding thunks, so some of these
  1887. // restrictions can be lifted.
  1888. switch (F.getCallingConv()) {
  1889. default:
  1890. case CallingConv::C:
  1891. break;
  1892. case CallingConv::AMDGPU_KERNEL:
  1893. case CallingConv::SPIR_KERNEL:
  1894. Assert(F.getReturnType()->isVoidTy(),
  1895. "Calling convention requires void return type", &F);
  1896. LLVM_FALLTHROUGH;
  1897. case CallingConv::AMDGPU_VS:
  1898. case CallingConv::AMDGPU_HS:
  1899. case CallingConv::AMDGPU_GS:
  1900. case CallingConv::AMDGPU_PS:
  1901. case CallingConv::AMDGPU_CS:
  1902. Assert(!F.hasStructRetAttr(),
  1903. "Calling convention does not allow sret", &F);
  1904. LLVM_FALLTHROUGH;
  1905. case CallingConv::Fast:
  1906. case CallingConv::Cold:
  1907. case CallingConv::Intel_OCL_BI:
  1908. case CallingConv::PTX_Kernel:
  1909. case CallingConv::PTX_Device:
  1910. Assert(!F.isVarArg(), "Calling convention does not support varargs or "
  1911. "perfect forwarding!",
  1912. &F);
  1913. break;
  1914. }
  1915. // Check that the argument values match the function type for this function...
  1916. unsigned i = 0;
  1917. for (const Argument &Arg : F.args()) {
  1918. Assert(Arg.getType() == FT->getParamType(i),
  1919. "Argument value does not match function argument type!", &Arg,
  1920. FT->getParamType(i));
  1921. Assert(Arg.getType()->isFirstClassType(),
  1922. "Function arguments must have first-class types!", &Arg);
  1923. if (!isLLVMdotName) {
  1924. Assert(!Arg.getType()->isMetadataTy(),
  1925. "Function takes metadata but isn't an intrinsic", &Arg, &F);
  1926. Assert(!Arg.getType()->isTokenTy(),
  1927. "Function takes token but isn't an intrinsic", &Arg, &F);
  1928. }
  1929. // Check that swifterror argument is only used by loads and stores.
  1930. if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) {
  1931. verifySwiftErrorValue(&Arg);
  1932. }
  1933. ++i;
  1934. }
  1935. if (!isLLVMdotName)
  1936. Assert(!F.getReturnType()->isTokenTy(),
  1937. "Functions returns a token but isn't an intrinsic", &F);
  1938. // Get the function metadata attachments.
  1939. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  1940. F.getAllMetadata(MDs);
  1941. assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
  1942. verifyFunctionMetadata(MDs);
  1943. // Check validity of the personality function
  1944. if (F.hasPersonalityFn()) {
  1945. auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
  1946. if (Per)
  1947. Assert(Per->getParent() == F.getParent(),
  1948. "Referencing personality function in another module!",
  1949. &F, F.getParent(), Per, Per->getParent());
  1950. }
  1951. if (F.isMaterializable()) {
  1952. // Function has a body somewhere we can't see.
  1953. Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
  1954. MDs.empty() ? nullptr : MDs.front().second);
  1955. } else if (F.isDeclaration()) {
  1956. for (const auto &I : MDs) {
  1957. // This is used for call site debug information.
  1958. AssertDI(I.first != LLVMContext::MD_dbg ||
  1959. !cast<DISubprogram>(I.second)->isDistinct(),
  1960. "function declaration may only have a unique !dbg attachment",
  1961. &F);
  1962. Assert(I.first != LLVMContext::MD_prof,
  1963. "function declaration may not have a !prof attachment", &F);
  1964. // Verify the metadata itself.
  1965. visitMDNode(*I.second);
  1966. }
  1967. Assert(!F.hasPersonalityFn(),
  1968. "Function declaration shouldn't have a personality routine", &F);
  1969. } else {
  1970. // Verify that this function (which has a body) is not named "llvm.*". It
  1971. // is not legal to define intrinsics.
  1972. Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
  1973. // Check the entry node
  1974. const BasicBlock *Entry = &F.getEntryBlock();
  1975. Assert(pred_empty(Entry),
  1976. "Entry block to function must not have predecessors!", Entry);
  1977. // The address of the entry block cannot be taken, unless it is dead.
  1978. if (Entry->hasAddressTaken()) {
  1979. Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
  1980. "blockaddress may not be used with the entry block!", Entry);
  1981. }
  1982. unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
  1983. // Visit metadata attachments.
  1984. for (const auto &I : MDs) {
  1985. // Verify that the attachment is legal.
  1986. switch (I.first) {
  1987. default:
  1988. break;
  1989. case LLVMContext::MD_dbg: {
  1990. ++NumDebugAttachments;
  1991. AssertDI(NumDebugAttachments == 1,
  1992. "function must have a single !dbg attachment", &F, I.second);
  1993. AssertDI(isa<DISubprogram>(I.second),
  1994. "function !dbg attachment must be a subprogram", &F, I.second);
  1995. auto *SP = cast<DISubprogram>(I.second);
  1996. const Function *&AttachedTo = DISubprogramAttachments[SP];
  1997. AssertDI(!AttachedTo || AttachedTo == &F,
  1998. "DISubprogram attached to more than one function", SP, &F);
  1999. AttachedTo = &F;
  2000. break;
  2001. }
  2002. case LLVMContext::MD_prof:
  2003. ++NumProfAttachments;
  2004. Assert(NumProfAttachments == 1,
  2005. "function must have a single !prof attachment", &F, I.second);
  2006. break;
  2007. }
  2008. // Verify the metadata itself.
  2009. visitMDNode(*I.second);
  2010. }
  2011. }
  2012. // If this function is actually an intrinsic, verify that it is only used in
  2013. // direct call/invokes, never having its "address taken".
  2014. // Only do this if the module is materialized, otherwise we don't have all the
  2015. // uses.
  2016. if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
  2017. const User *U;
  2018. if (F.hasAddressTaken(&U))
  2019. Assert(false, "Invalid user of intrinsic instruction!", U);
  2020. }
  2021. auto *N = F.getSubprogram();
  2022. HasDebugInfo = (N != nullptr);
  2023. if (!HasDebugInfo)
  2024. return;
  2025. // Check that all !dbg attachments lead to back to N (or, at least, another
  2026. // subprogram that describes the same function).
  2027. //
  2028. // FIXME: Check this incrementally while visiting !dbg attachments.
  2029. // FIXME: Only check when N is the canonical subprogram for F.
  2030. SmallPtrSet<const MDNode *, 32> Seen;
  2031. auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
  2032. // Be careful about using DILocation here since we might be dealing with
  2033. // broken code (this is the Verifier after all).
  2034. const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
  2035. if (!DL)
  2036. return;
  2037. if (!Seen.insert(DL).second)
  2038. return;
  2039. Metadata *Parent = DL->getRawScope();
  2040. AssertDI(Parent && isa<DILocalScope>(Parent),
  2041. "DILocation's scope must be a DILocalScope", N, &F, &I, DL,
  2042. Parent);
  2043. DILocalScope *Scope = DL->getInlinedAtScope();
  2044. if (Scope && !Seen.insert(Scope).second)
  2045. return;
  2046. DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
  2047. // Scope and SP could be the same MDNode and we don't want to skip
  2048. // validation in that case
  2049. if (SP && ((Scope != SP) && !Seen.insert(SP).second))
  2050. return;
  2051. // FIXME: Once N is canonical, check "SP == &N".
  2052. AssertDI(SP->describes(&F),
  2053. "!dbg attachment points at wrong subprogram for function", N, &F,
  2054. &I, DL, Scope, SP);
  2055. };
  2056. for (auto &BB : F)
  2057. for (auto &I : BB) {
  2058. VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
  2059. // The llvm.loop annotations also contain two DILocations.
  2060. if (auto MD = I.getMetadata(LLVMContext::MD_loop))
  2061. for (unsigned i = 1; i < MD->getNumOperands(); ++i)
  2062. VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
  2063. if (BrokenDebugInfo)
  2064. return;
  2065. }
  2066. }
  2067. // verifyBasicBlock - Verify that a basic block is well formed...
  2068. //
  2069. void Verifier::visitBasicBlock(BasicBlock &BB) {
  2070. InstsInThisBlock.clear();
  2071. // Ensure that basic blocks have terminators!
  2072. Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
  2073. // Check constraints that this basic block imposes on all of the PHI nodes in
  2074. // it.
  2075. if (isa<PHINode>(BB.front())) {
  2076. SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
  2077. SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
  2078. llvm::sort(Preds);
  2079. for (const PHINode &PN : BB.phis()) {
  2080. // Ensure that PHI nodes have at least one entry!
  2081. Assert(PN.getNumIncomingValues() != 0,
  2082. "PHI nodes must have at least one entry. If the block is dead, "
  2083. "the PHI should be removed!",
  2084. &PN);
  2085. Assert(PN.getNumIncomingValues() == Preds.size(),
  2086. "PHINode should have one entry for each predecessor of its "
  2087. "parent basic block!",
  2088. &PN);
  2089. // Get and sort all incoming values in the PHI node...
  2090. Values.clear();
  2091. Values.reserve(PN.getNumIncomingValues());
  2092. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
  2093. Values.push_back(
  2094. std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
  2095. llvm::sort(Values);
  2096. for (unsigned i = 0, e = Values.size(); i != e; ++i) {
  2097. // Check to make sure that if there is more than one entry for a
  2098. // particular basic block in this PHI node, that the incoming values are
  2099. // all identical.
  2100. //
  2101. Assert(i == 0 || Values[i].first != Values[i - 1].first ||
  2102. Values[i].second == Values[i - 1].second,
  2103. "PHI node has multiple entries for the same basic block with "
  2104. "different incoming values!",
  2105. &PN, Values[i].first, Values[i].second, Values[i - 1].second);
  2106. // Check to make sure that the predecessors and PHI node entries are
  2107. // matched up.
  2108. Assert(Values[i].first == Preds[i],
  2109. "PHI node entries do not match predecessors!", &PN,
  2110. Values[i].first, Preds[i]);
  2111. }
  2112. }
  2113. }
  2114. // Check that all instructions have their parent pointers set up correctly.
  2115. for (auto &I : BB)
  2116. {
  2117. Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
  2118. }
  2119. }
  2120. void Verifier::visitTerminator(Instruction &I) {
  2121. // Ensure that terminators only exist at the end of the basic block.
  2122. Assert(&I == I.getParent()->getTerminator(),
  2123. "Terminator found in the middle of a basic block!", I.getParent());
  2124. visitInstruction(I);
  2125. }
  2126. void Verifier::visitBranchInst(BranchInst &BI) {
  2127. if (BI.isConditional()) {
  2128. Assert(BI.getCondition()->getType()->isIntegerTy(1),
  2129. "Branch condition is not 'i1' type!", &BI, BI.getCondition());
  2130. }
  2131. visitTerminator(BI);
  2132. }
  2133. void Verifier::visitReturnInst(ReturnInst &RI) {
  2134. Function *F = RI.getParent()->getParent();
  2135. unsigned N = RI.getNumOperands();
  2136. if (F->getReturnType()->isVoidTy())
  2137. Assert(N == 0,
  2138. "Found return instr that returns non-void in Function of void "
  2139. "return type!",
  2140. &RI, F->getReturnType());
  2141. else
  2142. Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
  2143. "Function return type does not match operand "
  2144. "type of return inst!",
  2145. &RI, F->getReturnType());
  2146. // Check to make sure that the return value has necessary properties for
  2147. // terminators...
  2148. visitTerminator(RI);
  2149. }
  2150. void Verifier::visitSwitchInst(SwitchInst &SI) {
  2151. // Check to make sure that all of the constants in the switch instruction
  2152. // have the same type as the switched-on value.
  2153. Type *SwitchTy = SI.getCondition()->getType();
  2154. SmallPtrSet<ConstantInt*, 32> Constants;
  2155. for (auto &Case : SI.cases()) {
  2156. Assert(Case.getCaseValue()->getType() == SwitchTy,
  2157. "Switch constants must all be same type as switch value!", &SI);
  2158. Assert(Constants.insert(Case.getCaseValue()).second,
  2159. "Duplicate integer as switch case", &SI, Case.getCaseValue());
  2160. }
  2161. visitTerminator(SI);
  2162. }
  2163. void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
  2164. Assert(BI.getAddress()->getType()->isPointerTy(),
  2165. "Indirectbr operand must have pointer type!", &BI);
  2166. for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
  2167. Assert(BI.getDestination(i)->getType()->isLabelTy(),
  2168. "Indirectbr destinations must all have pointer type!", &BI);
  2169. visitTerminator(BI);
  2170. }
  2171. void Verifier::visitCallBrInst(CallBrInst &CBI) {
  2172. Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!",
  2173. &CBI);
  2174. Assert(CBI.getType()->isVoidTy(), "Callbr return value is not supported!",
  2175. &CBI);
  2176. for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i)
  2177. Assert(CBI.getSuccessor(i)->getType()->isLabelTy(),
  2178. "Callbr successors must all have pointer type!", &CBI);
  2179. for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) {
  2180. Assert(i >= CBI.getNumArgOperands() || !isa<BasicBlock>(CBI.getOperand(i)),
  2181. "Using an unescaped label as a callbr argument!", &CBI);
  2182. if (isa<BasicBlock>(CBI.getOperand(i)))
  2183. for (unsigned j = i + 1; j != e; ++j)
  2184. Assert(CBI.getOperand(i) != CBI.getOperand(j),
  2185. "Duplicate callbr destination!", &CBI);
  2186. }
  2187. visitTerminator(CBI);
  2188. }
  2189. void Verifier::visitSelectInst(SelectInst &SI) {
  2190. Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
  2191. SI.getOperand(2)),
  2192. "Invalid operands for select instruction!", &SI);
  2193. Assert(SI.getTrueValue()->getType() == SI.getType(),
  2194. "Select values must have same type as select instruction!", &SI);
  2195. visitInstruction(SI);
  2196. }
  2197. /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
  2198. /// a pass, if any exist, it's an error.
  2199. ///
  2200. void Verifier::visitUserOp1(Instruction &I) {
  2201. Assert(false, "User-defined operators should not live outside of a pass!", &I);
  2202. }
  2203. void Verifier::visitTruncInst(TruncInst &I) {
  2204. // Get the source and destination types
  2205. Type *SrcTy = I.getOperand(0)->getType();
  2206. Type *DestTy = I.getType();
  2207. // Get the size of the types in bits, we'll need this later
  2208. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2209. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2210. Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
  2211. Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
  2212. Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2213. "trunc source and destination must both be a vector or neither", &I);
  2214. Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
  2215. visitInstruction(I);
  2216. }
  2217. void Verifier::visitZExtInst(ZExtInst &I) {
  2218. // Get the source and destination types
  2219. Type *SrcTy = I.getOperand(0)->getType();
  2220. Type *DestTy = I.getType();
  2221. // Get the size of the types in bits, we'll need this later
  2222. Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
  2223. Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
  2224. Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2225. "zext source and destination must both be a vector or neither", &I);
  2226. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2227. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2228. Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
  2229. visitInstruction(I);
  2230. }
  2231. void Verifier::visitSExtInst(SExtInst &I) {
  2232. // Get the source and destination types
  2233. Type *SrcTy = I.getOperand(0)->getType();
  2234. Type *DestTy = I.getType();
  2235. // Get the size of the types in bits, we'll need this later
  2236. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2237. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2238. Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
  2239. Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
  2240. Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2241. "sext source and destination must both be a vector or neither", &I);
  2242. Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
  2243. visitInstruction(I);
  2244. }
  2245. void Verifier::visitFPTruncInst(FPTruncInst &I) {
  2246. // Get the source and destination types
  2247. Type *SrcTy = I.getOperand(0)->getType();
  2248. Type *DestTy = I.getType();
  2249. // Get the size of the types in bits, we'll need this later
  2250. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2251. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2252. Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
  2253. Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
  2254. Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2255. "fptrunc source and destination must both be a vector or neither", &I);
  2256. Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
  2257. visitInstruction(I);
  2258. }
  2259. void Verifier::visitFPExtInst(FPExtInst &I) {
  2260. // Get the source and destination types
  2261. Type *SrcTy = I.getOperand(0)->getType();
  2262. Type *DestTy = I.getType();
  2263. // Get the size of the types in bits, we'll need this later
  2264. unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
  2265. unsigned DestBitSize = DestTy->getScalarSizeInBits();
  2266. Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
  2267. Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
  2268. Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
  2269. "fpext source and destination must both be a vector or neither", &I);
  2270. Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
  2271. visitInstruction(I);
  2272. }
  2273. void Verifier::visitUIToFPInst(UIToFPInst &I) {
  2274. // Get the source and destination types
  2275. Type *SrcTy = I.getOperand(0)->getType();
  2276. Type *DestTy = I.getType();
  2277. bool SrcVec = SrcTy->isVectorTy();
  2278. bool DstVec = DestTy->isVectorTy();
  2279. Assert(SrcVec == DstVec,
  2280. "UIToFP source and dest must both be vector or scalar", &I);
  2281. Assert(SrcTy->isIntOrIntVectorTy(),
  2282. "UIToFP source must be integer or integer vector", &I);
  2283. Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
  2284. &I);
  2285. if (SrcVec && DstVec)
  2286. Assert(cast<VectorType>(SrcTy)->getNumElements() ==
  2287. cast<VectorType>(DestTy)->getNumElements(),
  2288. "UIToFP source and dest vector length mismatch", &I);
  2289. visitInstruction(I);
  2290. }
  2291. void Verifier::visitSIToFPInst(SIToFPInst &I) {
  2292. // Get the source and destination types
  2293. Type *SrcTy = I.getOperand(0)->getType();
  2294. Type *DestTy = I.getType();
  2295. bool SrcVec = SrcTy->isVectorTy();
  2296. bool DstVec = DestTy->isVectorTy();
  2297. Assert(SrcVec == DstVec,
  2298. "SIToFP source and dest must both be vector or scalar", &I);
  2299. Assert(SrcTy->isIntOrIntVectorTy(),
  2300. "SIToFP source must be integer or integer vector", &I);
  2301. Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
  2302. &I);
  2303. if (SrcVec && DstVec)
  2304. Assert(cast<VectorType>(SrcTy)->getNumElements() ==
  2305. cast<VectorType>(DestTy)->getNumElements(),
  2306. "SIToFP source and dest vector length mismatch", &I);
  2307. visitInstruction(I);
  2308. }
  2309. void Verifier::visitFPToUIInst(FPToUIInst &I) {
  2310. // Get the source and destination types
  2311. Type *SrcTy = I.getOperand(0)->getType();
  2312. Type *DestTy = I.getType();
  2313. bool SrcVec = SrcTy->isVectorTy();
  2314. bool DstVec = DestTy->isVectorTy();
  2315. Assert(SrcVec == DstVec,
  2316. "FPToUI source and dest must both be vector or scalar", &I);
  2317. Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
  2318. &I);
  2319. Assert(DestTy->isIntOrIntVectorTy(),
  2320. "FPToUI result must be integer or integer vector", &I);
  2321. if (SrcVec && DstVec)
  2322. Assert(cast<VectorType>(SrcTy)->getNumElements() ==
  2323. cast<VectorType>(DestTy)->getNumElements(),
  2324. "FPToUI source and dest vector length mismatch", &I);
  2325. visitInstruction(I);
  2326. }
  2327. void Verifier::visitFPToSIInst(FPToSIInst &I) {
  2328. // Get the source and destination types
  2329. Type *SrcTy = I.getOperand(0)->getType();
  2330. Type *DestTy = I.getType();
  2331. bool SrcVec = SrcTy->isVectorTy();
  2332. bool DstVec = DestTy->isVectorTy();
  2333. Assert(SrcVec == DstVec,
  2334. "FPToSI source and dest must both be vector or scalar", &I);
  2335. Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
  2336. &I);
  2337. Assert(DestTy->isIntOrIntVectorTy(),
  2338. "FPToSI result must be integer or integer vector", &I);
  2339. if (SrcVec && DstVec)
  2340. Assert(cast<VectorType>(SrcTy)->getNumElements() ==
  2341. cast<VectorType>(DestTy)->getNumElements(),
  2342. "FPToSI source and dest vector length mismatch", &I);
  2343. visitInstruction(I);
  2344. }
  2345. void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
  2346. // Get the source and destination types
  2347. Type *SrcTy = I.getOperand(0)->getType();
  2348. Type *DestTy = I.getType();
  2349. Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
  2350. if (auto *PTy = dyn_cast<PointerType>(SrcTy->getScalarType()))
  2351. Assert(!DL.isNonIntegralPointerType(PTy),
  2352. "ptrtoint not supported for non-integral pointers");
  2353. Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
  2354. Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
  2355. &I);
  2356. if (SrcTy->isVectorTy()) {
  2357. VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
  2358. VectorType *VDest = dyn_cast<VectorType>(DestTy);
  2359. Assert(VSrc->getNumElements() == VDest->getNumElements(),
  2360. "PtrToInt Vector width mismatch", &I);
  2361. }
  2362. visitInstruction(I);
  2363. }
  2364. void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
  2365. // Get the source and destination types
  2366. Type *SrcTy = I.getOperand(0)->getType();
  2367. Type *DestTy = I.getType();
  2368. Assert(SrcTy->isIntOrIntVectorTy(),
  2369. "IntToPtr source must be an integral", &I);
  2370. Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
  2371. if (auto *PTy = dyn_cast<PointerType>(DestTy->getScalarType()))
  2372. Assert(!DL.isNonIntegralPointerType(PTy),
  2373. "inttoptr not supported for non-integral pointers");
  2374. Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
  2375. &I);
  2376. if (SrcTy->isVectorTy()) {
  2377. VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
  2378. VectorType *VDest = dyn_cast<VectorType>(DestTy);
  2379. Assert(VSrc->getNumElements() == VDest->getNumElements(),
  2380. "IntToPtr Vector width mismatch", &I);
  2381. }
  2382. visitInstruction(I);
  2383. }
  2384. void Verifier::visitBitCastInst(BitCastInst &I) {
  2385. Assert(
  2386. CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
  2387. "Invalid bitcast", &I);
  2388. visitInstruction(I);
  2389. }
  2390. void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
  2391. Type *SrcTy = I.getOperand(0)->getType();
  2392. Type *DestTy = I.getType();
  2393. Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
  2394. &I);
  2395. Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
  2396. &I);
  2397. Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
  2398. "AddrSpaceCast must be between different address spaces", &I);
  2399. if (SrcTy->isVectorTy())
  2400. Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
  2401. "AddrSpaceCast vector pointer number of elements mismatch", &I);
  2402. visitInstruction(I);
  2403. }
  2404. /// visitPHINode - Ensure that a PHI node is well formed.
  2405. ///
  2406. void Verifier::visitPHINode(PHINode &PN) {
  2407. // Ensure that the PHI nodes are all grouped together at the top of the block.
  2408. // This can be tested by checking whether the instruction before this is
  2409. // either nonexistent (because this is begin()) or is a PHI node. If not,
  2410. // then there is some other instruction before a PHI.
  2411. Assert(&PN == &PN.getParent()->front() ||
  2412. isa<PHINode>(--BasicBlock::iterator(&PN)),
  2413. "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
  2414. // Check that a PHI doesn't yield a Token.
  2415. Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
  2416. // Check that all of the values of the PHI node have the same type as the
  2417. // result, and that the incoming blocks are really basic blocks.
  2418. for (Value *IncValue : PN.incoming_values()) {
  2419. Assert(PN.getType() == IncValue->getType(),
  2420. "PHI node operands are not the same type as the result!", &PN);
  2421. }
  2422. // All other PHI node constraints are checked in the visitBasicBlock method.
  2423. visitInstruction(PN);
  2424. }
  2425. void Verifier::visitCallBase(CallBase &Call) {
  2426. Assert(Call.getCalledValue()->getType()->isPointerTy(),
  2427. "Called function must be a pointer!", Call);
  2428. PointerType *FPTy = cast<PointerType>(Call.getCalledValue()->getType());
  2429. Assert(FPTy->getElementType()->isFunctionTy(),
  2430. "Called function is not pointer to function type!", Call);
  2431. Assert(FPTy->getElementType() == Call.getFunctionType(),
  2432. "Called function is not the same type as the call!", Call);
  2433. FunctionType *FTy = Call.getFunctionType();
  2434. // Verify that the correct number of arguments are being passed
  2435. if (FTy->isVarArg())
  2436. Assert(Call.arg_size() >= FTy->getNumParams(),
  2437. "Called function requires more parameters than were provided!",
  2438. Call);
  2439. else
  2440. Assert(Call.arg_size() == FTy->getNumParams(),
  2441. "Incorrect number of arguments passed to called function!", Call);
  2442. // Verify that all arguments to the call match the function type.
  2443. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  2444. Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
  2445. "Call parameter type does not match function signature!",
  2446. Call.getArgOperand(i), FTy->getParamType(i), Call);
  2447. AttributeList Attrs = Call.getAttributes();
  2448. Assert(verifyAttributeCount(Attrs, Call.arg_size()),
  2449. "Attribute after last parameter!", Call);
  2450. bool IsIntrinsic = Call.getCalledFunction() &&
  2451. Call.getCalledFunction()->getName().startswith("llvm.");
  2452. Function *Callee
  2453. = dyn_cast<Function>(Call.getCalledValue()->stripPointerCasts());
  2454. if (Attrs.hasAttribute(AttributeList::FunctionIndex, Attribute::Speculatable)) {
  2455. // Don't allow speculatable on call sites, unless the underlying function
  2456. // declaration is also speculatable.
  2457. Assert(Callee && Callee->isSpeculatable(),
  2458. "speculatable attribute may not apply to call sites", Call);
  2459. }
  2460. // Verify call attributes.
  2461. verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic);
  2462. // Conservatively check the inalloca argument.
  2463. // We have a bug if we can find that there is an underlying alloca without
  2464. // inalloca.
  2465. if (Call.hasInAllocaArgument()) {
  2466. Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
  2467. if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
  2468. Assert(AI->isUsedWithInAlloca(),
  2469. "inalloca argument for call has mismatched alloca", AI, Call);
  2470. }
  2471. // For each argument of the callsite, if it has the swifterror argument,
  2472. // make sure the underlying alloca/parameter it comes from has a swifterror as
  2473. // well.
  2474. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
  2475. if (Call.paramHasAttr(i, Attribute::SwiftError)) {
  2476. Value *SwiftErrorArg = Call.getArgOperand(i);
  2477. if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
  2478. Assert(AI->isSwiftError(),
  2479. "swifterror argument for call has mismatched alloca", AI, Call);
  2480. continue;
  2481. }
  2482. auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
  2483. Assert(ArgI,
  2484. "swifterror argument should come from an alloca or parameter",
  2485. SwiftErrorArg, Call);
  2486. Assert(ArgI->hasSwiftErrorAttr(),
  2487. "swifterror argument for call has mismatched parameter", ArgI,
  2488. Call);
  2489. }
  2490. if (Attrs.hasParamAttribute(i, Attribute::ImmArg)) {
  2491. // Don't allow immarg on call sites, unless the underlying declaration
  2492. // also has the matching immarg.
  2493. Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
  2494. "immarg may not apply only to call sites",
  2495. Call.getArgOperand(i), Call);
  2496. }
  2497. if (Call.paramHasAttr(i, Attribute::ImmArg)) {
  2498. Value *ArgVal = Call.getArgOperand(i);
  2499. Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
  2500. "immarg operand has non-immediate parameter", ArgVal, Call);
  2501. }
  2502. }
  2503. if (FTy->isVarArg()) {
  2504. // FIXME? is 'nest' even legal here?
  2505. bool SawNest = false;
  2506. bool SawReturned = false;
  2507. for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
  2508. if (Attrs.hasParamAttribute(Idx, Attribute::Nest))
  2509. SawNest = true;
  2510. if (Attrs.hasParamAttribute(Idx, Attribute::Returned))
  2511. SawReturned = true;
  2512. }
  2513. // Check attributes on the varargs part.
  2514. for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
  2515. Type *Ty = Call.getArgOperand(Idx)->getType();
  2516. AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx);
  2517. verifyParameterAttrs(ArgAttrs, Ty, &Call);
  2518. if (ArgAttrs.hasAttribute(Attribute::Nest)) {
  2519. Assert(!SawNest, "More than one parameter has attribute nest!", Call);
  2520. SawNest = true;
  2521. }
  2522. if (ArgAttrs.hasAttribute(Attribute::Returned)) {
  2523. Assert(!SawReturned, "More than one parameter has attribute returned!",
  2524. Call);
  2525. Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
  2526. "Incompatible argument and return types for 'returned' "
  2527. "attribute",
  2528. Call);
  2529. SawReturned = true;
  2530. }
  2531. // Statepoint intrinsic is vararg but the wrapped function may be not.
  2532. // Allow sret here and check the wrapped function in verifyStatepoint.
  2533. if (!Call.getCalledFunction() ||
  2534. Call.getCalledFunction()->getIntrinsicID() !=
  2535. Intrinsic::experimental_gc_statepoint)
  2536. Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
  2537. "Attribute 'sret' cannot be used for vararg call arguments!",
  2538. Call);
  2539. if (ArgAttrs.hasAttribute(Attribute::InAlloca))
  2540. Assert(Idx == Call.arg_size() - 1,
  2541. "inalloca isn't on the last argument!", Call);
  2542. }
  2543. }
  2544. // Verify that there's no metadata unless it's a direct call to an intrinsic.
  2545. if (!IsIntrinsic) {
  2546. for (Type *ParamTy : FTy->params()) {
  2547. Assert(!ParamTy->isMetadataTy(),
  2548. "Function has metadata parameter but isn't an intrinsic", Call);
  2549. Assert(!ParamTy->isTokenTy(),
  2550. "Function has token parameter but isn't an intrinsic", Call);
  2551. }
  2552. }
  2553. // Verify that indirect calls don't return tokens.
  2554. if (!Call.getCalledFunction())
  2555. Assert(!FTy->getReturnType()->isTokenTy(),
  2556. "Return type cannot be token for indirect call!");
  2557. if (Function *F = Call.getCalledFunction())
  2558. if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
  2559. visitIntrinsicCall(ID, Call);
  2560. // Verify that a callsite has at most one "deopt", at most one "funclet" and
  2561. // at most one "gc-transition" operand bundle.
  2562. bool FoundDeoptBundle = false, FoundFuncletBundle = false,
  2563. FoundGCTransitionBundle = false;
  2564. for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
  2565. OperandBundleUse BU = Call.getOperandBundleAt(i);
  2566. uint32_t Tag = BU.getTagID();
  2567. if (Tag == LLVMContext::OB_deopt) {
  2568. Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
  2569. FoundDeoptBundle = true;
  2570. } else if (Tag == LLVMContext::OB_gc_transition) {
  2571. Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
  2572. Call);
  2573. FoundGCTransitionBundle = true;
  2574. } else if (Tag == LLVMContext::OB_funclet) {
  2575. Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
  2576. FoundFuncletBundle = true;
  2577. Assert(BU.Inputs.size() == 1,
  2578. "Expected exactly one funclet bundle operand", Call);
  2579. Assert(isa<FuncletPadInst>(BU.Inputs.front()),
  2580. "Funclet bundle operands should correspond to a FuncletPadInst",
  2581. Call);
  2582. }
  2583. }
  2584. // Verify that each inlinable callsite of a debug-info-bearing function in a
  2585. // debug-info-bearing function has a debug location attached to it. Failure to
  2586. // do so causes assertion failures when the inliner sets up inline scope info.
  2587. if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
  2588. Call.getCalledFunction()->getSubprogram())
  2589. AssertDI(Call.getDebugLoc(),
  2590. "inlinable function call in a function with "
  2591. "debug info must have a !dbg location",
  2592. Call);
  2593. visitInstruction(Call);
  2594. }
  2595. /// Two types are "congruent" if they are identical, or if they are both pointer
  2596. /// types with different pointee types and the same address space.
  2597. static bool isTypeCongruent(Type *L, Type *R) {
  2598. if (L == R)
  2599. return true;
  2600. PointerType *PL = dyn_cast<PointerType>(L);
  2601. PointerType *PR = dyn_cast<PointerType>(R);
  2602. if (!PL || !PR)
  2603. return false;
  2604. return PL->getAddressSpace() == PR->getAddressSpace();
  2605. }
  2606. static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs) {
  2607. static const Attribute::AttrKind ABIAttrs[] = {
  2608. Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
  2609. Attribute::InReg, Attribute::Returned, Attribute::SwiftSelf,
  2610. Attribute::SwiftError};
  2611. AttrBuilder Copy;
  2612. for (auto AK : ABIAttrs) {
  2613. if (Attrs.hasParamAttribute(I, AK))
  2614. Copy.addAttribute(AK);
  2615. }
  2616. if (Attrs.hasParamAttribute(I, Attribute::Alignment))
  2617. Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
  2618. return Copy;
  2619. }
  2620. void Verifier::verifyMustTailCall(CallInst &CI) {
  2621. Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
  2622. // - The caller and callee prototypes must match. Pointer types of
  2623. // parameters or return types may differ in pointee type, but not
  2624. // address space.
  2625. Function *F = CI.getParent()->getParent();
  2626. FunctionType *CallerTy = F->getFunctionType();
  2627. FunctionType *CalleeTy = CI.getFunctionType();
  2628. if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
  2629. Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
  2630. "cannot guarantee tail call due to mismatched parameter counts",
  2631. &CI);
  2632. for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
  2633. Assert(
  2634. isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
  2635. "cannot guarantee tail call due to mismatched parameter types", &CI);
  2636. }
  2637. }
  2638. Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
  2639. "cannot guarantee tail call due to mismatched varargs", &CI);
  2640. Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
  2641. "cannot guarantee tail call due to mismatched return types", &CI);
  2642. // - The calling conventions of the caller and callee must match.
  2643. Assert(F->getCallingConv() == CI.getCallingConv(),
  2644. "cannot guarantee tail call due to mismatched calling conv", &CI);
  2645. // - All ABI-impacting function attributes, such as sret, byval, inreg,
  2646. // returned, and inalloca, must match.
  2647. AttributeList CallerAttrs = F->getAttributes();
  2648. AttributeList CalleeAttrs = CI.getAttributes();
  2649. for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
  2650. AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
  2651. AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
  2652. Assert(CallerABIAttrs == CalleeABIAttrs,
  2653. "cannot guarantee tail call due to mismatched ABI impacting "
  2654. "function attributes",
  2655. &CI, CI.getOperand(I));
  2656. }
  2657. // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
  2658. // or a pointer bitcast followed by a ret instruction.
  2659. // - The ret instruction must return the (possibly bitcasted) value
  2660. // produced by the call or void.
  2661. Value *RetVal = &CI;
  2662. Instruction *Next = CI.getNextNode();
  2663. // Handle the optional bitcast.
  2664. if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
  2665. Assert(BI->getOperand(0) == RetVal,
  2666. "bitcast following musttail call must use the call", BI);
  2667. RetVal = BI;
  2668. Next = BI->getNextNode();
  2669. }
  2670. // Check the return.
  2671. ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
  2672. Assert(Ret, "musttail call must precede a ret with an optional bitcast",
  2673. &CI);
  2674. Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
  2675. "musttail call result must be returned", Ret);
  2676. }
  2677. void Verifier::visitCallInst(CallInst &CI) {
  2678. visitCallBase(CI);
  2679. if (CI.isMustTailCall())
  2680. verifyMustTailCall(CI);
  2681. }
  2682. void Verifier::visitInvokeInst(InvokeInst &II) {
  2683. visitCallBase(II);
  2684. // Verify that the first non-PHI instruction of the unwind destination is an
  2685. // exception handling instruction.
  2686. Assert(
  2687. II.getUnwindDest()->isEHPad(),
  2688. "The unwind destination does not have an exception handling instruction!",
  2689. &II);
  2690. visitTerminator(II);
  2691. }
  2692. /// visitUnaryOperator - Check the argument to the unary operator.
  2693. ///
  2694. void Verifier::visitUnaryOperator(UnaryOperator &U) {
  2695. Assert(U.getType() == U.getOperand(0)->getType(),
  2696. "Unary operators must have same type for"
  2697. "operands and result!",
  2698. &U);
  2699. switch (U.getOpcode()) {
  2700. // Check that floating-point arithmetic operators are only used with
  2701. // floating-point operands.
  2702. case Instruction::FNeg:
  2703. Assert(U.getType()->isFPOrFPVectorTy(),
  2704. "FNeg operator only works with float types!", &U);
  2705. break;
  2706. default:
  2707. llvm_unreachable("Unknown UnaryOperator opcode!");
  2708. }
  2709. visitInstruction(U);
  2710. }
  2711. /// visitBinaryOperator - Check that both arguments to the binary operator are
  2712. /// of the same type!
  2713. ///
  2714. void Verifier::visitBinaryOperator(BinaryOperator &B) {
  2715. Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
  2716. "Both operands to a binary operator are not of the same type!", &B);
  2717. switch (B.getOpcode()) {
  2718. // Check that integer arithmetic operators are only used with
  2719. // integral operands.
  2720. case Instruction::Add:
  2721. case Instruction::Sub:
  2722. case Instruction::Mul:
  2723. case Instruction::SDiv:
  2724. case Instruction::UDiv:
  2725. case Instruction::SRem:
  2726. case Instruction::URem:
  2727. Assert(B.getType()->isIntOrIntVectorTy(),
  2728. "Integer arithmetic operators only work with integral types!", &B);
  2729. Assert(B.getType() == B.getOperand(0)->getType(),
  2730. "Integer arithmetic operators must have same type "
  2731. "for operands and result!",
  2732. &B);
  2733. break;
  2734. // Check that floating-point arithmetic operators are only used with
  2735. // floating-point operands.
  2736. case Instruction::FAdd:
  2737. case Instruction::FSub:
  2738. case Instruction::FMul:
  2739. case Instruction::FDiv:
  2740. case Instruction::FRem:
  2741. Assert(B.getType()->isFPOrFPVectorTy(),
  2742. "Floating-point arithmetic operators only work with "
  2743. "floating-point types!",
  2744. &B);
  2745. Assert(B.getType() == B.getOperand(0)->getType(),
  2746. "Floating-point arithmetic operators must have same type "
  2747. "for operands and result!",
  2748. &B);
  2749. break;
  2750. // Check that logical operators are only used with integral operands.
  2751. case Instruction::And:
  2752. case Instruction::Or:
  2753. case Instruction::Xor:
  2754. Assert(B.getType()->isIntOrIntVectorTy(),
  2755. "Logical operators only work with integral types!", &B);
  2756. Assert(B.getType() == B.getOperand(0)->getType(),
  2757. "Logical operators must have same type for operands and result!",
  2758. &B);
  2759. break;
  2760. case Instruction::Shl:
  2761. case Instruction::LShr:
  2762. case Instruction::AShr:
  2763. Assert(B.getType()->isIntOrIntVectorTy(),
  2764. "Shifts only work with integral types!", &B);
  2765. Assert(B.getType() == B.getOperand(0)->getType(),
  2766. "Shift return type must be same as operands!", &B);
  2767. break;
  2768. default:
  2769. llvm_unreachable("Unknown BinaryOperator opcode!");
  2770. }
  2771. visitInstruction(B);
  2772. }
  2773. void Verifier::visitICmpInst(ICmpInst &IC) {
  2774. // Check that the operands are the same type
  2775. Type *Op0Ty = IC.getOperand(0)->getType();
  2776. Type *Op1Ty = IC.getOperand(1)->getType();
  2777. Assert(Op0Ty == Op1Ty,
  2778. "Both operands to ICmp instruction are not of the same type!", &IC);
  2779. // Check that the operands are the right type
  2780. Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
  2781. "Invalid operand types for ICmp instruction", &IC);
  2782. // Check that the predicate is valid.
  2783. Assert(IC.isIntPredicate(),
  2784. "Invalid predicate in ICmp instruction!", &IC);
  2785. visitInstruction(IC);
  2786. }
  2787. void Verifier::visitFCmpInst(FCmpInst &FC) {
  2788. // Check that the operands are the same type
  2789. Type *Op0Ty = FC.getOperand(0)->getType();
  2790. Type *Op1Ty = FC.getOperand(1)->getType();
  2791. Assert(Op0Ty == Op1Ty,
  2792. "Both operands to FCmp instruction are not of the same type!", &FC);
  2793. // Check that the operands are the right type
  2794. Assert(Op0Ty->isFPOrFPVectorTy(),
  2795. "Invalid operand types for FCmp instruction", &FC);
  2796. // Check that the predicate is valid.
  2797. Assert(FC.isFPPredicate(),
  2798. "Invalid predicate in FCmp instruction!", &FC);
  2799. visitInstruction(FC);
  2800. }
  2801. void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
  2802. Assert(
  2803. ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
  2804. "Invalid extractelement operands!", &EI);
  2805. visitInstruction(EI);
  2806. }
  2807. void Verifier::visitInsertElementInst(InsertElementInst &IE) {
  2808. Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
  2809. IE.getOperand(2)),
  2810. "Invalid insertelement operands!", &IE);
  2811. visitInstruction(IE);
  2812. }
  2813. void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
  2814. Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
  2815. SV.getOperand(2)),
  2816. "Invalid shufflevector operands!", &SV);
  2817. visitInstruction(SV);
  2818. }
  2819. void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
  2820. Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
  2821. Assert(isa<PointerType>(TargetTy),
  2822. "GEP base pointer is not a vector or a vector of pointers", &GEP);
  2823. Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
  2824. SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
  2825. Assert(all_of(
  2826. Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }),
  2827. "GEP indexes must be integers", &GEP);
  2828. Type *ElTy =
  2829. GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
  2830. Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
  2831. Assert(GEP.getType()->isPtrOrPtrVectorTy() &&
  2832. GEP.getResultElementType() == ElTy,
  2833. "GEP is not of right type for indices!", &GEP, ElTy);
  2834. if (GEP.getType()->isVectorTy()) {
  2835. // Additional checks for vector GEPs.
  2836. unsigned GEPWidth = GEP.getType()->getVectorNumElements();
  2837. if (GEP.getPointerOperandType()->isVectorTy())
  2838. Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
  2839. "Vector GEP result width doesn't match operand's", &GEP);
  2840. for (Value *Idx : Idxs) {
  2841. Type *IndexTy = Idx->getType();
  2842. if (IndexTy->isVectorTy()) {
  2843. unsigned IndexWidth = IndexTy->getVectorNumElements();
  2844. Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
  2845. }
  2846. Assert(IndexTy->isIntOrIntVectorTy(),
  2847. "All GEP indices should be of integer type");
  2848. }
  2849. }
  2850. if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
  2851. Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),
  2852. "GEP address space doesn't match type", &GEP);
  2853. }
  2854. visitInstruction(GEP);
  2855. }
  2856. static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
  2857. return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
  2858. }
  2859. void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
  2860. assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
  2861. "precondition violation");
  2862. unsigned NumOperands = Range->getNumOperands();
  2863. Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
  2864. unsigned NumRanges = NumOperands / 2;
  2865. Assert(NumRanges >= 1, "It should have at least one range!", Range);
  2866. ConstantRange LastRange(1, true); // Dummy initial value
  2867. for (unsigned i = 0; i < NumRanges; ++i) {
  2868. ConstantInt *Low =
  2869. mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
  2870. Assert(Low, "The lower limit must be an integer!", Low);
  2871. ConstantInt *High =
  2872. mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
  2873. Assert(High, "The upper limit must be an integer!", High);
  2874. Assert(High->getType() == Low->getType() && High->getType() == Ty,
  2875. "Range types must match instruction type!", &I);
  2876. APInt HighV = High->getValue();
  2877. APInt LowV = Low->getValue();
  2878. ConstantRange CurRange(LowV, HighV);
  2879. Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
  2880. "Range must not be empty!", Range);
  2881. if (i != 0) {
  2882. Assert(CurRange.intersectWith(LastRange).isEmptySet(),
  2883. "Intervals are overlapping", Range);
  2884. Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
  2885. Range);
  2886. Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
  2887. Range);
  2888. }
  2889. LastRange = ConstantRange(LowV, HighV);
  2890. }
  2891. if (NumRanges > 2) {
  2892. APInt FirstLow =
  2893. mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
  2894. APInt FirstHigh =
  2895. mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
  2896. ConstantRange FirstRange(FirstLow, FirstHigh);
  2897. Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
  2898. "Intervals are overlapping", Range);
  2899. Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
  2900. Range);
  2901. }
  2902. }
  2903. void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
  2904. unsigned Size = DL.getTypeSizeInBits(Ty);
  2905. Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
  2906. Assert(!(Size & (Size - 1)),
  2907. "atomic memory access' operand must have a power-of-two size", Ty, I);
  2908. }
  2909. void Verifier::visitLoadInst(LoadInst &LI) {
  2910. PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
  2911. Assert(PTy, "Load operand must be a pointer.", &LI);
  2912. Type *ElTy = LI.getType();
  2913. Assert(LI.getAlignment() <= Value::MaximumAlignment,
  2914. "huge alignment values are unsupported", &LI);
  2915. Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
  2916. if (LI.isAtomic()) {
  2917. Assert(LI.getOrdering() != AtomicOrdering::Release &&
  2918. LI.getOrdering() != AtomicOrdering::AcquireRelease,
  2919. "Load cannot have Release ordering", &LI);
  2920. Assert(LI.getAlignment() != 0,
  2921. "Atomic load must specify explicit alignment", &LI);
  2922. Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
  2923. "atomic load operand must have integer, pointer, or floating point "
  2924. "type!",
  2925. ElTy, &LI);
  2926. checkAtomicMemAccessSize(ElTy, &LI);
  2927. } else {
  2928. Assert(LI.getSyncScopeID() == SyncScope::System,
  2929. "Non-atomic load cannot have SynchronizationScope specified", &LI);
  2930. }
  2931. visitInstruction(LI);
  2932. }
  2933. void Verifier::visitStoreInst(StoreInst &SI) {
  2934. PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
  2935. Assert(PTy, "Store operand must be a pointer.", &SI);
  2936. Type *ElTy = PTy->getElementType();
  2937. Assert(ElTy == SI.getOperand(0)->getType(),
  2938. "Stored value type does not match pointer operand type!", &SI, ElTy);
  2939. Assert(SI.getAlignment() <= Value::MaximumAlignment,
  2940. "huge alignment values are unsupported", &SI);
  2941. Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
  2942. if (SI.isAtomic()) {
  2943. Assert(SI.getOrdering() != AtomicOrdering::Acquire &&
  2944. SI.getOrdering() != AtomicOrdering::AcquireRelease,
  2945. "Store cannot have Acquire ordering", &SI);
  2946. Assert(SI.getAlignment() != 0,
  2947. "Atomic store must specify explicit alignment", &SI);
  2948. Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
  2949. "atomic store operand must have integer, pointer, or floating point "
  2950. "type!",
  2951. ElTy, &SI);
  2952. checkAtomicMemAccessSize(ElTy, &SI);
  2953. } else {
  2954. Assert(SI.getSyncScopeID() == SyncScope::System,
  2955. "Non-atomic store cannot have SynchronizationScope specified", &SI);
  2956. }
  2957. visitInstruction(SI);
  2958. }
  2959. /// Check that SwiftErrorVal is used as a swifterror argument in CS.
  2960. void Verifier::verifySwiftErrorCall(CallBase &Call,
  2961. const Value *SwiftErrorVal) {
  2962. unsigned Idx = 0;
  2963. for (auto I = Call.arg_begin(), E = Call.arg_end(); I != E; ++I, ++Idx) {
  2964. if (*I == SwiftErrorVal) {
  2965. Assert(Call.paramHasAttr(Idx, Attribute::SwiftError),
  2966. "swifterror value when used in a callsite should be marked "
  2967. "with swifterror attribute",
  2968. SwiftErrorVal, Call);
  2969. }
  2970. }
  2971. }
  2972. void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
  2973. // Check that swifterror value is only used by loads, stores, or as
  2974. // a swifterror argument.
  2975. for (const User *U : SwiftErrorVal->users()) {
  2976. Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
  2977. isa<InvokeInst>(U),
  2978. "swifterror value can only be loaded and stored from, or "
  2979. "as a swifterror argument!",
  2980. SwiftErrorVal, U);
  2981. // If it is used by a store, check it is the second operand.
  2982. if (auto StoreI = dyn_cast<StoreInst>(U))
  2983. Assert(StoreI->getOperand(1) == SwiftErrorVal,
  2984. "swifterror value should be the second operand when used "
  2985. "by stores", SwiftErrorVal, U);
  2986. if (auto *Call = dyn_cast<CallBase>(U))
  2987. verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
  2988. }
  2989. }
  2990. void Verifier::visitAllocaInst(AllocaInst &AI) {
  2991. SmallPtrSet<Type*, 4> Visited;
  2992. PointerType *PTy = AI.getType();
  2993. // TODO: Relax this restriction?
  2994. Assert(PTy->getAddressSpace() == DL.getAllocaAddrSpace(),
  2995. "Allocation instruction pointer not in the stack address space!",
  2996. &AI);
  2997. Assert(AI.getAllocatedType()->isSized(&Visited),
  2998. "Cannot allocate unsized type", &AI);
  2999. Assert(AI.getArraySize()->getType()->isIntegerTy(),
  3000. "Alloca array size must have integer type", &AI);
  3001. Assert(AI.getAlignment() <= Value::MaximumAlignment,
  3002. "huge alignment values are unsupported", &AI);
  3003. if (AI.isSwiftError()) {
  3004. verifySwiftErrorValue(&AI);
  3005. }
  3006. visitInstruction(AI);
  3007. }
  3008. void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
  3009. // FIXME: more conditions???
  3010. Assert(CXI.getSuccessOrdering() != AtomicOrdering::NotAtomic,
  3011. "cmpxchg instructions must be atomic.", &CXI);
  3012. Assert(CXI.getFailureOrdering() != AtomicOrdering::NotAtomic,
  3013. "cmpxchg instructions must be atomic.", &CXI);
  3014. Assert(CXI.getSuccessOrdering() != AtomicOrdering::Unordered,
  3015. "cmpxchg instructions cannot be unordered.", &CXI);
  3016. Assert(CXI.getFailureOrdering() != AtomicOrdering::Unordered,
  3017. "cmpxchg instructions cannot be unordered.", &CXI);
  3018. Assert(!isStrongerThan(CXI.getFailureOrdering(), CXI.getSuccessOrdering()),
  3019. "cmpxchg instructions failure argument shall be no stronger than the "
  3020. "success argument",
  3021. &CXI);
  3022. Assert(CXI.getFailureOrdering() != AtomicOrdering::Release &&
  3023. CXI.getFailureOrdering() != AtomicOrdering::AcquireRelease,
  3024. "cmpxchg failure ordering cannot include release semantics", &CXI);
  3025. PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
  3026. Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
  3027. Type *ElTy = PTy->getElementType();
  3028. Assert(ElTy->isIntOrPtrTy(),
  3029. "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
  3030. checkAtomicMemAccessSize(ElTy, &CXI);
  3031. Assert(ElTy == CXI.getOperand(1)->getType(),
  3032. "Expected value type does not match pointer operand type!", &CXI,
  3033. ElTy);
  3034. Assert(ElTy == CXI.getOperand(2)->getType(),
  3035. "Stored value type does not match pointer operand type!", &CXI, ElTy);
  3036. visitInstruction(CXI);
  3037. }
  3038. void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
  3039. Assert(RMWI.getOrdering() != AtomicOrdering::NotAtomic,
  3040. "atomicrmw instructions must be atomic.", &RMWI);
  3041. Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,
  3042. "atomicrmw instructions cannot be unordered.", &RMWI);
  3043. auto Op = RMWI.getOperation();
  3044. PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
  3045. Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
  3046. Type *ElTy = PTy->getElementType();
  3047. if (Op == AtomicRMWInst::Xchg) {
  3048. Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " +
  3049. AtomicRMWInst::getOperationName(Op) +
  3050. " operand must have integer or floating point type!",
  3051. &RMWI, ElTy);
  3052. } else if (AtomicRMWInst::isFPOperation(Op)) {
  3053. Assert(ElTy->isFloatingPointTy(), "atomicrmw " +
  3054. AtomicRMWInst::getOperationName(Op) +
  3055. " operand must have floating point type!",
  3056. &RMWI, ElTy);
  3057. } else {
  3058. Assert(ElTy->isIntegerTy(), "atomicrmw " +
  3059. AtomicRMWInst::getOperationName(Op) +
  3060. " operand must have integer type!",
  3061. &RMWI, ElTy);
  3062. }
  3063. checkAtomicMemAccessSize(ElTy, &RMWI);
  3064. Assert(ElTy == RMWI.getOperand(1)->getType(),
  3065. "Argument value type does not match pointer operand type!", &RMWI,
  3066. ElTy);
  3067. Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
  3068. "Invalid binary operation!", &RMWI);
  3069. visitInstruction(RMWI);
  3070. }
  3071. void Verifier::visitFenceInst(FenceInst &FI) {
  3072. const AtomicOrdering Ordering = FI.getOrdering();
  3073. Assert(Ordering == AtomicOrdering::Acquire ||
  3074. Ordering == AtomicOrdering::Release ||
  3075. Ordering == AtomicOrdering::AcquireRelease ||
  3076. Ordering == AtomicOrdering::SequentiallyConsistent,
  3077. "fence instructions may only have acquire, release, acq_rel, or "
  3078. "seq_cst ordering.",
  3079. &FI);
  3080. visitInstruction(FI);
  3081. }
  3082. void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
  3083. Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
  3084. EVI.getIndices()) == EVI.getType(),
  3085. "Invalid ExtractValueInst operands!", &EVI);
  3086. visitInstruction(EVI);
  3087. }
  3088. void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
  3089. Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
  3090. IVI.getIndices()) ==
  3091. IVI.getOperand(1)->getType(),
  3092. "Invalid InsertValueInst operands!", &IVI);
  3093. visitInstruction(IVI);
  3094. }
  3095. static Value *getParentPad(Value *EHPad) {
  3096. if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
  3097. return FPI->getParentPad();
  3098. return cast<CatchSwitchInst>(EHPad)->getParentPad();
  3099. }
  3100. void Verifier::visitEHPadPredecessors(Instruction &I) {
  3101. assert(I.isEHPad());
  3102. BasicBlock *BB = I.getParent();
  3103. Function *F = BB->getParent();
  3104. Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
  3105. if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
  3106. // The landingpad instruction defines its parent as a landing pad block. The
  3107. // landing pad block may be branched to only by the unwind edge of an
  3108. // invoke.
  3109. for (BasicBlock *PredBB : predecessors(BB)) {
  3110. const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
  3111. Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
  3112. "Block containing LandingPadInst must be jumped to "
  3113. "only by the unwind edge of an invoke.",
  3114. LPI);
  3115. }
  3116. return;
  3117. }
  3118. if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
  3119. if (!pred_empty(BB))
  3120. Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
  3121. "Block containg CatchPadInst must be jumped to "
  3122. "only by its catchswitch.",
  3123. CPI);
  3124. Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
  3125. "Catchswitch cannot unwind to one of its catchpads",
  3126. CPI->getCatchSwitch(), CPI);
  3127. return;
  3128. }
  3129. // Verify that each pred has a legal terminator with a legal to/from EH
  3130. // pad relationship.
  3131. Instruction *ToPad = &I;
  3132. Value *ToPadParent = getParentPad(ToPad);
  3133. for (BasicBlock *PredBB : predecessors(BB)) {
  3134. Instruction *TI = PredBB->getTerminator();
  3135. Value *FromPad;
  3136. if (auto *II = dyn_cast<InvokeInst>(TI)) {
  3137. Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
  3138. "EH pad must be jumped to via an unwind edge", ToPad, II);
  3139. if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
  3140. FromPad = Bundle->Inputs[0];
  3141. else
  3142. FromPad = ConstantTokenNone::get(II->getContext());
  3143. } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
  3144. FromPad = CRI->getOperand(0);
  3145. Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
  3146. } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
  3147. FromPad = CSI;
  3148. } else {
  3149. Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
  3150. }
  3151. // The edge may exit from zero or more nested pads.
  3152. SmallSet<Value *, 8> Seen;
  3153. for (;; FromPad = getParentPad(FromPad)) {
  3154. Assert(FromPad != ToPad,
  3155. "EH pad cannot handle exceptions raised within it", FromPad, TI);
  3156. if (FromPad == ToPadParent) {
  3157. // This is a legal unwind edge.
  3158. break;
  3159. }
  3160. Assert(!isa<ConstantTokenNone>(FromPad),
  3161. "A single unwind edge may only enter one EH pad", TI);
  3162. Assert(Seen.insert(FromPad).second,
  3163. "EH pad jumps through a cycle of pads", FromPad);
  3164. }
  3165. }
  3166. }
  3167. void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
  3168. // The landingpad instruction is ill-formed if it doesn't have any clauses and
  3169. // isn't a cleanup.
  3170. Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
  3171. "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
  3172. visitEHPadPredecessors(LPI);
  3173. if (!LandingPadResultTy)
  3174. LandingPadResultTy = LPI.getType();
  3175. else
  3176. Assert(LandingPadResultTy == LPI.getType(),
  3177. "The landingpad instruction should have a consistent result type "
  3178. "inside a function.",
  3179. &LPI);
  3180. Function *F = LPI.getParent()->getParent();
  3181. Assert(F->hasPersonalityFn(),
  3182. "LandingPadInst needs to be in a function with a personality.", &LPI);
  3183. // The landingpad instruction must be the first non-PHI instruction in the
  3184. // block.
  3185. Assert(LPI.getParent()->getLandingPadInst() == &LPI,
  3186. "LandingPadInst not the first non-PHI instruction in the block.",
  3187. &LPI);
  3188. for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
  3189. Constant *Clause = LPI.getClause(i);
  3190. if (LPI.isCatch(i)) {
  3191. Assert(isa<PointerType>(Clause->getType()),
  3192. "Catch operand does not have pointer type!", &LPI);
  3193. } else {
  3194. Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
  3195. Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
  3196. "Filter operand is not an array of constants!", &LPI);
  3197. }
  3198. }
  3199. visitInstruction(LPI);
  3200. }
  3201. void Verifier::visitResumeInst(ResumeInst &RI) {
  3202. Assert(RI.getFunction()->hasPersonalityFn(),
  3203. "ResumeInst needs to be in a function with a personality.", &RI);
  3204. if (!LandingPadResultTy)
  3205. LandingPadResultTy = RI.getValue()->getType();
  3206. else
  3207. Assert(LandingPadResultTy == RI.getValue()->getType(),
  3208. "The resume instruction should have a consistent result type "
  3209. "inside a function.",
  3210. &RI);
  3211. visitTerminator(RI);
  3212. }
  3213. void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
  3214. BasicBlock *BB = CPI.getParent();
  3215. Function *F = BB->getParent();
  3216. Assert(F->hasPersonalityFn(),
  3217. "CatchPadInst needs to be in a function with a personality.", &CPI);
  3218. Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
  3219. "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
  3220. CPI.getParentPad());
  3221. // The catchpad instruction must be the first non-PHI instruction in the
  3222. // block.
  3223. Assert(BB->getFirstNonPHI() == &CPI,
  3224. "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
  3225. visitEHPadPredecessors(CPI);
  3226. visitFuncletPadInst(CPI);
  3227. }
  3228. void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
  3229. Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
  3230. "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
  3231. CatchReturn.getOperand(0));
  3232. visitTerminator(CatchReturn);
  3233. }
  3234. void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
  3235. BasicBlock *BB = CPI.getParent();
  3236. Function *F = BB->getParent();
  3237. Assert(F->hasPersonalityFn(),
  3238. "CleanupPadInst needs to be in a function with a personality.", &CPI);
  3239. // The cleanuppad instruction must be the first non-PHI instruction in the
  3240. // block.
  3241. Assert(BB->getFirstNonPHI() == &CPI,
  3242. "CleanupPadInst not the first non-PHI instruction in the block.",
  3243. &CPI);
  3244. auto *ParentPad = CPI.getParentPad();
  3245. Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
  3246. "CleanupPadInst has an invalid parent.", &CPI);
  3247. visitEHPadPredecessors(CPI);
  3248. visitFuncletPadInst(CPI);
  3249. }
  3250. void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
  3251. User *FirstUser = nullptr;
  3252. Value *FirstUnwindPad = nullptr;
  3253. SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
  3254. SmallSet<FuncletPadInst *, 8> Seen;
  3255. while (!Worklist.empty()) {
  3256. FuncletPadInst *CurrentPad = Worklist.pop_back_val();
  3257. Assert(Seen.insert(CurrentPad).second,
  3258. "FuncletPadInst must not be nested within itself", CurrentPad);
  3259. Value *UnresolvedAncestorPad = nullptr;
  3260. for (User *U : CurrentPad->users()) {
  3261. BasicBlock *UnwindDest;
  3262. if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
  3263. UnwindDest = CRI->getUnwindDest();
  3264. } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
  3265. // We allow catchswitch unwind to caller to nest
  3266. // within an outer pad that unwinds somewhere else,
  3267. // because catchswitch doesn't have a nounwind variant.
  3268. // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
  3269. if (CSI->unwindsToCaller())
  3270. continue;
  3271. UnwindDest = CSI->getUnwindDest();
  3272. } else if (auto *II = dyn_cast<InvokeInst>(U)) {
  3273. UnwindDest = II->getUnwindDest();
  3274. } else if (isa<CallInst>(U)) {
  3275. // Calls which don't unwind may be found inside funclet
  3276. // pads that unwind somewhere else. We don't *require*
  3277. // such calls to be annotated nounwind.
  3278. continue;
  3279. } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
  3280. // The unwind dest for a cleanup can only be found by
  3281. // recursive search. Add it to the worklist, and we'll
  3282. // search for its first use that determines where it unwinds.
  3283. Worklist.push_back(CPI);
  3284. continue;
  3285. } else {
  3286. Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
  3287. continue;
  3288. }
  3289. Value *UnwindPad;
  3290. bool ExitsFPI;
  3291. if (UnwindDest) {
  3292. UnwindPad = UnwindDest->getFirstNonPHI();
  3293. if (!cast<Instruction>(UnwindPad)->isEHPad())
  3294. continue;
  3295. Value *UnwindParent = getParentPad(UnwindPad);
  3296. // Ignore unwind edges that don't exit CurrentPad.
  3297. if (UnwindParent == CurrentPad)
  3298. continue;
  3299. // Determine whether the original funclet pad is exited,
  3300. // and if we are scanning nested pads determine how many
  3301. // of them are exited so we can stop searching their
  3302. // children.
  3303. Value *ExitedPad = CurrentPad;
  3304. ExitsFPI = false;
  3305. do {
  3306. if (ExitedPad == &FPI) {
  3307. ExitsFPI = true;
  3308. // Now we can resolve any ancestors of CurrentPad up to
  3309. // FPI, but not including FPI since we need to make sure
  3310. // to check all direct users of FPI for consistency.
  3311. UnresolvedAncestorPad = &FPI;
  3312. break;
  3313. }
  3314. Value *ExitedParent = getParentPad(ExitedPad);
  3315. if (ExitedParent == UnwindParent) {
  3316. // ExitedPad is the ancestor-most pad which this unwind
  3317. // edge exits, so we can resolve up to it, meaning that
  3318. // ExitedParent is the first ancestor still unresolved.
  3319. UnresolvedAncestorPad = ExitedParent;
  3320. break;
  3321. }
  3322. ExitedPad = ExitedParent;
  3323. } while (!isa<ConstantTokenNone>(ExitedPad));
  3324. } else {
  3325. // Unwinding to caller exits all pads.
  3326. UnwindPad = ConstantTokenNone::get(FPI.getContext());
  3327. ExitsFPI = true;
  3328. UnresolvedAncestorPad = &FPI;
  3329. }
  3330. if (ExitsFPI) {
  3331. // This unwind edge exits FPI. Make sure it agrees with other
  3332. // such edges.
  3333. if (FirstUser) {
  3334. Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
  3335. "pad must have the same unwind "
  3336. "dest",
  3337. &FPI, U, FirstUser);
  3338. } else {
  3339. FirstUser = U;
  3340. FirstUnwindPad = UnwindPad;
  3341. // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
  3342. if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
  3343. getParentPad(UnwindPad) == getParentPad(&FPI))
  3344. SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
  3345. }
  3346. }
  3347. // Make sure we visit all uses of FPI, but for nested pads stop as
  3348. // soon as we know where they unwind to.
  3349. if (CurrentPad != &FPI)
  3350. break;
  3351. }
  3352. if (UnresolvedAncestorPad) {
  3353. if (CurrentPad == UnresolvedAncestorPad) {
  3354. // When CurrentPad is FPI itself, we don't mark it as resolved even if
  3355. // we've found an unwind edge that exits it, because we need to verify
  3356. // all direct uses of FPI.
  3357. assert(CurrentPad == &FPI);
  3358. continue;
  3359. }
  3360. // Pop off the worklist any nested pads that we've found an unwind
  3361. // destination for. The pads on the worklist are the uncles,
  3362. // great-uncles, etc. of CurrentPad. We've found an unwind destination
  3363. // for all ancestors of CurrentPad up to but not including
  3364. // UnresolvedAncestorPad.
  3365. Value *ResolvedPad = CurrentPad;
  3366. while (!Worklist.empty()) {
  3367. Value *UnclePad = Worklist.back();
  3368. Value *AncestorPad = getParentPad(UnclePad);
  3369. // Walk ResolvedPad up the ancestor list until we either find the
  3370. // uncle's parent or the last resolved ancestor.
  3371. while (ResolvedPad != AncestorPad) {
  3372. Value *ResolvedParent = getParentPad(ResolvedPad);
  3373. if (ResolvedParent == UnresolvedAncestorPad) {
  3374. break;
  3375. }
  3376. ResolvedPad = ResolvedParent;
  3377. }
  3378. // If the resolved ancestor search didn't find the uncle's parent,
  3379. // then the uncle is not yet resolved.
  3380. if (ResolvedPad != AncestorPad)
  3381. break;
  3382. // This uncle is resolved, so pop it from the worklist.
  3383. Worklist.pop_back();
  3384. }
  3385. }
  3386. }
  3387. if (FirstUnwindPad) {
  3388. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
  3389. BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
  3390. Value *SwitchUnwindPad;
  3391. if (SwitchUnwindDest)
  3392. SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
  3393. else
  3394. SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
  3395. Assert(SwitchUnwindPad == FirstUnwindPad,
  3396. "Unwind edges out of a catch must have the same unwind dest as "
  3397. "the parent catchswitch",
  3398. &FPI, FirstUser, CatchSwitch);
  3399. }
  3400. }
  3401. visitInstruction(FPI);
  3402. }
  3403. void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
  3404. BasicBlock *BB = CatchSwitch.getParent();
  3405. Function *F = BB->getParent();
  3406. Assert(F->hasPersonalityFn(),
  3407. "CatchSwitchInst needs to be in a function with a personality.",
  3408. &CatchSwitch);
  3409. // The catchswitch instruction must be the first non-PHI instruction in the
  3410. // block.
  3411. Assert(BB->getFirstNonPHI() == &CatchSwitch,
  3412. "CatchSwitchInst not the first non-PHI instruction in the block.",
  3413. &CatchSwitch);
  3414. auto *ParentPad = CatchSwitch.getParentPad();
  3415. Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
  3416. "CatchSwitchInst has an invalid parent.", ParentPad);
  3417. if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
  3418. Instruction *I = UnwindDest->getFirstNonPHI();
  3419. Assert(I->isEHPad() && !isa<LandingPadInst>(I),
  3420. "CatchSwitchInst must unwind to an EH block which is not a "
  3421. "landingpad.",
  3422. &CatchSwitch);
  3423. // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
  3424. if (getParentPad(I) == ParentPad)
  3425. SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
  3426. }
  3427. Assert(CatchSwitch.getNumHandlers() != 0,
  3428. "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
  3429. for (BasicBlock *Handler : CatchSwitch.handlers()) {
  3430. Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
  3431. "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
  3432. }
  3433. visitEHPadPredecessors(CatchSwitch);
  3434. visitTerminator(CatchSwitch);
  3435. }
  3436. void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
  3437. Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
  3438. "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
  3439. CRI.getOperand(0));
  3440. if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
  3441. Instruction *I = UnwindDest->getFirstNonPHI();
  3442. Assert(I->isEHPad() && !isa<LandingPadInst>(I),
  3443. "CleanupReturnInst must unwind to an EH block which is not a "
  3444. "landingpad.",
  3445. &CRI);
  3446. }
  3447. visitTerminator(CRI);
  3448. }
  3449. void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
  3450. Instruction *Op = cast<Instruction>(I.getOperand(i));
  3451. // If the we have an invalid invoke, don't try to compute the dominance.
  3452. // We already reject it in the invoke specific checks and the dominance
  3453. // computation doesn't handle multiple edges.
  3454. if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
  3455. if (II->getNormalDest() == II->getUnwindDest())
  3456. return;
  3457. }
  3458. // Quick check whether the def has already been encountered in the same block.
  3459. // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
  3460. // uses are defined to happen on the incoming edge, not at the instruction.
  3461. //
  3462. // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
  3463. // wrapping an SSA value, assert that we've already encountered it. See
  3464. // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
  3465. if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
  3466. return;
  3467. const Use &U = I.getOperandUse(i);
  3468. Assert(DT.dominates(Op, U),
  3469. "Instruction does not dominate all uses!", Op, &I);
  3470. }
  3471. void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
  3472. Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
  3473. "apply only to pointer types", &I);
  3474. Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
  3475. "dereferenceable, dereferenceable_or_null apply only to load"
  3476. " and inttoptr instructions, use attributes for calls or invokes", &I);
  3477. Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
  3478. "take one operand!", &I);
  3479. ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
  3480. Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
  3481. "dereferenceable_or_null metadata value must be an i64!", &I);
  3482. }
  3483. void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
  3484. Assert(MD->getNumOperands() >= 2,
  3485. "!prof annotations should have no less than 2 operands", MD);
  3486. // Check first operand.
  3487. Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
  3488. Assert(isa<MDString>(MD->getOperand(0)),
  3489. "expected string with name of the !prof annotation", MD);
  3490. MDString *MDS = cast<MDString>(MD->getOperand(0));
  3491. StringRef ProfName = MDS->getString();
  3492. // Check consistency of !prof branch_weights metadata.
  3493. if (ProfName.equals("branch_weights")) {
  3494. unsigned ExpectedNumOperands = 0;
  3495. if (BranchInst *BI = dyn_cast<BranchInst>(&I))
  3496. ExpectedNumOperands = BI->getNumSuccessors();
  3497. else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
  3498. ExpectedNumOperands = SI->getNumSuccessors();
  3499. else if (isa<CallInst>(&I) || isa<InvokeInst>(&I))
  3500. ExpectedNumOperands = 1;
  3501. else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
  3502. ExpectedNumOperands = IBI->getNumDestinations();
  3503. else if (isa<SelectInst>(&I))
  3504. ExpectedNumOperands = 2;
  3505. else
  3506. CheckFailed("!prof branch_weights are not allowed for this instruction",
  3507. MD);
  3508. Assert(MD->getNumOperands() == 1 + ExpectedNumOperands,
  3509. "Wrong number of operands", MD);
  3510. for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
  3511. auto &MDO = MD->getOperand(i);
  3512. Assert(MDO, "second operand should not be null", MD);
  3513. Assert(mdconst::dyn_extract<ConstantInt>(MDO),
  3514. "!prof brunch_weights operand is not a const int");
  3515. }
  3516. }
  3517. }
  3518. /// verifyInstruction - Verify that an instruction is well formed.
  3519. ///
  3520. void Verifier::visitInstruction(Instruction &I) {
  3521. BasicBlock *BB = I.getParent();
  3522. Assert(BB, "Instruction not embedded in basic block!", &I);
  3523. if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
  3524. for (User *U : I.users()) {
  3525. Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
  3526. "Only PHI nodes may reference their own value!", &I);
  3527. }
  3528. }
  3529. // Check that void typed values don't have names
  3530. Assert(!I.getType()->isVoidTy() || !I.hasName(),
  3531. "Instruction has a name, but provides a void value!", &I);
  3532. // Check that the return value of the instruction is either void or a legal
  3533. // value type.
  3534. Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
  3535. "Instruction returns a non-scalar type!", &I);
  3536. // Check that the instruction doesn't produce metadata. Calls are already
  3537. // checked against the callee type.
  3538. Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
  3539. "Invalid use of metadata!", &I);
  3540. // Check that all uses of the instruction, if they are instructions
  3541. // themselves, actually have parent basic blocks. If the use is not an
  3542. // instruction, it is an error!
  3543. for (Use &U : I.uses()) {
  3544. if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
  3545. Assert(Used->getParent() != nullptr,
  3546. "Instruction referencing"
  3547. " instruction not embedded in a basic block!",
  3548. &I, Used);
  3549. else {
  3550. CheckFailed("Use of instruction is not an instruction!", U);
  3551. return;
  3552. }
  3553. }
  3554. // Get a pointer to the call base of the instruction if it is some form of
  3555. // call.
  3556. const CallBase *CBI = dyn_cast<CallBase>(&I);
  3557. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
  3558. Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
  3559. // Check to make sure that only first-class-values are operands to
  3560. // instructions.
  3561. if (!I.getOperand(i)->getType()->isFirstClassType()) {
  3562. Assert(false, "Instruction operands must be first-class values!", &I);
  3563. }
  3564. if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
  3565. // Check to make sure that the "address of" an intrinsic function is never
  3566. // taken.
  3567. Assert(!F->isIntrinsic() ||
  3568. (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)),
  3569. "Cannot take the address of an intrinsic!", &I);
  3570. Assert(
  3571. !F->isIntrinsic() || isa<CallInst>(I) ||
  3572. F->getIntrinsicID() == Intrinsic::donothing ||
  3573. F->getIntrinsicID() == Intrinsic::coro_resume ||
  3574. F->getIntrinsicID() == Intrinsic::coro_destroy ||
  3575. F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
  3576. F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
  3577. F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
  3578. F->getIntrinsicID() == Intrinsic::wasm_rethrow_in_catch,
  3579. "Cannot invoke an intrinsic other than donothing, patchpoint, "
  3580. "statepoint, coro_resume or coro_destroy",
  3581. &I);
  3582. Assert(F->getParent() == &M, "Referencing function in another module!",
  3583. &I, &M, F, F->getParent());
  3584. } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
  3585. Assert(OpBB->getParent() == BB->getParent(),
  3586. "Referring to a basic block in another function!", &I);
  3587. } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
  3588. Assert(OpArg->getParent() == BB->getParent(),
  3589. "Referring to an argument in another function!", &I);
  3590. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
  3591. Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
  3592. &M, GV, GV->getParent());
  3593. } else if (isa<Instruction>(I.getOperand(i))) {
  3594. verifyDominatesUse(I, i);
  3595. } else if (isa<InlineAsm>(I.getOperand(i))) {
  3596. Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
  3597. "Cannot take the address of an inline asm!", &I);
  3598. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
  3599. if (CE->getType()->isPtrOrPtrVectorTy() ||
  3600. !DL.getNonIntegralAddressSpaces().empty()) {
  3601. // If we have a ConstantExpr pointer, we need to see if it came from an
  3602. // illegal bitcast. If the datalayout string specifies non-integral
  3603. // address spaces then we also need to check for illegal ptrtoint and
  3604. // inttoptr expressions.
  3605. visitConstantExprsRecursively(CE);
  3606. }
  3607. }
  3608. }
  3609. if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
  3610. Assert(I.getType()->isFPOrFPVectorTy(),
  3611. "fpmath requires a floating point result!", &I);
  3612. Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
  3613. if (ConstantFP *CFP0 =
  3614. mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
  3615. const APFloat &Accuracy = CFP0->getValueAPF();
  3616. Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
  3617. "fpmath accuracy must have float type", &I);
  3618. Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
  3619. "fpmath accuracy not a positive number!", &I);
  3620. } else {
  3621. Assert(false, "invalid fpmath accuracy!", &I);
  3622. }
  3623. }
  3624. if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
  3625. Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
  3626. "Ranges are only for loads, calls and invokes!", &I);
  3627. visitRangeMetadata(I, Range, I.getType());
  3628. }
  3629. if (I.getMetadata(LLVMContext::MD_nonnull)) {
  3630. Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
  3631. &I);
  3632. Assert(isa<LoadInst>(I),
  3633. "nonnull applies only to load instructions, use attributes"
  3634. " for calls or invokes",
  3635. &I);
  3636. }
  3637. if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
  3638. visitDereferenceableMetadata(I, MD);
  3639. if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
  3640. visitDereferenceableMetadata(I, MD);
  3641. if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
  3642. TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
  3643. if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
  3644. Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
  3645. &I);
  3646. Assert(isa<LoadInst>(I), "align applies only to load instructions, "
  3647. "use attributes for calls or invokes", &I);
  3648. Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
  3649. ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
  3650. Assert(CI && CI->getType()->isIntegerTy(64),
  3651. "align metadata value must be an i64!", &I);
  3652. uint64_t Align = CI->getZExtValue();
  3653. Assert(isPowerOf2_64(Align),
  3654. "align metadata value must be a power of 2!", &I);
  3655. Assert(Align <= Value::MaximumAlignment,
  3656. "alignment is larger that implementation defined limit", &I);
  3657. }
  3658. if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
  3659. visitProfMetadata(I, MD);
  3660. if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
  3661. AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
  3662. visitMDNode(*N);
  3663. }
  3664. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I))
  3665. verifyFragmentExpression(*DII);
  3666. InstsInThisBlock.insert(&I);
  3667. }
  3668. /// Allow intrinsics to be verified in different ways.
  3669. void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
  3670. Function *IF = Call.getCalledFunction();
  3671. Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
  3672. IF);
  3673. // Verify that the intrinsic prototype lines up with what the .td files
  3674. // describe.
  3675. FunctionType *IFTy = IF->getFunctionType();
  3676. bool IsVarArg = IFTy->isVarArg();
  3677. SmallVector<Intrinsic::IITDescriptor, 8> Table;
  3678. getIntrinsicInfoTableEntries(ID, Table);
  3679. ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
  3680. // Walk the descriptors to extract overloaded types.
  3681. SmallVector<Type *, 4> ArgTys;
  3682. Intrinsic::MatchIntrinsicTypesResult Res =
  3683. Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
  3684. Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
  3685. "Intrinsic has incorrect return type!", IF);
  3686. Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
  3687. "Intrinsic has incorrect argument type!", IF);
  3688. // Verify if the intrinsic call matches the vararg property.
  3689. if (IsVarArg)
  3690. Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
  3691. "Intrinsic was not defined with variable arguments!", IF);
  3692. else
  3693. Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
  3694. "Callsite was not defined with variable arguments!", IF);
  3695. // All descriptors should be absorbed by now.
  3696. Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
  3697. // Now that we have the intrinsic ID and the actual argument types (and we
  3698. // know they are legal for the intrinsic!) get the intrinsic name through the
  3699. // usual means. This allows us to verify the mangling of argument types into
  3700. // the name.
  3701. const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
  3702. Assert(ExpectedName == IF->getName(),
  3703. "Intrinsic name not mangled correctly for type arguments! "
  3704. "Should be: " +
  3705. ExpectedName,
  3706. IF);
  3707. // If the intrinsic takes MDNode arguments, verify that they are either global
  3708. // or are local to *this* function.
  3709. for (Value *V : Call.args())
  3710. if (auto *MD = dyn_cast<MetadataAsValue>(V))
  3711. visitMetadataAsValue(*MD, Call.getCaller());
  3712. switch (ID) {
  3713. default:
  3714. break;
  3715. case Intrinsic::coro_id: {
  3716. auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
  3717. if (isa<ConstantPointerNull>(InfoArg))
  3718. break;
  3719. auto *GV = dyn_cast<GlobalVariable>(InfoArg);
  3720. Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
  3721. "info argument of llvm.coro.begin must refer to an initialized "
  3722. "constant");
  3723. Constant *Init = GV->getInitializer();
  3724. Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
  3725. "info argument of llvm.coro.begin must refer to either a struct or "
  3726. "an array");
  3727. break;
  3728. }
  3729. case Intrinsic::experimental_constrained_fadd:
  3730. case Intrinsic::experimental_constrained_fsub:
  3731. case Intrinsic::experimental_constrained_fmul:
  3732. case Intrinsic::experimental_constrained_fdiv:
  3733. case Intrinsic::experimental_constrained_frem:
  3734. case Intrinsic::experimental_constrained_fma:
  3735. case Intrinsic::experimental_constrained_fptosi:
  3736. case Intrinsic::experimental_constrained_fptoui:
  3737. case Intrinsic::experimental_constrained_fptrunc:
  3738. case Intrinsic::experimental_constrained_fpext:
  3739. case Intrinsic::experimental_constrained_sqrt:
  3740. case Intrinsic::experimental_constrained_pow:
  3741. case Intrinsic::experimental_constrained_powi:
  3742. case Intrinsic::experimental_constrained_sin:
  3743. case Intrinsic::experimental_constrained_cos:
  3744. case Intrinsic::experimental_constrained_exp:
  3745. case Intrinsic::experimental_constrained_exp2:
  3746. case Intrinsic::experimental_constrained_log:
  3747. case Intrinsic::experimental_constrained_log10:
  3748. case Intrinsic::experimental_constrained_log2:
  3749. case Intrinsic::experimental_constrained_rint:
  3750. case Intrinsic::experimental_constrained_nearbyint:
  3751. case Intrinsic::experimental_constrained_maxnum:
  3752. case Intrinsic::experimental_constrained_minnum:
  3753. case Intrinsic::experimental_constrained_ceil:
  3754. case Intrinsic::experimental_constrained_floor:
  3755. case Intrinsic::experimental_constrained_round:
  3756. case Intrinsic::experimental_constrained_trunc:
  3757. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
  3758. break;
  3759. case Intrinsic::dbg_declare: // llvm.dbg.declare
  3760. Assert(isa<MetadataAsValue>(Call.getArgOperand(0)),
  3761. "invalid llvm.dbg.declare intrinsic call 1", Call);
  3762. visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
  3763. break;
  3764. case Intrinsic::dbg_addr: // llvm.dbg.addr
  3765. visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
  3766. break;
  3767. case Intrinsic::dbg_value: // llvm.dbg.value
  3768. visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
  3769. break;
  3770. case Intrinsic::dbg_label: // llvm.dbg.label
  3771. visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
  3772. break;
  3773. case Intrinsic::memcpy:
  3774. case Intrinsic::memmove:
  3775. case Intrinsic::memset: {
  3776. const auto *MI = cast<MemIntrinsic>(&Call);
  3777. auto IsValidAlignment = [&](unsigned Alignment) -> bool {
  3778. return Alignment == 0 || isPowerOf2_32(Alignment);
  3779. };
  3780. Assert(IsValidAlignment(MI->getDestAlignment()),
  3781. "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
  3782. Call);
  3783. if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
  3784. Assert(IsValidAlignment(MTI->getSourceAlignment()),
  3785. "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
  3786. Call);
  3787. }
  3788. break;
  3789. }
  3790. case Intrinsic::memcpy_element_unordered_atomic:
  3791. case Intrinsic::memmove_element_unordered_atomic:
  3792. case Intrinsic::memset_element_unordered_atomic: {
  3793. const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
  3794. ConstantInt *ElementSizeCI =
  3795. cast<ConstantInt>(AMI->getRawElementSizeInBytes());
  3796. const APInt &ElementSizeVal = ElementSizeCI->getValue();
  3797. Assert(ElementSizeVal.isPowerOf2(),
  3798. "element size of the element-wise atomic memory intrinsic "
  3799. "must be a power of 2",
  3800. Call);
  3801. if (auto *LengthCI = dyn_cast<ConstantInt>(AMI->getLength())) {
  3802. uint64_t Length = LengthCI->getZExtValue();
  3803. uint64_t ElementSize = AMI->getElementSizeInBytes();
  3804. Assert((Length % ElementSize) == 0,
  3805. "constant length must be a multiple of the element size in the "
  3806. "element-wise atomic memory intrinsic",
  3807. Call);
  3808. }
  3809. auto IsValidAlignment = [&](uint64_t Alignment) {
  3810. return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
  3811. };
  3812. uint64_t DstAlignment = AMI->getDestAlignment();
  3813. Assert(IsValidAlignment(DstAlignment),
  3814. "incorrect alignment of the destination argument", Call);
  3815. if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
  3816. uint64_t SrcAlignment = AMT->getSourceAlignment();
  3817. Assert(IsValidAlignment(SrcAlignment),
  3818. "incorrect alignment of the source argument", Call);
  3819. }
  3820. break;
  3821. }
  3822. case Intrinsic::gcroot:
  3823. case Intrinsic::gcwrite:
  3824. case Intrinsic::gcread:
  3825. if (ID == Intrinsic::gcroot) {
  3826. AllocaInst *AI =
  3827. dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
  3828. Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
  3829. Assert(isa<Constant>(Call.getArgOperand(1)),
  3830. "llvm.gcroot parameter #2 must be a constant.", Call);
  3831. if (!AI->getAllocatedType()->isPointerTy()) {
  3832. Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
  3833. "llvm.gcroot parameter #1 must either be a pointer alloca, "
  3834. "or argument #2 must be a non-null constant.",
  3835. Call);
  3836. }
  3837. }
  3838. Assert(Call.getParent()->getParent()->hasGC(),
  3839. "Enclosing function does not use GC.", Call);
  3840. break;
  3841. case Intrinsic::init_trampoline:
  3842. Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
  3843. "llvm.init_trampoline parameter #2 must resolve to a function.",
  3844. Call);
  3845. break;
  3846. case Intrinsic::prefetch:
  3847. Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 &&
  3848. cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
  3849. "invalid arguments to llvm.prefetch", Call);
  3850. break;
  3851. case Intrinsic::stackprotector:
  3852. Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
  3853. "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
  3854. break;
  3855. case Intrinsic::localescape: {
  3856. BasicBlock *BB = Call.getParent();
  3857. Assert(BB == &BB->getParent()->front(),
  3858. "llvm.localescape used outside of entry block", Call);
  3859. Assert(!SawFrameEscape,
  3860. "multiple calls to llvm.localescape in one function", Call);
  3861. for (Value *Arg : Call.args()) {
  3862. if (isa<ConstantPointerNull>(Arg))
  3863. continue; // Null values are allowed as placeholders.
  3864. auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
  3865. Assert(AI && AI->isStaticAlloca(),
  3866. "llvm.localescape only accepts static allocas", Call);
  3867. }
  3868. FrameEscapeInfo[BB->getParent()].first = Call.getNumArgOperands();
  3869. SawFrameEscape = true;
  3870. break;
  3871. }
  3872. case Intrinsic::localrecover: {
  3873. Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
  3874. Function *Fn = dyn_cast<Function>(FnArg);
  3875. Assert(Fn && !Fn->isDeclaration(),
  3876. "llvm.localrecover first "
  3877. "argument must be function defined in this module",
  3878. Call);
  3879. auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
  3880. auto &Entry = FrameEscapeInfo[Fn];
  3881. Entry.second = unsigned(
  3882. std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
  3883. break;
  3884. }
  3885. case Intrinsic::experimental_gc_statepoint:
  3886. if (auto *CI = dyn_cast<CallInst>(&Call))
  3887. Assert(!CI->isInlineAsm(),
  3888. "gc.statepoint support for inline assembly unimplemented", CI);
  3889. Assert(Call.getParent()->getParent()->hasGC(),
  3890. "Enclosing function does not use GC.", Call);
  3891. verifyStatepoint(Call);
  3892. break;
  3893. case Intrinsic::experimental_gc_result: {
  3894. Assert(Call.getParent()->getParent()->hasGC(),
  3895. "Enclosing function does not use GC.", Call);
  3896. // Are we tied to a statepoint properly?
  3897. const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0));
  3898. const Function *StatepointFn =
  3899. StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
  3900. Assert(StatepointFn && StatepointFn->isDeclaration() &&
  3901. StatepointFn->getIntrinsicID() ==
  3902. Intrinsic::experimental_gc_statepoint,
  3903. "gc.result operand #1 must be from a statepoint", Call,
  3904. Call.getArgOperand(0));
  3905. // Assert that result type matches wrapped callee.
  3906. const Value *Target = StatepointCall->getArgOperand(2);
  3907. auto *PT = cast<PointerType>(Target->getType());
  3908. auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
  3909. Assert(Call.getType() == TargetFuncType->getReturnType(),
  3910. "gc.result result type does not match wrapped callee", Call);
  3911. break;
  3912. }
  3913. case Intrinsic::experimental_gc_relocate: {
  3914. Assert(Call.getNumArgOperands() == 3, "wrong number of arguments", Call);
  3915. Assert(isa<PointerType>(Call.getType()->getScalarType()),
  3916. "gc.relocate must return a pointer or a vector of pointers", Call);
  3917. // Check that this relocate is correctly tied to the statepoint
  3918. // This is case for relocate on the unwinding path of an invoke statepoint
  3919. if (LandingPadInst *LandingPad =
  3920. dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
  3921. const BasicBlock *InvokeBB =
  3922. LandingPad->getParent()->getUniquePredecessor();
  3923. // Landingpad relocates should have only one predecessor with invoke
  3924. // statepoint terminator
  3925. Assert(InvokeBB, "safepoints should have unique landingpads",
  3926. LandingPad->getParent());
  3927. Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
  3928. InvokeBB);
  3929. Assert(isStatepoint(InvokeBB->getTerminator()),
  3930. "gc relocate should be linked to a statepoint", InvokeBB);
  3931. } else {
  3932. // In all other cases relocate should be tied to the statepoint directly.
  3933. // This covers relocates on a normal return path of invoke statepoint and
  3934. // relocates of a call statepoint.
  3935. auto Token = Call.getArgOperand(0);
  3936. Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
  3937. "gc relocate is incorrectly tied to the statepoint", Call, Token);
  3938. }
  3939. // Verify rest of the relocate arguments.
  3940. const CallBase &StatepointCall =
  3941. *cast<CallBase>(cast<GCRelocateInst>(Call).getStatepoint());
  3942. // Both the base and derived must be piped through the safepoint.
  3943. Value *Base = Call.getArgOperand(1);
  3944. Assert(isa<ConstantInt>(Base),
  3945. "gc.relocate operand #2 must be integer offset", Call);
  3946. Value *Derived = Call.getArgOperand(2);
  3947. Assert(isa<ConstantInt>(Derived),
  3948. "gc.relocate operand #3 must be integer offset", Call);
  3949. const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
  3950. const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
  3951. // Check the bounds
  3952. Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCall.arg_size(),
  3953. "gc.relocate: statepoint base index out of bounds", Call);
  3954. Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCall.arg_size(),
  3955. "gc.relocate: statepoint derived index out of bounds", Call);
  3956. // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
  3957. // section of the statepoint's argument.
  3958. Assert(StatepointCall.arg_size() > 0,
  3959. "gc.statepoint: insufficient arguments");
  3960. Assert(isa<ConstantInt>(StatepointCall.getArgOperand(3)),
  3961. "gc.statement: number of call arguments must be constant integer");
  3962. const unsigned NumCallArgs =
  3963. cast<ConstantInt>(StatepointCall.getArgOperand(3))->getZExtValue();
  3964. Assert(StatepointCall.arg_size() > NumCallArgs + 5,
  3965. "gc.statepoint: mismatch in number of call arguments");
  3966. Assert(isa<ConstantInt>(StatepointCall.getArgOperand(NumCallArgs + 5)),
  3967. "gc.statepoint: number of transition arguments must be "
  3968. "a constant integer");
  3969. const int NumTransitionArgs =
  3970. cast<ConstantInt>(StatepointCall.getArgOperand(NumCallArgs + 5))
  3971. ->getZExtValue();
  3972. const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
  3973. Assert(isa<ConstantInt>(StatepointCall.getArgOperand(DeoptArgsStart)),
  3974. "gc.statepoint: number of deoptimization arguments must be "
  3975. "a constant integer");
  3976. const int NumDeoptArgs =
  3977. cast<ConstantInt>(StatepointCall.getArgOperand(DeoptArgsStart))
  3978. ->getZExtValue();
  3979. const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
  3980. const int GCParamArgsEnd = StatepointCall.arg_size();
  3981. Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
  3982. "gc.relocate: statepoint base index doesn't fall within the "
  3983. "'gc parameters' section of the statepoint call",
  3984. Call);
  3985. Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
  3986. "gc.relocate: statepoint derived index doesn't fall within the "
  3987. "'gc parameters' section of the statepoint call",
  3988. Call);
  3989. // Relocated value must be either a pointer type or vector-of-pointer type,
  3990. // but gc_relocate does not need to return the same pointer type as the
  3991. // relocated pointer. It can be casted to the correct type later if it's
  3992. // desired. However, they must have the same address space and 'vectorness'
  3993. GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
  3994. Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(),
  3995. "gc.relocate: relocated value must be a gc pointer", Call);
  3996. auto ResultType = Call.getType();
  3997. auto DerivedType = Relocate.getDerivedPtr()->getType();
  3998. Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
  3999. "gc.relocate: vector relocates to vector and pointer to pointer",
  4000. Call);
  4001. Assert(
  4002. ResultType->getPointerAddressSpace() ==
  4003. DerivedType->getPointerAddressSpace(),
  4004. "gc.relocate: relocating a pointer shouldn't change its address space",
  4005. Call);
  4006. break;
  4007. }
  4008. case Intrinsic::eh_exceptioncode:
  4009. case Intrinsic::eh_exceptionpointer: {
  4010. Assert(isa<CatchPadInst>(Call.getArgOperand(0)),
  4011. "eh.exceptionpointer argument must be a catchpad", Call);
  4012. break;
  4013. }
  4014. case Intrinsic::masked_load: {
  4015. Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector",
  4016. Call);
  4017. Value *Ptr = Call.getArgOperand(0);
  4018. ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
  4019. Value *Mask = Call.getArgOperand(2);
  4020. Value *PassThru = Call.getArgOperand(3);
  4021. Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
  4022. Call);
  4023. Assert(Alignment->getValue().isPowerOf2(),
  4024. "masked_load: alignment must be a power of 2", Call);
  4025. // DataTy is the overloaded type
  4026. Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
  4027. Assert(DataTy == Call.getType(),
  4028. "masked_load: return must match pointer type", Call);
  4029. Assert(PassThru->getType() == DataTy,
  4030. "masked_load: pass through and data type must match", Call);
  4031. Assert(Mask->getType()->getVectorNumElements() ==
  4032. DataTy->getVectorNumElements(),
  4033. "masked_load: vector mask must be same length as data", Call);
  4034. break;
  4035. }
  4036. case Intrinsic::masked_store: {
  4037. Value *Val = Call.getArgOperand(0);
  4038. Value *Ptr = Call.getArgOperand(1);
  4039. ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
  4040. Value *Mask = Call.getArgOperand(3);
  4041. Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
  4042. Call);
  4043. Assert(Alignment->getValue().isPowerOf2(),
  4044. "masked_store: alignment must be a power of 2", Call);
  4045. // DataTy is the overloaded type
  4046. Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
  4047. Assert(DataTy == Val->getType(),
  4048. "masked_store: storee must match pointer type", Call);
  4049. Assert(Mask->getType()->getVectorNumElements() ==
  4050. DataTy->getVectorNumElements(),
  4051. "masked_store: vector mask must be same length as data", Call);
  4052. break;
  4053. }
  4054. case Intrinsic::experimental_guard: {
  4055. Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
  4056. Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
  4057. "experimental_guard must have exactly one "
  4058. "\"deopt\" operand bundle");
  4059. break;
  4060. }
  4061. case Intrinsic::experimental_deoptimize: {
  4062. Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
  4063. Call);
  4064. Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
  4065. "experimental_deoptimize must have exactly one "
  4066. "\"deopt\" operand bundle");
  4067. Assert(Call.getType() == Call.getFunction()->getReturnType(),
  4068. "experimental_deoptimize return type must match caller return type");
  4069. if (isa<CallInst>(Call)) {
  4070. auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
  4071. Assert(RI,
  4072. "calls to experimental_deoptimize must be followed by a return");
  4073. if (!Call.getType()->isVoidTy() && RI)
  4074. Assert(RI->getReturnValue() == &Call,
  4075. "calls to experimental_deoptimize must be followed by a return "
  4076. "of the value computed by experimental_deoptimize");
  4077. }
  4078. break;
  4079. }
  4080. case Intrinsic::sadd_sat:
  4081. case Intrinsic::uadd_sat:
  4082. case Intrinsic::ssub_sat:
  4083. case Intrinsic::usub_sat: {
  4084. Value *Op1 = Call.getArgOperand(0);
  4085. Value *Op2 = Call.getArgOperand(1);
  4086. Assert(Op1->getType()->isIntOrIntVectorTy(),
  4087. "first operand of [us][add|sub]_sat must be an int type or vector "
  4088. "of ints");
  4089. Assert(Op2->getType()->isIntOrIntVectorTy(),
  4090. "second operand of [us][add|sub]_sat must be an int type or vector "
  4091. "of ints");
  4092. break;
  4093. }
  4094. case Intrinsic::smul_fix:
  4095. case Intrinsic::smul_fix_sat:
  4096. case Intrinsic::umul_fix:
  4097. case Intrinsic::umul_fix_sat: {
  4098. Value *Op1 = Call.getArgOperand(0);
  4099. Value *Op2 = Call.getArgOperand(1);
  4100. Assert(Op1->getType()->isIntOrIntVectorTy(),
  4101. "first operand of [us]mul_fix[_sat] must be an int type or vector "
  4102. "of ints");
  4103. Assert(Op2->getType()->isIntOrIntVectorTy(),
  4104. "second operand of [us]mul_fix_[sat] must be an int type or vector "
  4105. "of ints");
  4106. auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
  4107. Assert(Op3->getType()->getBitWidth() <= 32,
  4108. "third argument of [us]mul_fix[_sat] must fit within 32 bits");
  4109. if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat) {
  4110. Assert(
  4111. Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
  4112. "the scale of smul_fix[_sat] must be less than the width of the operands");
  4113. } else {
  4114. Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
  4115. "the scale of umul_fix[_sat] must be less than or equal to the width of "
  4116. "the operands");
  4117. }
  4118. break;
  4119. }
  4120. case Intrinsic::lround:
  4121. case Intrinsic::llround:
  4122. case Intrinsic::lrint:
  4123. case Intrinsic::llrint: {
  4124. Type *ValTy = Call.getArgOperand(0)->getType();
  4125. Type *ResultTy = Call.getType();
  4126. Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
  4127. "Intrinsic does not support vectors", &Call);
  4128. break;
  4129. }
  4130. };
  4131. }
  4132. /// Carefully grab the subprogram from a local scope.
  4133. ///
  4134. /// This carefully grabs the subprogram from a local scope, avoiding the
  4135. /// built-in assertions that would typically fire.
  4136. static DISubprogram *getSubprogram(Metadata *LocalScope) {
  4137. if (!LocalScope)
  4138. return nullptr;
  4139. if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
  4140. return SP;
  4141. if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
  4142. return getSubprogram(LB->getRawScope());
  4143. // Just return null; broken scope chains are checked elsewhere.
  4144. assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
  4145. return nullptr;
  4146. }
  4147. void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
  4148. unsigned NumOperands = FPI.getNumArgOperands();
  4149. bool HasExceptionMD = false;
  4150. bool HasRoundingMD = false;
  4151. switch (FPI.getIntrinsicID()) {
  4152. case Intrinsic::experimental_constrained_sqrt:
  4153. case Intrinsic::experimental_constrained_sin:
  4154. case Intrinsic::experimental_constrained_cos:
  4155. case Intrinsic::experimental_constrained_exp:
  4156. case Intrinsic::experimental_constrained_exp2:
  4157. case Intrinsic::experimental_constrained_log:
  4158. case Intrinsic::experimental_constrained_log10:
  4159. case Intrinsic::experimental_constrained_log2:
  4160. case Intrinsic::experimental_constrained_rint:
  4161. case Intrinsic::experimental_constrained_nearbyint:
  4162. case Intrinsic::experimental_constrained_ceil:
  4163. case Intrinsic::experimental_constrained_floor:
  4164. case Intrinsic::experimental_constrained_round:
  4165. case Intrinsic::experimental_constrained_trunc:
  4166. Assert((NumOperands == 3), "invalid arguments for constrained FP intrinsic",
  4167. &FPI);
  4168. HasExceptionMD = true;
  4169. HasRoundingMD = true;
  4170. break;
  4171. case Intrinsic::experimental_constrained_fma:
  4172. Assert((NumOperands == 5), "invalid arguments for constrained FP intrinsic",
  4173. &FPI);
  4174. HasExceptionMD = true;
  4175. HasRoundingMD = true;
  4176. break;
  4177. case Intrinsic::experimental_constrained_fadd:
  4178. case Intrinsic::experimental_constrained_fsub:
  4179. case Intrinsic::experimental_constrained_fmul:
  4180. case Intrinsic::experimental_constrained_fdiv:
  4181. case Intrinsic::experimental_constrained_frem:
  4182. case Intrinsic::experimental_constrained_pow:
  4183. case Intrinsic::experimental_constrained_powi:
  4184. case Intrinsic::experimental_constrained_maxnum:
  4185. case Intrinsic::experimental_constrained_minnum:
  4186. Assert((NumOperands == 4), "invalid arguments for constrained FP intrinsic",
  4187. &FPI);
  4188. HasExceptionMD = true;
  4189. HasRoundingMD = true;
  4190. break;
  4191. case Intrinsic::experimental_constrained_fptosi:
  4192. case Intrinsic::experimental_constrained_fptoui: {
  4193. Assert((NumOperands == 2),
  4194. "invalid arguments for constrained FP intrinsic", &FPI);
  4195. HasExceptionMD = true;
  4196. Value *Operand = FPI.getArgOperand(0);
  4197. uint64_t NumSrcElem = 0;
  4198. Assert(Operand->getType()->isFPOrFPVectorTy(),
  4199. "Intrinsic first argument must be floating point", &FPI);
  4200. if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
  4201. NumSrcElem = OperandT->getNumElements();
  4202. }
  4203. Operand = &FPI;
  4204. Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
  4205. "Intrinsic first argument and result disagree on vector use", &FPI);
  4206. Assert(Operand->getType()->isIntOrIntVectorTy(),
  4207. "Intrinsic result must be an integer", &FPI);
  4208. if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
  4209. Assert(NumSrcElem == OperandT->getNumElements(),
  4210. "Intrinsic first argument and result vector lengths must be equal",
  4211. &FPI);
  4212. }
  4213. }
  4214. break;
  4215. case Intrinsic::experimental_constrained_fptrunc:
  4216. case Intrinsic::experimental_constrained_fpext: {
  4217. if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
  4218. Assert((NumOperands == 3),
  4219. "invalid arguments for constrained FP intrinsic", &FPI);
  4220. HasRoundingMD = true;
  4221. } else {
  4222. Assert((NumOperands == 2),
  4223. "invalid arguments for constrained FP intrinsic", &FPI);
  4224. }
  4225. HasExceptionMD = true;
  4226. Value *Operand = FPI.getArgOperand(0);
  4227. Type *OperandTy = Operand->getType();
  4228. Value *Result = &FPI;
  4229. Type *ResultTy = Result->getType();
  4230. Assert(OperandTy->isFPOrFPVectorTy(),
  4231. "Intrinsic first argument must be FP or FP vector", &FPI);
  4232. Assert(ResultTy->isFPOrFPVectorTy(),
  4233. "Intrinsic result must be FP or FP vector", &FPI);
  4234. Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
  4235. "Intrinsic first argument and result disagree on vector use", &FPI);
  4236. if (OperandTy->isVectorTy()) {
  4237. auto *OperandVecTy = cast<VectorType>(OperandTy);
  4238. auto *ResultVecTy = cast<VectorType>(ResultTy);
  4239. Assert(OperandVecTy->getNumElements() == ResultVecTy->getNumElements(),
  4240. "Intrinsic first argument and result vector lengths must be equal",
  4241. &FPI);
  4242. }
  4243. if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
  4244. Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
  4245. "Intrinsic first argument's type must be larger than result type",
  4246. &FPI);
  4247. } else {
  4248. Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
  4249. "Intrinsic first argument's type must be smaller than result type",
  4250. &FPI);
  4251. }
  4252. }
  4253. break;
  4254. default:
  4255. llvm_unreachable("Invalid constrained FP intrinsic!");
  4256. }
  4257. // If a non-metadata argument is passed in a metadata slot then the
  4258. // error will be caught earlier when the incorrect argument doesn't
  4259. // match the specification in the intrinsic call table. Thus, no
  4260. // argument type check is needed here.
  4261. if (HasExceptionMD) {
  4262. Assert(FPI.getExceptionBehavior().hasValue(),
  4263. "invalid exception behavior argument", &FPI);
  4264. }
  4265. if (HasRoundingMD) {
  4266. Assert(FPI.getRoundingMode().hasValue(),
  4267. "invalid rounding mode argument", &FPI);
  4268. }
  4269. }
  4270. void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
  4271. auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
  4272. AssertDI(isa<ValueAsMetadata>(MD) ||
  4273. (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
  4274. "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
  4275. AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
  4276. "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
  4277. DII.getRawVariable());
  4278. AssertDI(isa<DIExpression>(DII.getRawExpression()),
  4279. "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
  4280. DII.getRawExpression());
  4281. // Ignore broken !dbg attachments; they're checked elsewhere.
  4282. if (MDNode *N = DII.getDebugLoc().getAsMDNode())
  4283. if (!isa<DILocation>(N))
  4284. return;
  4285. BasicBlock *BB = DII.getParent();
  4286. Function *F = BB ? BB->getParent() : nullptr;
  4287. // The scopes for variables and !dbg attachments must agree.
  4288. DILocalVariable *Var = DII.getVariable();
  4289. DILocation *Loc = DII.getDebugLoc();
  4290. AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
  4291. &DII, BB, F);
  4292. DISubprogram *VarSP = getSubprogram(Var->getRawScope());
  4293. DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
  4294. if (!VarSP || !LocSP)
  4295. return; // Broken scope chains are checked elsewhere.
  4296. AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
  4297. " variable and !dbg attachment",
  4298. &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
  4299. Loc->getScope()->getSubprogram());
  4300. // This check is redundant with one in visitLocalVariable().
  4301. AssertDI(isType(Var->getRawType()), "invalid type ref", Var,
  4302. Var->getRawType());
  4303. verifyFnArgs(DII);
  4304. }
  4305. void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
  4306. AssertDI(isa<DILabel>(DLI.getRawLabel()),
  4307. "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
  4308. DLI.getRawLabel());
  4309. // Ignore broken !dbg attachments; they're checked elsewhere.
  4310. if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
  4311. if (!isa<DILocation>(N))
  4312. return;
  4313. BasicBlock *BB = DLI.getParent();
  4314. Function *F = BB ? BB->getParent() : nullptr;
  4315. // The scopes for variables and !dbg attachments must agree.
  4316. DILabel *Label = DLI.getLabel();
  4317. DILocation *Loc = DLI.getDebugLoc();
  4318. Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
  4319. &DLI, BB, F);
  4320. DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
  4321. DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
  4322. if (!LabelSP || !LocSP)
  4323. return;
  4324. AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
  4325. " label and !dbg attachment",
  4326. &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
  4327. Loc->getScope()->getSubprogram());
  4328. }
  4329. void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
  4330. DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
  4331. DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
  4332. // We don't know whether this intrinsic verified correctly.
  4333. if (!V || !E || !E->isValid())
  4334. return;
  4335. // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
  4336. auto Fragment = E->getFragmentInfo();
  4337. if (!Fragment)
  4338. return;
  4339. // The frontend helps out GDB by emitting the members of local anonymous
  4340. // unions as artificial local variables with shared storage. When SROA splits
  4341. // the storage for artificial local variables that are smaller than the entire
  4342. // union, the overhang piece will be outside of the allotted space for the
  4343. // variable and this check fails.
  4344. // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
  4345. if (V->isArtificial())
  4346. return;
  4347. verifyFragmentExpression(*V, *Fragment, &I);
  4348. }
  4349. template <typename ValueOrMetadata>
  4350. void Verifier::verifyFragmentExpression(const DIVariable &V,
  4351. DIExpression::FragmentInfo Fragment,
  4352. ValueOrMetadata *Desc) {
  4353. // If there's no size, the type is broken, but that should be checked
  4354. // elsewhere.
  4355. auto VarSize = V.getSizeInBits();
  4356. if (!VarSize)
  4357. return;
  4358. unsigned FragSize = Fragment.SizeInBits;
  4359. unsigned FragOffset = Fragment.OffsetInBits;
  4360. AssertDI(FragSize + FragOffset <= *VarSize,
  4361. "fragment is larger than or outside of variable", Desc, &V);
  4362. AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
  4363. }
  4364. void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
  4365. // This function does not take the scope of noninlined function arguments into
  4366. // account. Don't run it if current function is nodebug, because it may
  4367. // contain inlined debug intrinsics.
  4368. if (!HasDebugInfo)
  4369. return;
  4370. // For performance reasons only check non-inlined ones.
  4371. if (I.getDebugLoc()->getInlinedAt())
  4372. return;
  4373. DILocalVariable *Var = I.getVariable();
  4374. AssertDI(Var, "dbg intrinsic without variable");
  4375. unsigned ArgNo = Var->getArg();
  4376. if (!ArgNo)
  4377. return;
  4378. // Verify there are no duplicate function argument debug info entries.
  4379. // These will cause hard-to-debug assertions in the DWARF backend.
  4380. if (DebugFnArgs.size() < ArgNo)
  4381. DebugFnArgs.resize(ArgNo, nullptr);
  4382. auto *Prev = DebugFnArgs[ArgNo - 1];
  4383. DebugFnArgs[ArgNo - 1] = Var;
  4384. AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
  4385. Prev, Var);
  4386. }
  4387. void Verifier::verifyCompileUnits() {
  4388. // When more than one Module is imported into the same context, such as during
  4389. // an LTO build before linking the modules, ODR type uniquing may cause types
  4390. // to point to a different CU. This check does not make sense in this case.
  4391. if (M.getContext().isODRUniquingDebugTypes())
  4392. return;
  4393. auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
  4394. SmallPtrSet<const Metadata *, 2> Listed;
  4395. if (CUs)
  4396. Listed.insert(CUs->op_begin(), CUs->op_end());
  4397. for (auto *CU : CUVisited)
  4398. AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
  4399. CUVisited.clear();
  4400. }
  4401. void Verifier::verifyDeoptimizeCallingConvs() {
  4402. if (DeoptimizeDeclarations.empty())
  4403. return;
  4404. const Function *First = DeoptimizeDeclarations[0];
  4405. for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
  4406. Assert(First->getCallingConv() == F->getCallingConv(),
  4407. "All llvm.experimental.deoptimize declarations must have the same "
  4408. "calling convention",
  4409. First, F);
  4410. }
  4411. }
  4412. void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
  4413. bool HasSource = F.getSource().hasValue();
  4414. if (!HasSourceDebugInfo.count(&U))
  4415. HasSourceDebugInfo[&U] = HasSource;
  4416. AssertDI(HasSource == HasSourceDebugInfo[&U],
  4417. "inconsistent use of embedded source");
  4418. }
  4419. //===----------------------------------------------------------------------===//
  4420. // Implement the public interfaces to this file...
  4421. //===----------------------------------------------------------------------===//
  4422. bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
  4423. Function &F = const_cast<Function &>(f);
  4424. // Don't use a raw_null_ostream. Printing IR is expensive.
  4425. Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
  4426. // Note that this function's return value is inverted from what you would
  4427. // expect of a function called "verify".
  4428. return !V.verify(F);
  4429. }
  4430. bool llvm::verifyModule(const Module &M, raw_ostream *OS,
  4431. bool *BrokenDebugInfo) {
  4432. // Don't use a raw_null_ostream. Printing IR is expensive.
  4433. Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
  4434. bool Broken = false;
  4435. for (const Function &F : M)
  4436. Broken |= !V.verify(F);
  4437. Broken |= !V.verify();
  4438. if (BrokenDebugInfo)
  4439. *BrokenDebugInfo = V.hasBrokenDebugInfo();
  4440. // Note that this function's return value is inverted from what you would
  4441. // expect of a function called "verify".
  4442. return Broken;
  4443. }
  4444. namespace {
  4445. struct VerifierLegacyPass : public FunctionPass {
  4446. static char ID;
  4447. std::unique_ptr<Verifier> V;
  4448. bool FatalErrors = true;
  4449. VerifierLegacyPass() : FunctionPass(ID) {
  4450. initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
  4451. }
  4452. explicit VerifierLegacyPass(bool FatalErrors)
  4453. : FunctionPass(ID),
  4454. FatalErrors(FatalErrors) {
  4455. initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
  4456. }
  4457. bool doInitialization(Module &M) override {
  4458. V = std::make_unique<Verifier>(
  4459. &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
  4460. return false;
  4461. }
  4462. bool runOnFunction(Function &F) override {
  4463. if (!V->verify(F) && FatalErrors) {
  4464. errs() << "in function " << F.getName() << '\n';
  4465. report_fatal_error("Broken function found, compilation aborted!");
  4466. }
  4467. return false;
  4468. }
  4469. bool doFinalization(Module &M) override {
  4470. bool HasErrors = false;
  4471. for (Function &F : M)
  4472. if (F.isDeclaration())
  4473. HasErrors |= !V->verify(F);
  4474. HasErrors |= !V->verify();
  4475. if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
  4476. report_fatal_error("Broken module found, compilation aborted!");
  4477. return false;
  4478. }
  4479. void getAnalysisUsage(AnalysisUsage &AU) const override {
  4480. AU.setPreservesAll();
  4481. }
  4482. };
  4483. } // end anonymous namespace
  4484. /// Helper to issue failure from the TBAA verification
  4485. template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
  4486. if (Diagnostic)
  4487. return Diagnostic->CheckFailed(Args...);
  4488. }
  4489. #define AssertTBAA(C, ...) \
  4490. do { \
  4491. if (!(C)) { \
  4492. CheckFailed(__VA_ARGS__); \
  4493. return false; \
  4494. } \
  4495. } while (false)
  4496. /// Verify that \p BaseNode can be used as the "base type" in the struct-path
  4497. /// TBAA scheme. This means \p BaseNode is either a scalar node, or a
  4498. /// struct-type node describing an aggregate data structure (like a struct).
  4499. TBAAVerifier::TBAABaseNodeSummary
  4500. TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
  4501. bool IsNewFormat) {
  4502. if (BaseNode->getNumOperands() < 2) {
  4503. CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
  4504. return {true, ~0u};
  4505. }
  4506. auto Itr = TBAABaseNodes.find(BaseNode);
  4507. if (Itr != TBAABaseNodes.end())
  4508. return Itr->second;
  4509. auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
  4510. auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
  4511. (void)InsertResult;
  4512. assert(InsertResult.second && "We just checked!");
  4513. return Result;
  4514. }
  4515. TBAAVerifier::TBAABaseNodeSummary
  4516. TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
  4517. bool IsNewFormat) {
  4518. const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
  4519. if (BaseNode->getNumOperands() == 2) {
  4520. // Scalar nodes can only be accessed at offset 0.
  4521. return isValidScalarTBAANode(BaseNode)
  4522. ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
  4523. : InvalidNode;
  4524. }
  4525. if (IsNewFormat) {
  4526. if (BaseNode->getNumOperands() % 3 != 0) {
  4527. CheckFailed("Access tag nodes must have the number of operands that is a "
  4528. "multiple of 3!", BaseNode);
  4529. return InvalidNode;
  4530. }
  4531. } else {
  4532. if (BaseNode->getNumOperands() % 2 != 1) {
  4533. CheckFailed("Struct tag nodes must have an odd number of operands!",
  4534. BaseNode);
  4535. return InvalidNode;
  4536. }
  4537. }
  4538. // Check the type size field.
  4539. if (IsNewFormat) {
  4540. auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
  4541. BaseNode->getOperand(1));
  4542. if (!TypeSizeNode) {
  4543. CheckFailed("Type size nodes must be constants!", &I, BaseNode);
  4544. return InvalidNode;
  4545. }
  4546. }
  4547. // Check the type name field. In the new format it can be anything.
  4548. if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
  4549. CheckFailed("Struct tag nodes have a string as their first operand",
  4550. BaseNode);
  4551. return InvalidNode;
  4552. }
  4553. bool Failed = false;
  4554. Optional<APInt> PrevOffset;
  4555. unsigned BitWidth = ~0u;
  4556. // We've already checked that BaseNode is not a degenerate root node with one
  4557. // operand in \c verifyTBAABaseNode, so this loop should run at least once.
  4558. unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
  4559. unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
  4560. for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
  4561. Idx += NumOpsPerField) {
  4562. const MDOperand &FieldTy = BaseNode->getOperand(Idx);
  4563. const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
  4564. if (!isa<MDNode>(FieldTy)) {
  4565. CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
  4566. Failed = true;
  4567. continue;
  4568. }
  4569. auto *OffsetEntryCI =
  4570. mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
  4571. if (!OffsetEntryCI) {
  4572. CheckFailed("Offset entries must be constants!", &I, BaseNode);
  4573. Failed = true;
  4574. continue;
  4575. }
  4576. if (BitWidth == ~0u)
  4577. BitWidth = OffsetEntryCI->getBitWidth();
  4578. if (OffsetEntryCI->getBitWidth() != BitWidth) {
  4579. CheckFailed(
  4580. "Bitwidth between the offsets and struct type entries must match", &I,
  4581. BaseNode);
  4582. Failed = true;
  4583. continue;
  4584. }
  4585. // NB! As far as I can tell, we generate a non-strictly increasing offset
  4586. // sequence only from structs that have zero size bit fields. When
  4587. // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
  4588. // pick the field lexically the latest in struct type metadata node. This
  4589. // mirrors the actual behavior of the alias analysis implementation.
  4590. bool IsAscending =
  4591. !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
  4592. if (!IsAscending) {
  4593. CheckFailed("Offsets must be increasing!", &I, BaseNode);
  4594. Failed = true;
  4595. }
  4596. PrevOffset = OffsetEntryCI->getValue();
  4597. if (IsNewFormat) {
  4598. auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
  4599. BaseNode->getOperand(Idx + 2));
  4600. if (!MemberSizeNode) {
  4601. CheckFailed("Member size entries must be constants!", &I, BaseNode);
  4602. Failed = true;
  4603. continue;
  4604. }
  4605. }
  4606. }
  4607. return Failed ? InvalidNode
  4608. : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
  4609. }
  4610. static bool IsRootTBAANode(const MDNode *MD) {
  4611. return MD->getNumOperands() < 2;
  4612. }
  4613. static bool IsScalarTBAANodeImpl(const MDNode *MD,
  4614. SmallPtrSetImpl<const MDNode *> &Visited) {
  4615. if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
  4616. return false;
  4617. if (!isa<MDString>(MD->getOperand(0)))
  4618. return false;
  4619. if (MD->getNumOperands() == 3) {
  4620. auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
  4621. if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
  4622. return false;
  4623. }
  4624. auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
  4625. return Parent && Visited.insert(Parent).second &&
  4626. (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
  4627. }
  4628. bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
  4629. auto ResultIt = TBAAScalarNodes.find(MD);
  4630. if (ResultIt != TBAAScalarNodes.end())
  4631. return ResultIt->second;
  4632. SmallPtrSet<const MDNode *, 4> Visited;
  4633. bool Result = IsScalarTBAANodeImpl(MD, Visited);
  4634. auto InsertResult = TBAAScalarNodes.insert({MD, Result});
  4635. (void)InsertResult;
  4636. assert(InsertResult.second && "Just checked!");
  4637. return Result;
  4638. }
  4639. /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
  4640. /// Offset in place to be the offset within the field node returned.
  4641. ///
  4642. /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
  4643. MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
  4644. const MDNode *BaseNode,
  4645. APInt &Offset,
  4646. bool IsNewFormat) {
  4647. assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
  4648. // Scalar nodes have only one possible "field" -- their parent in the access
  4649. // hierarchy. Offset must be zero at this point, but our caller is supposed
  4650. // to Assert that.
  4651. if (BaseNode->getNumOperands() == 2)
  4652. return cast<MDNode>(BaseNode->getOperand(1));
  4653. unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
  4654. unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
  4655. for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
  4656. Idx += NumOpsPerField) {
  4657. auto *OffsetEntryCI =
  4658. mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
  4659. if (OffsetEntryCI->getValue().ugt(Offset)) {
  4660. if (Idx == FirstFieldOpNo) {
  4661. CheckFailed("Could not find TBAA parent in struct type node", &I,
  4662. BaseNode, &Offset);
  4663. return nullptr;
  4664. }
  4665. unsigned PrevIdx = Idx - NumOpsPerField;
  4666. auto *PrevOffsetEntryCI =
  4667. mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
  4668. Offset -= PrevOffsetEntryCI->getValue();
  4669. return cast<MDNode>(BaseNode->getOperand(PrevIdx));
  4670. }
  4671. }
  4672. unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
  4673. auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
  4674. BaseNode->getOperand(LastIdx + 1));
  4675. Offset -= LastOffsetEntryCI->getValue();
  4676. return cast<MDNode>(BaseNode->getOperand(LastIdx));
  4677. }
  4678. static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
  4679. if (!Type || Type->getNumOperands() < 3)
  4680. return false;
  4681. // In the new format type nodes shall have a reference to the parent type as
  4682. // its first operand.
  4683. MDNode *Parent = dyn_cast_or_null<MDNode>(Type->getOperand(0));
  4684. if (!Parent)
  4685. return false;
  4686. return true;
  4687. }
  4688. bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
  4689. AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
  4690. isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
  4691. isa<AtomicCmpXchgInst>(I),
  4692. "This instruction shall not have a TBAA access tag!", &I);
  4693. bool IsStructPathTBAA =
  4694. isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
  4695. AssertTBAA(
  4696. IsStructPathTBAA,
  4697. "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
  4698. MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
  4699. MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
  4700. bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
  4701. if (IsNewFormat) {
  4702. AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
  4703. "Access tag metadata must have either 4 or 5 operands", &I, MD);
  4704. } else {
  4705. AssertTBAA(MD->getNumOperands() < 5,
  4706. "Struct tag metadata must have either 3 or 4 operands", &I, MD);
  4707. }
  4708. // Check the access size field.
  4709. if (IsNewFormat) {
  4710. auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
  4711. MD->getOperand(3));
  4712. AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
  4713. }
  4714. // Check the immutability flag.
  4715. unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
  4716. if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
  4717. auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
  4718. MD->getOperand(ImmutabilityFlagOpNo));
  4719. AssertTBAA(IsImmutableCI,
  4720. "Immutability tag on struct tag metadata must be a constant",
  4721. &I, MD);
  4722. AssertTBAA(
  4723. IsImmutableCI->isZero() || IsImmutableCI->isOne(),
  4724. "Immutability part of the struct tag metadata must be either 0 or 1",
  4725. &I, MD);
  4726. }
  4727. AssertTBAA(BaseNode && AccessType,
  4728. "Malformed struct tag metadata: base and access-type "
  4729. "should be non-null and point to Metadata nodes",
  4730. &I, MD, BaseNode, AccessType);
  4731. if (!IsNewFormat) {
  4732. AssertTBAA(isValidScalarTBAANode(AccessType),
  4733. "Access type node must be a valid scalar type", &I, MD,
  4734. AccessType);
  4735. }
  4736. auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
  4737. AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
  4738. APInt Offset = OffsetCI->getValue();
  4739. bool SeenAccessTypeInPath = false;
  4740. SmallPtrSet<MDNode *, 4> StructPath;
  4741. for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
  4742. BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
  4743. IsNewFormat)) {
  4744. if (!StructPath.insert(BaseNode).second) {
  4745. CheckFailed("Cycle detected in struct path", &I, MD);
  4746. return false;
  4747. }
  4748. bool Invalid;
  4749. unsigned BaseNodeBitWidth;
  4750. std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
  4751. IsNewFormat);
  4752. // If the base node is invalid in itself, then we've already printed all the
  4753. // errors we wanted to print.
  4754. if (Invalid)
  4755. return false;
  4756. SeenAccessTypeInPath |= BaseNode == AccessType;
  4757. if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
  4758. AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",
  4759. &I, MD, &Offset);
  4760. AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
  4761. (BaseNodeBitWidth == 0 && Offset == 0) ||
  4762. (IsNewFormat && BaseNodeBitWidth == ~0u),
  4763. "Access bit-width not the same as description bit-width", &I, MD,
  4764. BaseNodeBitWidth, Offset.getBitWidth());
  4765. if (IsNewFormat && SeenAccessTypeInPath)
  4766. break;
  4767. }
  4768. AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",
  4769. &I, MD);
  4770. return true;
  4771. }
  4772. char VerifierLegacyPass::ID = 0;
  4773. INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
  4774. FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
  4775. return new VerifierLegacyPass(FatalErrors);
  4776. }
  4777. AnalysisKey VerifierAnalysis::Key;
  4778. VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
  4779. ModuleAnalysisManager &) {
  4780. Result Res;
  4781. Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
  4782. return Res;
  4783. }
  4784. VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
  4785. FunctionAnalysisManager &) {
  4786. return { llvm::verifyFunction(F, &dbgs()), false };
  4787. }
  4788. PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
  4789. auto Res = AM.getResult<VerifierAnalysis>(M);
  4790. if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
  4791. report_fatal_error("Broken module found, compilation aborted!");
  4792. return PreservedAnalyses::all();
  4793. }
  4794. PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
  4795. auto res = AM.getResult<VerifierAnalysis>(F);
  4796. if (res.IRBroken && FatalErrors)
  4797. report_fatal_error("Broken function found, compilation aborted!");
  4798. return PreservedAnalyses::all();
  4799. }