SelectionDAGBuilder.cpp 306 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780
  1. //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SelectionDAGBuilder.h"
  14. #include "SDNodeDbgValue.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/Analysis/AliasAnalysis.h"
  19. #include "llvm/Analysis/BranchProbabilityInfo.h"
  20. #include "llvm/Analysis/ConstantFolding.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/CodeGen/Analysis.h"
  23. #include "llvm/CodeGen/FastISel.h"
  24. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  25. #include "llvm/CodeGen/GCMetadata.h"
  26. #include "llvm/CodeGen/GCStrategy.h"
  27. #include "llvm/CodeGen/MachineFrameInfo.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineInstrBuilder.h"
  30. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  31. #include "llvm/CodeGen/MachineModuleInfo.h"
  32. #include "llvm/CodeGen/MachineRegisterInfo.h"
  33. #include "llvm/CodeGen/SelectionDAG.h"
  34. #include "llvm/CodeGen/StackMaps.h"
  35. #include "llvm/IR/CallingConv.h"
  36. #include "llvm/IR/Constants.h"
  37. #include "llvm/IR/DataLayout.h"
  38. #include "llvm/IR/DebugInfo.h"
  39. #include "llvm/IR/DerivedTypes.h"
  40. #include "llvm/IR/Function.h"
  41. #include "llvm/IR/GlobalVariable.h"
  42. #include "llvm/IR/InlineAsm.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/IntrinsicInst.h"
  45. #include "llvm/IR/Intrinsics.h"
  46. #include "llvm/IR/LLVMContext.h"
  47. #include "llvm/IR/Module.h"
  48. #include "llvm/Support/CommandLine.h"
  49. #include "llvm/Support/Debug.h"
  50. #include "llvm/Support/ErrorHandling.h"
  51. #include "llvm/Support/MathExtras.h"
  52. #include "llvm/Support/raw_ostream.h"
  53. #include "llvm/Target/TargetFrameLowering.h"
  54. #include "llvm/Target/TargetInstrInfo.h"
  55. #include "llvm/Target/TargetIntrinsicInfo.h"
  56. #include "llvm/Target/TargetLibraryInfo.h"
  57. #include "llvm/Target/TargetLowering.h"
  58. #include "llvm/Target/TargetOptions.h"
  59. #include "llvm/Target/TargetSelectionDAGInfo.h"
  60. #include "llvm/Target/TargetSubtargetInfo.h"
  61. #include <algorithm>
  62. using namespace llvm;
  63. #define DEBUG_TYPE "isel"
  64. /// LimitFloatPrecision - Generate low-precision inline sequences for
  65. /// some float libcalls (6, 8 or 12 bits).
  66. static unsigned LimitFloatPrecision;
  67. static cl::opt<unsigned, true>
  68. LimitFPPrecision("limit-float-precision",
  69. cl::desc("Generate low-precision inline sequences "
  70. "for some float libcalls"),
  71. cl::location(LimitFloatPrecision),
  72. cl::init(0));
  73. // Limit the width of DAG chains. This is important in general to prevent
  74. // prevent DAG-based analysis from blowing up. For example, alias analysis and
  75. // load clustering may not complete in reasonable time. It is difficult to
  76. // recognize and avoid this situation within each individual analysis, and
  77. // future analyses are likely to have the same behavior. Limiting DAG width is
  78. // the safe approach, and will be especially important with global DAGs.
  79. //
  80. // MaxParallelChains default is arbitrarily high to avoid affecting
  81. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  82. // sequence over this should have been converted to llvm.memcpy by the
  83. // frontend. It easy to induce this behavior with .ll code such as:
  84. // %buffer = alloca [4096 x i8]
  85. // %data = load [4096 x i8]* %argPtr
  86. // store [4096 x i8] %data, [4096 x i8]* %buffer
  87. static const unsigned MaxParallelChains = 64;
  88. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
  89. const SDValue *Parts, unsigned NumParts,
  90. MVT PartVT, EVT ValueVT, const Value *V);
  91. /// getCopyFromParts - Create a value that contains the specified legal parts
  92. /// combined into the value they represent. If the parts combine to a type
  93. /// larger then ValueVT then AssertOp can be used to specify whether the extra
  94. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  95. /// (ISD::AssertSext).
  96. static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
  97. const SDValue *Parts,
  98. unsigned NumParts, MVT PartVT, EVT ValueVT,
  99. const Value *V,
  100. ISD::NodeType AssertOp = ISD::DELETED_NODE) {
  101. if (ValueVT.isVector())
  102. return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
  103. PartVT, ValueVT, V);
  104. assert(NumParts > 0 && "No parts to assemble!");
  105. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  106. SDValue Val = Parts[0];
  107. if (NumParts > 1) {
  108. // Assemble the value from multiple parts.
  109. if (ValueVT.isInteger()) {
  110. unsigned PartBits = PartVT.getSizeInBits();
  111. unsigned ValueBits = ValueVT.getSizeInBits();
  112. // Assemble the power of 2 part.
  113. unsigned RoundParts = NumParts & (NumParts - 1) ?
  114. 1 << Log2_32(NumParts) : NumParts;
  115. unsigned RoundBits = PartBits * RoundParts;
  116. EVT RoundVT = RoundBits == ValueBits ?
  117. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  118. SDValue Lo, Hi;
  119. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  120. if (RoundParts > 2) {
  121. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  122. PartVT, HalfVT, V);
  123. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  124. RoundParts / 2, PartVT, HalfVT, V);
  125. } else {
  126. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  127. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  128. }
  129. if (TLI.isBigEndian())
  130. std::swap(Lo, Hi);
  131. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  132. if (RoundParts < NumParts) {
  133. // Assemble the trailing non-power-of-2 part.
  134. unsigned OddParts = NumParts - RoundParts;
  135. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  136. Hi = getCopyFromParts(DAG, DL,
  137. Parts + RoundParts, OddParts, PartVT, OddVT, V);
  138. // Combine the round and odd parts.
  139. Lo = Val;
  140. if (TLI.isBigEndian())
  141. std::swap(Lo, Hi);
  142. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  143. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  144. Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  145. DAG.getConstant(Lo.getValueType().getSizeInBits(),
  146. TLI.getPointerTy()));
  147. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  148. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  149. }
  150. } else if (PartVT.isFloatingPoint()) {
  151. // FP split into multiple FP parts (for ppcf128)
  152. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  153. "Unexpected split");
  154. SDValue Lo, Hi;
  155. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  156. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  157. if (TLI.hasBigEndianPartOrdering(ValueVT))
  158. std::swap(Lo, Hi);
  159. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  160. } else {
  161. // FP split into integer parts (soft fp)
  162. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  163. !PartVT.isVector() && "Unexpected split");
  164. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  165. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
  166. }
  167. }
  168. // There is now one part, held in Val. Correct it to match ValueVT.
  169. EVT PartEVT = Val.getValueType();
  170. if (PartEVT == ValueVT)
  171. return Val;
  172. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  173. if (ValueVT.bitsLT(PartEVT)) {
  174. // For a truncate, see if we have any information to
  175. // indicate whether the truncated bits will always be
  176. // zero or sign-extension.
  177. if (AssertOp != ISD::DELETED_NODE)
  178. Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
  179. DAG.getValueType(ValueVT));
  180. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  181. }
  182. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  183. }
  184. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  185. // FP_ROUND's are always exact here.
  186. if (ValueVT.bitsLT(Val.getValueType()))
  187. return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
  188. DAG.getTargetConstant(1, TLI.getPointerTy()));
  189. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  190. }
  191. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  192. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  193. llvm_unreachable("Unknown mismatch!");
  194. }
  195. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  196. const Twine &ErrMsg) {
  197. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  198. if (!V)
  199. return Ctx.emitError(ErrMsg);
  200. const char *AsmError = ", possible invalid constraint for vector type";
  201. if (const CallInst *CI = dyn_cast<CallInst>(I))
  202. if (isa<InlineAsm>(CI->getCalledValue()))
  203. return Ctx.emitError(I, ErrMsg + AsmError);
  204. return Ctx.emitError(I, ErrMsg);
  205. }
  206. /// getCopyFromPartsVector - Create a value that contains the specified legal
  207. /// parts combined into the value they represent. If the parts combine to a
  208. /// type larger then ValueVT then AssertOp can be used to specify whether the
  209. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  210. /// ValueVT (ISD::AssertSext).
  211. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
  212. const SDValue *Parts, unsigned NumParts,
  213. MVT PartVT, EVT ValueVT, const Value *V) {
  214. assert(ValueVT.isVector() && "Not a vector value");
  215. assert(NumParts > 0 && "No parts to assemble!");
  216. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  217. SDValue Val = Parts[0];
  218. // Handle a multi-element vector.
  219. if (NumParts > 1) {
  220. EVT IntermediateVT;
  221. MVT RegisterVT;
  222. unsigned NumIntermediates;
  223. unsigned NumRegs =
  224. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  225. NumIntermediates, RegisterVT);
  226. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  227. NumParts = NumRegs; // Silence a compiler warning.
  228. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  229. assert(RegisterVT == Parts[0].getSimpleValueType() &&
  230. "Part type doesn't match part!");
  231. // Assemble the parts into intermediate operands.
  232. SmallVector<SDValue, 8> Ops(NumIntermediates);
  233. if (NumIntermediates == NumParts) {
  234. // If the register was not expanded, truncate or copy the value,
  235. // as appropriate.
  236. for (unsigned i = 0; i != NumParts; ++i)
  237. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  238. PartVT, IntermediateVT, V);
  239. } else if (NumParts > 0) {
  240. // If the intermediate type was expanded, build the intermediate
  241. // operands from the parts.
  242. assert(NumParts % NumIntermediates == 0 &&
  243. "Must expand into a divisible number of parts!");
  244. unsigned Factor = NumParts / NumIntermediates;
  245. for (unsigned i = 0; i != NumIntermediates; ++i)
  246. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  247. PartVT, IntermediateVT, V);
  248. }
  249. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  250. // intermediate operands.
  251. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  252. : ISD::BUILD_VECTOR,
  253. DL, ValueVT, Ops);
  254. }
  255. // There is now one part, held in Val. Correct it to match ValueVT.
  256. EVT PartEVT = Val.getValueType();
  257. if (PartEVT == ValueVT)
  258. return Val;
  259. if (PartEVT.isVector()) {
  260. // If the element type of the source/dest vectors are the same, but the
  261. // parts vector has more elements than the value vector, then we have a
  262. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  263. // elements we want.
  264. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  265. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  266. "Cannot narrow, it would be a lossy transformation");
  267. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  268. DAG.getConstant(0, TLI.getVectorIdxTy()));
  269. }
  270. // Vector/Vector bitcast.
  271. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  272. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  273. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  274. "Cannot handle this kind of promotion");
  275. // Promoted vector extract
  276. bool Smaller = ValueVT.bitsLE(PartEVT);
  277. return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  278. DL, ValueVT, Val);
  279. }
  280. // Trivial bitcast if the types are the same size and the destination
  281. // vector type is legal.
  282. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  283. TLI.isTypeLegal(ValueVT))
  284. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  285. // Handle cases such as i8 -> <1 x i1>
  286. if (ValueVT.getVectorNumElements() != 1) {
  287. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  288. "non-trivial scalar-to-vector conversion");
  289. return DAG.getUNDEF(ValueVT);
  290. }
  291. if (ValueVT.getVectorNumElements() == 1 &&
  292. ValueVT.getVectorElementType() != PartEVT) {
  293. bool Smaller = ValueVT.bitsLE(PartEVT);
  294. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  295. DL, ValueVT.getScalarType(), Val);
  296. }
  297. return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
  298. }
  299. static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
  300. SDValue Val, SDValue *Parts, unsigned NumParts,
  301. MVT PartVT, const Value *V);
  302. /// getCopyToParts - Create a series of nodes that contain the specified value
  303. /// split into legal parts. If the parts contain more bits than Val, then, for
  304. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  305. static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
  306. SDValue Val, SDValue *Parts, unsigned NumParts,
  307. MVT PartVT, const Value *V,
  308. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  309. EVT ValueVT = Val.getValueType();
  310. // Handle the vector case separately.
  311. if (ValueVT.isVector())
  312. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
  313. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  314. unsigned PartBits = PartVT.getSizeInBits();
  315. unsigned OrigNumParts = NumParts;
  316. assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
  317. if (NumParts == 0)
  318. return;
  319. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  320. EVT PartEVT = PartVT;
  321. if (PartEVT == ValueVT) {
  322. assert(NumParts == 1 && "No-op copy with multiple parts!");
  323. Parts[0] = Val;
  324. return;
  325. }
  326. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  327. // If the parts cover more bits than the value has, promote the value.
  328. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  329. assert(NumParts == 1 && "Do not know what to promote to!");
  330. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  331. } else {
  332. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  333. ValueVT.isInteger() &&
  334. "Unknown mismatch!");
  335. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  336. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  337. if (PartVT == MVT::x86mmx)
  338. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  339. }
  340. } else if (PartBits == ValueVT.getSizeInBits()) {
  341. // Different types of the same size.
  342. assert(NumParts == 1 && PartEVT != ValueVT);
  343. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  344. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  345. // If the parts cover less bits than value has, truncate the value.
  346. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  347. ValueVT.isInteger() &&
  348. "Unknown mismatch!");
  349. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  350. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  351. if (PartVT == MVT::x86mmx)
  352. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  353. }
  354. // The value may have changed - recompute ValueVT.
  355. ValueVT = Val.getValueType();
  356. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  357. "Failed to tile the value with PartVT!");
  358. if (NumParts == 1) {
  359. if (PartEVT != ValueVT)
  360. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  361. "scalar-to-vector conversion failed");
  362. Parts[0] = Val;
  363. return;
  364. }
  365. // Expand the value into multiple parts.
  366. if (NumParts & (NumParts - 1)) {
  367. // The number of parts is not a power of 2. Split off and copy the tail.
  368. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  369. "Do not know what to expand to!");
  370. unsigned RoundParts = 1 << Log2_32(NumParts);
  371. unsigned RoundBits = RoundParts * PartBits;
  372. unsigned OddParts = NumParts - RoundParts;
  373. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  374. DAG.getIntPtrConstant(RoundBits));
  375. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
  376. if (TLI.isBigEndian())
  377. // The odd parts were reversed by getCopyToParts - unreverse them.
  378. std::reverse(Parts + RoundParts, Parts + NumParts);
  379. NumParts = RoundParts;
  380. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  381. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  382. }
  383. // The number of parts is a power of 2. Repeatedly bisect the value using
  384. // EXTRACT_ELEMENT.
  385. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  386. EVT::getIntegerVT(*DAG.getContext(),
  387. ValueVT.getSizeInBits()),
  388. Val);
  389. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  390. for (unsigned i = 0; i < NumParts; i += StepSize) {
  391. unsigned ThisBits = StepSize * PartBits / 2;
  392. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  393. SDValue &Part0 = Parts[i];
  394. SDValue &Part1 = Parts[i+StepSize/2];
  395. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  396. ThisVT, Part0, DAG.getIntPtrConstant(1));
  397. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  398. ThisVT, Part0, DAG.getIntPtrConstant(0));
  399. if (ThisBits == PartBits && ThisVT != PartVT) {
  400. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  401. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  402. }
  403. }
  404. }
  405. if (TLI.isBigEndian())
  406. std::reverse(Parts, Parts + OrigNumParts);
  407. }
  408. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  409. /// value split into legal parts.
  410. static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
  411. SDValue Val, SDValue *Parts, unsigned NumParts,
  412. MVT PartVT, const Value *V) {
  413. EVT ValueVT = Val.getValueType();
  414. assert(ValueVT.isVector() && "Not a vector");
  415. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  416. if (NumParts == 1) {
  417. EVT PartEVT = PartVT;
  418. if (PartEVT == ValueVT) {
  419. // Nothing to do.
  420. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  421. // Bitconvert vector->vector case.
  422. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  423. } else if (PartVT.isVector() &&
  424. PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
  425. PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
  426. EVT ElementVT = PartVT.getVectorElementType();
  427. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  428. // undef elements.
  429. SmallVector<SDValue, 16> Ops;
  430. for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
  431. Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  432. ElementVT, Val, DAG.getConstant(i,
  433. TLI.getVectorIdxTy())));
  434. for (unsigned i = ValueVT.getVectorNumElements(),
  435. e = PartVT.getVectorNumElements(); i != e; ++i)
  436. Ops.push_back(DAG.getUNDEF(ElementVT));
  437. Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
  438. // FIXME: Use CONCAT for 2x -> 4x.
  439. //SDValue UndefElts = DAG.getUNDEF(VectorTy);
  440. //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
  441. } else if (PartVT.isVector() &&
  442. PartEVT.getVectorElementType().bitsGE(
  443. ValueVT.getVectorElementType()) &&
  444. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  445. // Promoted vector extract
  446. bool Smaller = PartEVT.bitsLE(ValueVT);
  447. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  448. DL, PartVT, Val);
  449. } else{
  450. // Vector -> scalar conversion.
  451. assert(ValueVT.getVectorNumElements() == 1 &&
  452. "Only trivial vector-to-scalar conversions should get here!");
  453. Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  454. PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
  455. bool Smaller = ValueVT.bitsLE(PartVT);
  456. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  457. DL, PartVT, Val);
  458. }
  459. Parts[0] = Val;
  460. return;
  461. }
  462. // Handle a multi-element vector.
  463. EVT IntermediateVT;
  464. MVT RegisterVT;
  465. unsigned NumIntermediates;
  466. unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
  467. IntermediateVT,
  468. NumIntermediates, RegisterVT);
  469. unsigned NumElements = ValueVT.getVectorNumElements();
  470. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  471. NumParts = NumRegs; // Silence a compiler warning.
  472. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  473. // Split the vector into intermediate operands.
  474. SmallVector<SDValue, 8> Ops(NumIntermediates);
  475. for (unsigned i = 0; i != NumIntermediates; ++i) {
  476. if (IntermediateVT.isVector())
  477. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
  478. IntermediateVT, Val,
  479. DAG.getConstant(i * (NumElements / NumIntermediates),
  480. TLI.getVectorIdxTy()));
  481. else
  482. Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  483. IntermediateVT, Val,
  484. DAG.getConstant(i, TLI.getVectorIdxTy()));
  485. }
  486. // Split the intermediate operands into legal parts.
  487. if (NumParts == NumIntermediates) {
  488. // If the register was not expanded, promote or copy the value,
  489. // as appropriate.
  490. for (unsigned i = 0; i != NumParts; ++i)
  491. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
  492. } else if (NumParts > 0) {
  493. // If the intermediate type was expanded, split each the value into
  494. // legal parts.
  495. assert(NumParts % NumIntermediates == 0 &&
  496. "Must expand into a divisible number of parts!");
  497. unsigned Factor = NumParts / NumIntermediates;
  498. for (unsigned i = 0; i != NumIntermediates; ++i)
  499. getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
  500. }
  501. }
  502. namespace {
  503. /// RegsForValue - This struct represents the registers (physical or virtual)
  504. /// that a particular set of values is assigned, and the type information
  505. /// about the value. The most common situation is to represent one value at a
  506. /// time, but struct or array values are handled element-wise as multiple
  507. /// values. The splitting of aggregates is performed recursively, so that we
  508. /// never have aggregate-typed registers. The values at this point do not
  509. /// necessarily have legal types, so each value may require one or more
  510. /// registers of some legal type.
  511. ///
  512. struct RegsForValue {
  513. /// ValueVTs - The value types of the values, which may not be legal, and
  514. /// may need be promoted or synthesized from one or more registers.
  515. ///
  516. SmallVector<EVT, 4> ValueVTs;
  517. /// RegVTs - The value types of the registers. This is the same size as
  518. /// ValueVTs and it records, for each value, what the type of the assigned
  519. /// register or registers are. (Individual values are never synthesized
  520. /// from more than one type of register.)
  521. ///
  522. /// With virtual registers, the contents of RegVTs is redundant with TLI's
  523. /// getRegisterType member function, however when with physical registers
  524. /// it is necessary to have a separate record of the types.
  525. ///
  526. SmallVector<MVT, 4> RegVTs;
  527. /// Regs - This list holds the registers assigned to the values.
  528. /// Each legal or promoted value requires one register, and each
  529. /// expanded value requires multiple registers.
  530. ///
  531. SmallVector<unsigned, 4> Regs;
  532. RegsForValue() {}
  533. RegsForValue(const SmallVector<unsigned, 4> &regs,
  534. MVT regvt, EVT valuevt)
  535. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
  536. RegsForValue(LLVMContext &Context, const TargetLowering &tli,
  537. unsigned Reg, Type *Ty) {
  538. ComputeValueVTs(tli, Ty, ValueVTs);
  539. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  540. EVT ValueVT = ValueVTs[Value];
  541. unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
  542. MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
  543. for (unsigned i = 0; i != NumRegs; ++i)
  544. Regs.push_back(Reg + i);
  545. RegVTs.push_back(RegisterVT);
  546. Reg += NumRegs;
  547. }
  548. }
  549. /// append - Add the specified values to this one.
  550. void append(const RegsForValue &RHS) {
  551. ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
  552. RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
  553. Regs.append(RHS.Regs.begin(), RHS.Regs.end());
  554. }
  555. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  556. /// this value and returns the result as a ValueVTs value. This uses
  557. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  558. /// If the Flag pointer is NULL, no flag is used.
  559. SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
  560. SDLoc dl,
  561. SDValue &Chain, SDValue *Flag,
  562. const Value *V = nullptr) const;
  563. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  564. /// specified value into the registers specified by this object. This uses
  565. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  566. /// If the Flag pointer is NULL, no flag is used.
  567. void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
  568. SDValue &Chain, SDValue *Flag, const Value *V) const;
  569. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  570. /// operand list. This adds the code marker, matching input operand index
  571. /// (if applicable), and includes the number of values added into it.
  572. void AddInlineAsmOperands(unsigned Kind,
  573. bool HasMatching, unsigned MatchingIdx,
  574. SelectionDAG &DAG,
  575. std::vector<SDValue> &Ops) const;
  576. };
  577. }
  578. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  579. /// this value and returns the result as a ValueVT value. This uses
  580. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  581. /// If the Flag pointer is NULL, no flag is used.
  582. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  583. FunctionLoweringInfo &FuncInfo,
  584. SDLoc dl,
  585. SDValue &Chain, SDValue *Flag,
  586. const Value *V) const {
  587. // A Value with type {} or [0 x %t] needs no registers.
  588. if (ValueVTs.empty())
  589. return SDValue();
  590. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  591. // Assemble the legal parts into the final values.
  592. SmallVector<SDValue, 4> Values(ValueVTs.size());
  593. SmallVector<SDValue, 8> Parts;
  594. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  595. // Copy the legal parts from the registers.
  596. EVT ValueVT = ValueVTs[Value];
  597. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  598. MVT RegisterVT = RegVTs[Value];
  599. Parts.resize(NumRegs);
  600. for (unsigned i = 0; i != NumRegs; ++i) {
  601. SDValue P;
  602. if (!Flag) {
  603. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  604. } else {
  605. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  606. *Flag = P.getValue(2);
  607. }
  608. Chain = P.getValue(1);
  609. Parts[i] = P;
  610. // If the source register was virtual and if we know something about it,
  611. // add an assert node.
  612. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  613. !RegisterVT.isInteger() || RegisterVT.isVector())
  614. continue;
  615. const FunctionLoweringInfo::LiveOutInfo *LOI =
  616. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  617. if (!LOI)
  618. continue;
  619. unsigned RegSize = RegisterVT.getSizeInBits();
  620. unsigned NumSignBits = LOI->NumSignBits;
  621. unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
  622. if (NumZeroBits == RegSize) {
  623. // The current value is a zero.
  624. // Explicitly express that as it would be easier for
  625. // optimizations to kick in.
  626. Parts[i] = DAG.getConstant(0, RegisterVT);
  627. continue;
  628. }
  629. // FIXME: We capture more information than the dag can represent. For
  630. // now, just use the tightest assertzext/assertsext possible.
  631. bool isSExt = true;
  632. EVT FromVT(MVT::Other);
  633. if (NumSignBits == RegSize)
  634. isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
  635. else if (NumZeroBits >= RegSize-1)
  636. isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
  637. else if (NumSignBits > RegSize-8)
  638. isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
  639. else if (NumZeroBits >= RegSize-8)
  640. isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
  641. else if (NumSignBits > RegSize-16)
  642. isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
  643. else if (NumZeroBits >= RegSize-16)
  644. isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
  645. else if (NumSignBits > RegSize-32)
  646. isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
  647. else if (NumZeroBits >= RegSize-32)
  648. isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
  649. else
  650. continue;
  651. // Add an assertion node.
  652. assert(FromVT != MVT::Other);
  653. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  654. RegisterVT, P, DAG.getValueType(FromVT));
  655. }
  656. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  657. NumRegs, RegisterVT, ValueVT, V);
  658. Part += NumRegs;
  659. Parts.clear();
  660. }
  661. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  662. }
  663. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  664. /// specified value into the registers specified by this object. This uses
  665. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  666. /// If the Flag pointer is NULL, no flag is used.
  667. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
  668. SDValue &Chain, SDValue *Flag,
  669. const Value *V) const {
  670. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  671. // Get the list of the values's legal parts.
  672. unsigned NumRegs = Regs.size();
  673. SmallVector<SDValue, 8> Parts(NumRegs);
  674. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  675. EVT ValueVT = ValueVTs[Value];
  676. unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  677. MVT RegisterVT = RegVTs[Value];
  678. ISD::NodeType ExtendKind =
  679. TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND;
  680. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  681. &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
  682. Part += NumParts;
  683. }
  684. // Copy the parts into the registers.
  685. SmallVector<SDValue, 8> Chains(NumRegs);
  686. for (unsigned i = 0; i != NumRegs; ++i) {
  687. SDValue Part;
  688. if (!Flag) {
  689. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  690. } else {
  691. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  692. *Flag = Part.getValue(1);
  693. }
  694. Chains[i] = Part.getValue(0);
  695. }
  696. if (NumRegs == 1 || Flag)
  697. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  698. // flagged to it. That is the CopyToReg nodes and the user are considered
  699. // a single scheduling unit. If we create a TokenFactor and return it as
  700. // chain, then the TokenFactor is both a predecessor (operand) of the
  701. // user as well as a successor (the TF operands are flagged to the user).
  702. // c1, f1 = CopyToReg
  703. // c2, f2 = CopyToReg
  704. // c3 = TokenFactor c1, c2
  705. // ...
  706. // = op c3, ..., f2
  707. Chain = Chains[NumRegs-1];
  708. else
  709. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  710. }
  711. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  712. /// operand list. This adds the code marker and includes the number of
  713. /// values added into it.
  714. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  715. unsigned MatchingIdx,
  716. SelectionDAG &DAG,
  717. std::vector<SDValue> &Ops) const {
  718. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  719. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  720. if (HasMatching)
  721. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  722. else if (!Regs.empty() &&
  723. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  724. // Put the register class of the virtual registers in the flag word. That
  725. // way, later passes can recompute register class constraints for inline
  726. // assembly as well as normal instructions.
  727. // Don't do this for tied operands that can use the regclass information
  728. // from the def.
  729. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  730. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  731. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  732. }
  733. SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
  734. Ops.push_back(Res);
  735. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  736. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  737. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  738. MVT RegisterVT = RegVTs[Value];
  739. for (unsigned i = 0; i != NumRegs; ++i) {
  740. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  741. unsigned TheReg = Regs[Reg++];
  742. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  743. if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
  744. // If we clobbered the stack pointer, MFI should know about it.
  745. assert(DAG.getMachineFunction().getFrameInfo()->
  746. hasInlineAsmWithSPAdjust());
  747. }
  748. }
  749. }
  750. }
  751. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
  752. const TargetLibraryInfo *li) {
  753. AA = &aa;
  754. GFI = gfi;
  755. LibInfo = li;
  756. DL = DAG.getSubtarget().getDataLayout();
  757. Context = DAG.getContext();
  758. LPadToCallSiteMap.clear();
  759. }
  760. /// clear - Clear out the current SelectionDAG and the associated
  761. /// state and prepare this SelectionDAGBuilder object to be used
  762. /// for a new block. This doesn't clear out information about
  763. /// additional blocks that are needed to complete switch lowering
  764. /// or PHI node updating; that information is cleared out as it is
  765. /// consumed.
  766. void SelectionDAGBuilder::clear() {
  767. NodeMap.clear();
  768. UnusedArgNodeMap.clear();
  769. PendingLoads.clear();
  770. PendingExports.clear();
  771. CurInst = nullptr;
  772. HasTailCall = false;
  773. SDNodeOrder = LowestSDNodeOrder;
  774. }
  775. /// clearDanglingDebugInfo - Clear the dangling debug information
  776. /// map. This function is separated from the clear so that debug
  777. /// information that is dangling in a basic block can be properly
  778. /// resolved in a different basic block. This allows the
  779. /// SelectionDAG to resolve dangling debug information attached
  780. /// to PHI nodes.
  781. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  782. DanglingDebugInfoMap.clear();
  783. }
  784. /// getRoot - Return the current virtual root of the Selection DAG,
  785. /// flushing any PendingLoad items. This must be done before emitting
  786. /// a store or any other node that may need to be ordered after any
  787. /// prior load instructions.
  788. ///
  789. SDValue SelectionDAGBuilder::getRoot() {
  790. if (PendingLoads.empty())
  791. return DAG.getRoot();
  792. if (PendingLoads.size() == 1) {
  793. SDValue Root = PendingLoads[0];
  794. DAG.setRoot(Root);
  795. PendingLoads.clear();
  796. return Root;
  797. }
  798. // Otherwise, we have to make a token factor node.
  799. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  800. PendingLoads);
  801. PendingLoads.clear();
  802. DAG.setRoot(Root);
  803. return Root;
  804. }
  805. /// getControlRoot - Similar to getRoot, but instead of flushing all the
  806. /// PendingLoad items, flush all the PendingExports items. It is necessary
  807. /// to do this before emitting a terminator instruction.
  808. ///
  809. SDValue SelectionDAGBuilder::getControlRoot() {
  810. SDValue Root = DAG.getRoot();
  811. if (PendingExports.empty())
  812. return Root;
  813. // Turn all of the CopyToReg chains into one factored node.
  814. if (Root.getOpcode() != ISD::EntryToken) {
  815. unsigned i = 0, e = PendingExports.size();
  816. for (; i != e; ++i) {
  817. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  818. if (PendingExports[i].getNode()->getOperand(0) == Root)
  819. break; // Don't add the root if we already indirectly depend on it.
  820. }
  821. if (i == e)
  822. PendingExports.push_back(Root);
  823. }
  824. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  825. PendingExports);
  826. PendingExports.clear();
  827. DAG.setRoot(Root);
  828. return Root;
  829. }
  830. void SelectionDAGBuilder::visit(const Instruction &I) {
  831. // Set up outgoing PHI node register values before emitting the terminator.
  832. if (isa<TerminatorInst>(&I))
  833. HandlePHINodesInSuccessorBlocks(I.getParent());
  834. ++SDNodeOrder;
  835. CurInst = &I;
  836. visit(I.getOpcode(), I);
  837. if (!isa<TerminatorInst>(&I) && !HasTailCall)
  838. CopyToExportRegsIfNeeded(&I);
  839. CurInst = nullptr;
  840. }
  841. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  842. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  843. }
  844. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  845. // Note: this doesn't use InstVisitor, because it has to work with
  846. // ConstantExpr's in addition to instructions.
  847. switch (Opcode) {
  848. default: llvm_unreachable("Unknown instruction type encountered!");
  849. // Build the switch statement using the Instruction.def file.
  850. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  851. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  852. #include "llvm/IR/Instruction.def"
  853. }
  854. }
  855. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  856. // generate the debug data structures now that we've seen its definition.
  857. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  858. SDValue Val) {
  859. DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
  860. if (DDI.getDI()) {
  861. const DbgValueInst *DI = DDI.getDI();
  862. DebugLoc dl = DDI.getdl();
  863. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  864. MDNode *Variable = DI->getVariable();
  865. uint64_t Offset = DI->getOffset();
  866. // A dbg.value for an alloca is always indirect.
  867. bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
  868. SDDbgValue *SDV;
  869. if (Val.getNode()) {
  870. if (!EmitFuncArgumentDbgValue(V, Variable, Offset, IsIndirect, Val)) {
  871. SDV = DAG.getDbgValue(Variable, Val.getNode(),
  872. Val.getResNo(), IsIndirect,
  873. Offset, dl, DbgSDNodeOrder);
  874. DAG.AddDbgValue(SDV, Val.getNode(), false);
  875. }
  876. } else
  877. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  878. DanglingDebugInfoMap[V] = DanglingDebugInfo();
  879. }
  880. }
  881. /// getValue - Return an SDValue for the given Value.
  882. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  883. // If we already have an SDValue for this value, use it. It's important
  884. // to do this first, so that we don't create a CopyFromReg if we already
  885. // have a regular SDValue.
  886. SDValue &N = NodeMap[V];
  887. if (N.getNode()) return N;
  888. // If there's a virtual register allocated and initialized for this
  889. // value, use it.
  890. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  891. if (It != FuncInfo.ValueMap.end()) {
  892. unsigned InReg = It->second;
  893. RegsForValue RFV(*DAG.getContext(),
  894. *TM.getSubtargetImpl()->getTargetLowering(), InReg,
  895. V->getType());
  896. SDValue Chain = DAG.getEntryNode();
  897. N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  898. resolveDanglingDebugInfo(V, N);
  899. return N;
  900. }
  901. // Otherwise create a new SDValue and remember it.
  902. SDValue Val = getValueImpl(V);
  903. NodeMap[V] = Val;
  904. resolveDanglingDebugInfo(V, Val);
  905. return Val;
  906. }
  907. /// getNonRegisterValue - Return an SDValue for the given Value, but
  908. /// don't look in FuncInfo.ValueMap for a virtual register.
  909. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  910. // If we already have an SDValue for this value, use it.
  911. SDValue &N = NodeMap[V];
  912. if (N.getNode()) return N;
  913. // Otherwise create a new SDValue and remember it.
  914. SDValue Val = getValueImpl(V);
  915. NodeMap[V] = Val;
  916. resolveDanglingDebugInfo(V, Val);
  917. return Val;
  918. }
  919. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  920. /// Create an SDValue for the given value.
  921. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  922. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  923. if (const Constant *C = dyn_cast<Constant>(V)) {
  924. EVT VT = TLI->getValueType(V->getType(), true);
  925. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  926. return DAG.getConstant(*CI, VT);
  927. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  928. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  929. if (isa<ConstantPointerNull>(C)) {
  930. unsigned AS = V->getType()->getPointerAddressSpace();
  931. return DAG.getConstant(0, TLI->getPointerTy(AS));
  932. }
  933. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  934. return DAG.getConstantFP(*CFP, VT);
  935. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  936. return DAG.getUNDEF(VT);
  937. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  938. visit(CE->getOpcode(), *CE);
  939. SDValue N1 = NodeMap[V];
  940. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  941. return N1;
  942. }
  943. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  944. SmallVector<SDValue, 4> Constants;
  945. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  946. OI != OE; ++OI) {
  947. SDNode *Val = getValue(*OI).getNode();
  948. // If the operand is an empty aggregate, there are no values.
  949. if (!Val) continue;
  950. // Add each leaf value from the operand to the Constants list
  951. // to form a flattened list of all the values.
  952. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  953. Constants.push_back(SDValue(Val, i));
  954. }
  955. return DAG.getMergeValues(Constants, getCurSDLoc());
  956. }
  957. if (const ConstantDataSequential *CDS =
  958. dyn_cast<ConstantDataSequential>(C)) {
  959. SmallVector<SDValue, 4> Ops;
  960. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  961. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  962. // Add each leaf value from the operand to the Constants list
  963. // to form a flattened list of all the values.
  964. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  965. Ops.push_back(SDValue(Val, i));
  966. }
  967. if (isa<ArrayType>(CDS->getType()))
  968. return DAG.getMergeValues(Ops, getCurSDLoc());
  969. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
  970. VT, Ops);
  971. }
  972. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  973. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  974. "Unknown struct or array constant!");
  975. SmallVector<EVT, 4> ValueVTs;
  976. ComputeValueVTs(*TLI, C->getType(), ValueVTs);
  977. unsigned NumElts = ValueVTs.size();
  978. if (NumElts == 0)
  979. return SDValue(); // empty struct
  980. SmallVector<SDValue, 4> Constants(NumElts);
  981. for (unsigned i = 0; i != NumElts; ++i) {
  982. EVT EltVT = ValueVTs[i];
  983. if (isa<UndefValue>(C))
  984. Constants[i] = DAG.getUNDEF(EltVT);
  985. else if (EltVT.isFloatingPoint())
  986. Constants[i] = DAG.getConstantFP(0, EltVT);
  987. else
  988. Constants[i] = DAG.getConstant(0, EltVT);
  989. }
  990. return DAG.getMergeValues(Constants, getCurSDLoc());
  991. }
  992. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  993. return DAG.getBlockAddress(BA, VT);
  994. VectorType *VecTy = cast<VectorType>(V->getType());
  995. unsigned NumElements = VecTy->getNumElements();
  996. // Now that we know the number and type of the elements, get that number of
  997. // elements into the Ops array based on what kind of constant it is.
  998. SmallVector<SDValue, 16> Ops;
  999. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1000. for (unsigned i = 0; i != NumElements; ++i)
  1001. Ops.push_back(getValue(CV->getOperand(i)));
  1002. } else {
  1003. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1004. EVT EltVT = TLI->getValueType(VecTy->getElementType());
  1005. SDValue Op;
  1006. if (EltVT.isFloatingPoint())
  1007. Op = DAG.getConstantFP(0, EltVT);
  1008. else
  1009. Op = DAG.getConstant(0, EltVT);
  1010. Ops.assign(NumElements, Op);
  1011. }
  1012. // Create a BUILD_VECTOR node.
  1013. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
  1014. }
  1015. // If this is a static alloca, generate it as the frameindex instead of
  1016. // computation.
  1017. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1018. DenseMap<const AllocaInst*, int>::iterator SI =
  1019. FuncInfo.StaticAllocaMap.find(AI);
  1020. if (SI != FuncInfo.StaticAllocaMap.end())
  1021. return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
  1022. }
  1023. // If this is an instruction which fast-isel has deferred, select it now.
  1024. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1025. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1026. RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
  1027. SDValue Chain = DAG.getEntryNode();
  1028. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1029. }
  1030. llvm_unreachable("Can't get register for value!");
  1031. }
  1032. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1033. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  1034. SDValue Chain = getControlRoot();
  1035. SmallVector<ISD::OutputArg, 8> Outs;
  1036. SmallVector<SDValue, 8> OutVals;
  1037. if (!FuncInfo.CanLowerReturn) {
  1038. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1039. const Function *F = I.getParent()->getParent();
  1040. // Emit a store of the return value through the virtual register.
  1041. // Leave Outs empty so that LowerReturn won't try to load return
  1042. // registers the usual way.
  1043. SmallVector<EVT, 1> PtrValueVTs;
  1044. ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
  1045. PtrValueVTs);
  1046. SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
  1047. SDValue RetOp = getValue(I.getOperand(0));
  1048. SmallVector<EVT, 4> ValueVTs;
  1049. SmallVector<uint64_t, 4> Offsets;
  1050. ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1051. unsigned NumValues = ValueVTs.size();
  1052. SmallVector<SDValue, 4> Chains(NumValues);
  1053. for (unsigned i = 0; i != NumValues; ++i) {
  1054. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
  1055. RetPtr.getValueType(), RetPtr,
  1056. DAG.getIntPtrConstant(Offsets[i]));
  1057. Chains[i] =
  1058. DAG.getStore(Chain, getCurSDLoc(),
  1059. SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1060. // FIXME: better loc info would be nice.
  1061. Add, MachinePointerInfo(), false, false, 0);
  1062. }
  1063. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1064. MVT::Other, Chains);
  1065. } else if (I.getNumOperands() != 0) {
  1066. SmallVector<EVT, 4> ValueVTs;
  1067. ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
  1068. unsigned NumValues = ValueVTs.size();
  1069. if (NumValues) {
  1070. SDValue RetOp = getValue(I.getOperand(0));
  1071. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  1072. EVT VT = ValueVTs[j];
  1073. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1074. const Function *F = I.getParent()->getParent();
  1075. if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1076. Attribute::SExt))
  1077. ExtendKind = ISD::SIGN_EXTEND;
  1078. else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1079. Attribute::ZExt))
  1080. ExtendKind = ISD::ZERO_EXTEND;
  1081. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1082. VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
  1083. unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
  1084. MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
  1085. SmallVector<SDValue, 4> Parts(NumParts);
  1086. getCopyToParts(DAG, getCurSDLoc(),
  1087. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1088. &Parts[0], NumParts, PartVT, &I, ExtendKind);
  1089. // 'inreg' on function refers to return value
  1090. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1091. if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1092. Attribute::InReg))
  1093. Flags.setInReg();
  1094. // Propagate extension type if any
  1095. if (ExtendKind == ISD::SIGN_EXTEND)
  1096. Flags.setSExt();
  1097. else if (ExtendKind == ISD::ZERO_EXTEND)
  1098. Flags.setZExt();
  1099. for (unsigned i = 0; i < NumParts; ++i) {
  1100. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1101. VT, /*isfixed=*/true, 0, 0));
  1102. OutVals.push_back(Parts[i]);
  1103. }
  1104. }
  1105. }
  1106. }
  1107. bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
  1108. CallingConv::ID CallConv =
  1109. DAG.getMachineFunction().getFunction()->getCallingConv();
  1110. Chain = TM.getSubtargetImpl()->getTargetLowering()->LowerReturn(
  1111. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1112. // Verify that the target's LowerReturn behaved as expected.
  1113. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1114. "LowerReturn didn't return a valid chain!");
  1115. // Update the DAG with the new chain value resulting from return lowering.
  1116. DAG.setRoot(Chain);
  1117. }
  1118. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1119. /// created for it, emit nodes to copy the value into the virtual
  1120. /// registers.
  1121. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1122. // Skip empty types
  1123. if (V->getType()->isEmptyTy())
  1124. return;
  1125. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1126. if (VMI != FuncInfo.ValueMap.end()) {
  1127. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1128. CopyValueToVirtualRegister(V, VMI->second);
  1129. }
  1130. }
  1131. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1132. /// the current basic block, add it to ValueMap now so that we'll get a
  1133. /// CopyTo/FromReg.
  1134. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1135. // No need to export constants.
  1136. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1137. // Already exported?
  1138. if (FuncInfo.isExportedInst(V)) return;
  1139. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1140. CopyValueToVirtualRegister(V, Reg);
  1141. }
  1142. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1143. const BasicBlock *FromBB) {
  1144. // The operands of the setcc have to be in this block. We don't know
  1145. // how to export them from some other block.
  1146. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1147. // Can export from current BB.
  1148. if (VI->getParent() == FromBB)
  1149. return true;
  1150. // Is already exported, noop.
  1151. return FuncInfo.isExportedInst(V);
  1152. }
  1153. // If this is an argument, we can export it if the BB is the entry block or
  1154. // if it is already exported.
  1155. if (isa<Argument>(V)) {
  1156. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1157. return true;
  1158. // Otherwise, can only export this if it is already exported.
  1159. return FuncInfo.isExportedInst(V);
  1160. }
  1161. // Otherwise, constants can always be exported.
  1162. return true;
  1163. }
  1164. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1165. uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
  1166. const MachineBasicBlock *Dst) const {
  1167. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1168. if (!BPI)
  1169. return 0;
  1170. const BasicBlock *SrcBB = Src->getBasicBlock();
  1171. const BasicBlock *DstBB = Dst->getBasicBlock();
  1172. return BPI->getEdgeWeight(SrcBB, DstBB);
  1173. }
  1174. void SelectionDAGBuilder::
  1175. addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
  1176. uint32_t Weight /* = 0 */) {
  1177. if (!Weight)
  1178. Weight = getEdgeWeight(Src, Dst);
  1179. Src->addSuccessor(Dst, Weight);
  1180. }
  1181. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1182. if (const Instruction *I = dyn_cast<Instruction>(V))
  1183. return I->getParent() == BB;
  1184. return true;
  1185. }
  1186. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1187. /// This function emits a branch and is used at the leaves of an OR or an
  1188. /// AND operator tree.
  1189. ///
  1190. void
  1191. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1192. MachineBasicBlock *TBB,
  1193. MachineBasicBlock *FBB,
  1194. MachineBasicBlock *CurBB,
  1195. MachineBasicBlock *SwitchBB,
  1196. uint32_t TWeight,
  1197. uint32_t FWeight) {
  1198. const BasicBlock *BB = CurBB->getBasicBlock();
  1199. // If the leaf of the tree is a comparison, merge the condition into
  1200. // the caseblock.
  1201. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1202. // The operands of the cmp have to be in this block. We don't know
  1203. // how to export them from some other block. If this is the first block
  1204. // of the sequence, no exporting is needed.
  1205. if (CurBB == SwitchBB ||
  1206. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1207. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1208. ISD::CondCode Condition;
  1209. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1210. Condition = getICmpCondCode(IC->getPredicate());
  1211. } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
  1212. Condition = getFCmpCondCode(FC->getPredicate());
  1213. if (TM.Options.NoNaNsFPMath)
  1214. Condition = getFCmpCodeWithoutNaN(Condition);
  1215. } else {
  1216. Condition = ISD::SETEQ; // silence warning.
  1217. llvm_unreachable("Unknown compare instruction");
  1218. }
  1219. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1220. TBB, FBB, CurBB, TWeight, FWeight);
  1221. SwitchCases.push_back(CB);
  1222. return;
  1223. }
  1224. }
  1225. // Create a CaseBlock record representing this branch.
  1226. CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1227. nullptr, TBB, FBB, CurBB, TWeight, FWeight);
  1228. SwitchCases.push_back(CB);
  1229. }
  1230. /// Scale down both weights to fit into uint32_t.
  1231. static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  1232. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  1233. uint32_t Scale = (NewMax / UINT32_MAX) + 1;
  1234. NewTrue = NewTrue / Scale;
  1235. NewFalse = NewFalse / Scale;
  1236. }
  1237. /// FindMergedConditions - If Cond is an expression like
  1238. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1239. MachineBasicBlock *TBB,
  1240. MachineBasicBlock *FBB,
  1241. MachineBasicBlock *CurBB,
  1242. MachineBasicBlock *SwitchBB,
  1243. unsigned Opc, uint32_t TWeight,
  1244. uint32_t FWeight) {
  1245. // If this node is not part of the or/and tree, emit it as a branch.
  1246. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1247. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1248. (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
  1249. BOp->getParent() != CurBB->getBasicBlock() ||
  1250. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1251. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1252. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1253. TWeight, FWeight);
  1254. return;
  1255. }
  1256. // Create TmpBB after CurBB.
  1257. MachineFunction::iterator BBI = CurBB;
  1258. MachineFunction &MF = DAG.getMachineFunction();
  1259. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1260. CurBB->getParent()->insert(++BBI, TmpBB);
  1261. if (Opc == Instruction::Or) {
  1262. // Codegen X | Y as:
  1263. // BB1:
  1264. // jmp_if_X TBB
  1265. // jmp TmpBB
  1266. // TmpBB:
  1267. // jmp_if_Y TBB
  1268. // jmp FBB
  1269. //
  1270. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1271. // The requirement is that
  1272. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1273. // = TrueProb for orignal BB.
  1274. // Assuming the orignal weights are A and B, one choice is to set BB1's
  1275. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  1276. // assumes that
  1277. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1278. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1279. // TmpBB, but the math is more complicated.
  1280. uint64_t NewTrueWeight = TWeight;
  1281. uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
  1282. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1283. // Emit the LHS condition.
  1284. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1285. NewTrueWeight, NewFalseWeight);
  1286. NewTrueWeight = TWeight;
  1287. NewFalseWeight = 2 * (uint64_t)FWeight;
  1288. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1289. // Emit the RHS condition into TmpBB.
  1290. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1291. NewTrueWeight, NewFalseWeight);
  1292. } else {
  1293. assert(Opc == Instruction::And && "Unknown merge op!");
  1294. // Codegen X & Y as:
  1295. // BB1:
  1296. // jmp_if_X TmpBB
  1297. // jmp FBB
  1298. // TmpBB:
  1299. // jmp_if_Y TBB
  1300. // jmp FBB
  1301. //
  1302. // This requires creation of TmpBB after CurBB.
  1303. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1304. // The requirement is that
  1305. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1306. // = FalseProb for orignal BB.
  1307. // Assuming the orignal weights are A and B, one choice is to set BB1's
  1308. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  1309. // assumes that
  1310. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  1311. uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
  1312. uint64_t NewFalseWeight = FWeight;
  1313. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1314. // Emit the LHS condition.
  1315. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1316. NewTrueWeight, NewFalseWeight);
  1317. NewTrueWeight = 2 * (uint64_t)TWeight;
  1318. NewFalseWeight = FWeight;
  1319. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1320. // Emit the RHS condition into TmpBB.
  1321. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1322. NewTrueWeight, NewFalseWeight);
  1323. }
  1324. }
  1325. /// If the set of cases should be emitted as a series of branches, return true.
  1326. /// If we should emit this as a bunch of and/or'd together conditions, return
  1327. /// false.
  1328. bool
  1329. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1330. if (Cases.size() != 2) return true;
  1331. // If this is two comparisons of the same values or'd or and'd together, they
  1332. // will get folded into a single comparison, so don't emit two blocks.
  1333. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1334. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1335. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1336. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1337. return false;
  1338. }
  1339. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1340. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1341. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1342. Cases[0].CC == Cases[1].CC &&
  1343. isa<Constant>(Cases[0].CmpRHS) &&
  1344. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1345. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1346. return false;
  1347. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1348. return false;
  1349. }
  1350. return true;
  1351. }
  1352. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1353. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1354. // Update machine-CFG edges.
  1355. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1356. // Figure out which block is immediately after the current one.
  1357. MachineBasicBlock *NextBlock = nullptr;
  1358. MachineFunction::iterator BBI = BrMBB;
  1359. if (++BBI != FuncInfo.MF->end())
  1360. NextBlock = BBI;
  1361. if (I.isUnconditional()) {
  1362. // Update machine-CFG edges.
  1363. BrMBB->addSuccessor(Succ0MBB);
  1364. // If this is not a fall-through branch or optimizations are switched off,
  1365. // emit the branch.
  1366. if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
  1367. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1368. MVT::Other, getControlRoot(),
  1369. DAG.getBasicBlock(Succ0MBB)));
  1370. return;
  1371. }
  1372. // If this condition is one of the special cases we handle, do special stuff
  1373. // now.
  1374. const Value *CondVal = I.getCondition();
  1375. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1376. // If this is a series of conditions that are or'd or and'd together, emit
  1377. // this as a sequence of branches instead of setcc's with and/or operations.
  1378. // As long as jumps are not expensive, this should improve performance.
  1379. // For example, instead of something like:
  1380. // cmp A, B
  1381. // C = seteq
  1382. // cmp D, E
  1383. // F = setle
  1384. // or C, F
  1385. // jnz foo
  1386. // Emit:
  1387. // cmp A, B
  1388. // je foo
  1389. // cmp D, E
  1390. // jle foo
  1391. //
  1392. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1393. if (!TM.getSubtargetImpl()->getTargetLowering()->isJumpExpensive() &&
  1394. BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
  1395. BOp->getOpcode() == Instruction::Or)) {
  1396. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1397. BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
  1398. getEdgeWeight(BrMBB, Succ1MBB));
  1399. // If the compares in later blocks need to use values not currently
  1400. // exported from this block, export them now. This block should always
  1401. // be the first entry.
  1402. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1403. // Allow some cases to be rejected.
  1404. if (ShouldEmitAsBranches(SwitchCases)) {
  1405. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1406. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1407. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1408. }
  1409. // Emit the branch for this block.
  1410. visitSwitchCase(SwitchCases[0], BrMBB);
  1411. SwitchCases.erase(SwitchCases.begin());
  1412. return;
  1413. }
  1414. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1415. // SwitchCases.
  1416. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1417. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1418. SwitchCases.clear();
  1419. }
  1420. }
  1421. // Create a CaseBlock record representing this branch.
  1422. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1423. nullptr, Succ0MBB, Succ1MBB, BrMBB);
  1424. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1425. // cond branch.
  1426. visitSwitchCase(CB, BrMBB);
  1427. }
  1428. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1429. /// the binary search tree resulting from lowering a switch instruction.
  1430. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1431. MachineBasicBlock *SwitchBB) {
  1432. SDValue Cond;
  1433. SDValue CondLHS = getValue(CB.CmpLHS);
  1434. SDLoc dl = getCurSDLoc();
  1435. // Build the setcc now.
  1436. if (!CB.CmpMHS) {
  1437. // Fold "(X == true)" to X and "(X == false)" to !X to
  1438. // handle common cases produced by branch lowering.
  1439. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1440. CB.CC == ISD::SETEQ)
  1441. Cond = CondLHS;
  1442. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1443. CB.CC == ISD::SETEQ) {
  1444. SDValue True = DAG.getConstant(1, CondLHS.getValueType());
  1445. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1446. } else
  1447. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1448. } else {
  1449. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1450. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1451. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1452. SDValue CmpOp = getValue(CB.CmpMHS);
  1453. EVT VT = CmpOp.getValueType();
  1454. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1455. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
  1456. ISD::SETLE);
  1457. } else {
  1458. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1459. VT, CmpOp, DAG.getConstant(Low, VT));
  1460. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1461. DAG.getConstant(High-Low, VT), ISD::SETULE);
  1462. }
  1463. }
  1464. // Update successor info
  1465. addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
  1466. // TrueBB and FalseBB are always different unless the incoming IR is
  1467. // degenerate. This only happens when running llc on weird IR.
  1468. if (CB.TrueBB != CB.FalseBB)
  1469. addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
  1470. // Set NextBlock to be the MBB immediately after the current one, if any.
  1471. // This is used to avoid emitting unnecessary branches to the next block.
  1472. MachineBasicBlock *NextBlock = nullptr;
  1473. MachineFunction::iterator BBI = SwitchBB;
  1474. if (++BBI != FuncInfo.MF->end())
  1475. NextBlock = BBI;
  1476. // If the lhs block is the next block, invert the condition so that we can
  1477. // fall through to the lhs instead of the rhs block.
  1478. if (CB.TrueBB == NextBlock) {
  1479. std::swap(CB.TrueBB, CB.FalseBB);
  1480. SDValue True = DAG.getConstant(1, Cond.getValueType());
  1481. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1482. }
  1483. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1484. MVT::Other, getControlRoot(), Cond,
  1485. DAG.getBasicBlock(CB.TrueBB));
  1486. // Insert the false branch. Do this even if it's a fall through branch,
  1487. // this makes it easier to do DAG optimizations which require inverting
  1488. // the branch condition.
  1489. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1490. DAG.getBasicBlock(CB.FalseBB));
  1491. DAG.setRoot(BrCond);
  1492. }
  1493. /// visitJumpTable - Emit JumpTable node in the current MBB
  1494. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1495. // Emit the code for the jump table
  1496. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1497. EVT PTy = TM.getSubtargetImpl()->getTargetLowering()->getPointerTy();
  1498. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1499. JT.Reg, PTy);
  1500. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1501. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  1502. MVT::Other, Index.getValue(1),
  1503. Table, Index);
  1504. DAG.setRoot(BrJumpTable);
  1505. }
  1506. /// visitJumpTableHeader - This function emits necessary code to produce index
  1507. /// in the JumpTable from switch case.
  1508. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1509. JumpTableHeader &JTH,
  1510. MachineBasicBlock *SwitchBB) {
  1511. // Subtract the lowest switch case value from the value being switched on and
  1512. // conditional branch to default mbb if the result is greater than the
  1513. // difference between smallest and largest cases.
  1514. SDValue SwitchOp = getValue(JTH.SValue);
  1515. EVT VT = SwitchOp.getValueType();
  1516. SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
  1517. DAG.getConstant(JTH.First, VT));
  1518. // The SDNode we just created, which holds the value being switched on minus
  1519. // the smallest case value, needs to be copied to a virtual register so it
  1520. // can be used as an index into the jump table in a subsequent basic block.
  1521. // This value may be smaller or larger than the target's pointer type, and
  1522. // therefore require extension or truncating.
  1523. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  1524. SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
  1525. unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
  1526. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
  1527. JumpTableReg, SwitchOp);
  1528. JT.Reg = JumpTableReg;
  1529. // Emit the range check for the jump table, and branch to the default block
  1530. // for the switch statement if the value being switched on exceeds the largest
  1531. // case in the switch.
  1532. SDValue CMP = DAG.getSetCC(getCurSDLoc(),
  1533. TLI->getSetCCResultType(*DAG.getContext(),
  1534. Sub.getValueType()),
  1535. Sub,
  1536. DAG.getConstant(JTH.Last - JTH.First,VT),
  1537. ISD::SETUGT);
  1538. // Set NextBlock to be the MBB immediately after the current one, if any.
  1539. // This is used to avoid emitting unnecessary branches to the next block.
  1540. MachineBasicBlock *NextBlock = nullptr;
  1541. MachineFunction::iterator BBI = SwitchBB;
  1542. if (++BBI != FuncInfo.MF->end())
  1543. NextBlock = BBI;
  1544. SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1545. MVT::Other, CopyTo, CMP,
  1546. DAG.getBasicBlock(JT.Default));
  1547. if (JT.MBB != NextBlock)
  1548. BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
  1549. DAG.getBasicBlock(JT.MBB));
  1550. DAG.setRoot(BrCond);
  1551. }
  1552. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  1553. /// tail spliced into a stack protector check success bb.
  1554. ///
  1555. /// For a high level explanation of how this fits into the stack protector
  1556. /// generation see the comment on the declaration of class
  1557. /// StackProtectorDescriptor.
  1558. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  1559. MachineBasicBlock *ParentBB) {
  1560. // First create the loads to the guard/stack slot for the comparison.
  1561. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  1562. EVT PtrTy = TLI->getPointerTy();
  1563. MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
  1564. int FI = MFI->getStackProtectorIndex();
  1565. const Value *IRGuard = SPD.getGuard();
  1566. SDValue GuardPtr = getValue(IRGuard);
  1567. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  1568. unsigned Align =
  1569. TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
  1570. SDValue Guard;
  1571. // If useLoadStackGuardNode returns true, retrieve the guard value from
  1572. // the virtual register holding the value. Otherwise, emit a volatile load
  1573. // to retrieve the stack guard value.
  1574. if (TLI->useLoadStackGuardNode())
  1575. Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1576. SPD.getGuardReg(), PtrTy);
  1577. else
  1578. Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
  1579. GuardPtr, MachinePointerInfo(IRGuard, 0),
  1580. true, false, false, Align);
  1581. SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
  1582. StackSlotPtr,
  1583. MachinePointerInfo::getFixedStack(FI),
  1584. true, false, false, Align);
  1585. // Perform the comparison via a subtract/getsetcc.
  1586. EVT VT = Guard.getValueType();
  1587. SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
  1588. SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
  1589. TLI->getSetCCResultType(*DAG.getContext(),
  1590. Sub.getValueType()),
  1591. Sub, DAG.getConstant(0, VT),
  1592. ISD::SETNE);
  1593. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  1594. // branch to failure MBB.
  1595. SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1596. MVT::Other, StackSlot.getOperand(0),
  1597. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  1598. // Otherwise branch to success MBB.
  1599. SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
  1600. MVT::Other, BrCond,
  1601. DAG.getBasicBlock(SPD.getSuccessMBB()));
  1602. DAG.setRoot(Br);
  1603. }
  1604. /// Codegen the failure basic block for a stack protector check.
  1605. ///
  1606. /// A failure stack protector machine basic block consists simply of a call to
  1607. /// __stack_chk_fail().
  1608. ///
  1609. /// For a high level explanation of how this fits into the stack protector
  1610. /// generation see the comment on the declaration of class
  1611. /// StackProtectorDescriptor.
  1612. void
  1613. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  1614. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  1615. SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
  1616. MVT::isVoid, nullptr, 0, false,
  1617. getCurSDLoc(), false, false).second;
  1618. DAG.setRoot(Chain);
  1619. }
  1620. /// visitBitTestHeader - This function emits necessary code to produce value
  1621. /// suitable for "bit tests"
  1622. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  1623. MachineBasicBlock *SwitchBB) {
  1624. // Subtract the minimum value
  1625. SDValue SwitchOp = getValue(B.SValue);
  1626. EVT VT = SwitchOp.getValueType();
  1627. SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
  1628. DAG.getConstant(B.First, VT));
  1629. // Check range
  1630. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  1631. SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
  1632. TLI->getSetCCResultType(*DAG.getContext(),
  1633. Sub.getValueType()),
  1634. Sub, DAG.getConstant(B.Range, VT),
  1635. ISD::SETUGT);
  1636. // Determine the type of the test operands.
  1637. bool UsePtrType = false;
  1638. if (!TLI->isTypeLegal(VT))
  1639. UsePtrType = true;
  1640. else {
  1641. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  1642. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  1643. // Switch table case range are encoded into series of masks.
  1644. // Just use pointer type, it's guaranteed to fit.
  1645. UsePtrType = true;
  1646. break;
  1647. }
  1648. }
  1649. if (UsePtrType) {
  1650. VT = TLI->getPointerTy();
  1651. Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
  1652. }
  1653. B.RegVT = VT.getSimpleVT();
  1654. B.Reg = FuncInfo.CreateReg(B.RegVT);
  1655. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
  1656. B.Reg, Sub);
  1657. // Set NextBlock to be the MBB immediately after the current one, if any.
  1658. // This is used to avoid emitting unnecessary branches to the next block.
  1659. MachineBasicBlock *NextBlock = nullptr;
  1660. MachineFunction::iterator BBI = SwitchBB;
  1661. if (++BBI != FuncInfo.MF->end())
  1662. NextBlock = BBI;
  1663. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1664. addSuccessorWithWeight(SwitchBB, B.Default);
  1665. addSuccessorWithWeight(SwitchBB, MBB);
  1666. SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1667. MVT::Other, CopyTo, RangeCmp,
  1668. DAG.getBasicBlock(B.Default));
  1669. if (MBB != NextBlock)
  1670. BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
  1671. DAG.getBasicBlock(MBB));
  1672. DAG.setRoot(BrRange);
  1673. }
  1674. /// visitBitTestCase - this function produces one "bit test"
  1675. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  1676. MachineBasicBlock* NextMBB,
  1677. uint32_t BranchWeightToNext,
  1678. unsigned Reg,
  1679. BitTestCase &B,
  1680. MachineBasicBlock *SwitchBB) {
  1681. MVT VT = BB.RegVT;
  1682. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1683. Reg, VT);
  1684. SDValue Cmp;
  1685. unsigned PopCount = CountPopulation_64(B.Mask);
  1686. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  1687. if (PopCount == 1) {
  1688. // Testing for a single bit; just compare the shift count with what it
  1689. // would need to be to shift a 1 bit in that position.
  1690. Cmp = DAG.getSetCC(getCurSDLoc(),
  1691. TLI->getSetCCResultType(*DAG.getContext(), VT),
  1692. ShiftOp,
  1693. DAG.getConstant(countTrailingZeros(B.Mask), VT),
  1694. ISD::SETEQ);
  1695. } else if (PopCount == BB.Range) {
  1696. // There is only one zero bit in the range, test for it directly.
  1697. Cmp = DAG.getSetCC(getCurSDLoc(),
  1698. TLI->getSetCCResultType(*DAG.getContext(), VT),
  1699. ShiftOp,
  1700. DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
  1701. ISD::SETNE);
  1702. } else {
  1703. // Make desired shift
  1704. SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
  1705. DAG.getConstant(1, VT), ShiftOp);
  1706. // Emit bit tests and jumps
  1707. SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
  1708. VT, SwitchVal, DAG.getConstant(B.Mask, VT));
  1709. Cmp = DAG.getSetCC(getCurSDLoc(),
  1710. TLI->getSetCCResultType(*DAG.getContext(), VT),
  1711. AndOp, DAG.getConstant(0, VT),
  1712. ISD::SETNE);
  1713. }
  1714. // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
  1715. addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
  1716. // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
  1717. addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
  1718. SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1719. MVT::Other, getControlRoot(),
  1720. Cmp, DAG.getBasicBlock(B.TargetBB));
  1721. // Set NextBlock to be the MBB immediately after the current one, if any.
  1722. // This is used to avoid emitting unnecessary branches to the next block.
  1723. MachineBasicBlock *NextBlock = nullptr;
  1724. MachineFunction::iterator BBI = SwitchBB;
  1725. if (++BBI != FuncInfo.MF->end())
  1726. NextBlock = BBI;
  1727. if (NextMBB != NextBlock)
  1728. BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
  1729. DAG.getBasicBlock(NextMBB));
  1730. DAG.setRoot(BrAnd);
  1731. }
  1732. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  1733. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  1734. // Retrieve successors.
  1735. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  1736. MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
  1737. const Value *Callee(I.getCalledValue());
  1738. const Function *Fn = dyn_cast<Function>(Callee);
  1739. if (isa<InlineAsm>(Callee))
  1740. visitInlineAsm(&I);
  1741. else if (Fn && Fn->isIntrinsic()) {
  1742. assert(Fn->getIntrinsicID() == Intrinsic::donothing);
  1743. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  1744. } else
  1745. LowerCallTo(&I, getValue(Callee), false, LandingPad);
  1746. // If the value of the invoke is used outside of its defining block, make it
  1747. // available as a virtual register.
  1748. CopyToExportRegsIfNeeded(&I);
  1749. // Update successor info
  1750. addSuccessorWithWeight(InvokeMBB, Return);
  1751. addSuccessorWithWeight(InvokeMBB, LandingPad);
  1752. // Drop into normal successor.
  1753. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1754. MVT::Other, getControlRoot(),
  1755. DAG.getBasicBlock(Return)));
  1756. }
  1757. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  1758. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  1759. }
  1760. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  1761. assert(FuncInfo.MBB->isLandingPad() &&
  1762. "Call to landingpad not in landing pad!");
  1763. MachineBasicBlock *MBB = FuncInfo.MBB;
  1764. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  1765. AddLandingPadInfo(LP, MMI, MBB);
  1766. // If there aren't registers to copy the values into (e.g., during SjLj
  1767. // exceptions), then don't bother to create these DAG nodes.
  1768. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  1769. if (TLI->getExceptionPointerRegister() == 0 &&
  1770. TLI->getExceptionSelectorRegister() == 0)
  1771. return;
  1772. SmallVector<EVT, 2> ValueVTs;
  1773. ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
  1774. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  1775. // Get the two live-in registers as SDValues. The physregs have already been
  1776. // copied into virtual registers.
  1777. SDValue Ops[2];
  1778. Ops[0] = DAG.getZExtOrTrunc(
  1779. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1780. FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
  1781. getCurSDLoc(), ValueVTs[0]);
  1782. Ops[1] = DAG.getZExtOrTrunc(
  1783. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1784. FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
  1785. getCurSDLoc(), ValueVTs[1]);
  1786. // Merge into one.
  1787. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  1788. DAG.getVTList(ValueVTs), Ops);
  1789. setValue(&LP, Res);
  1790. }
  1791. /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
  1792. /// small case ranges).
  1793. bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
  1794. CaseRecVector& WorkList,
  1795. const Value* SV,
  1796. MachineBasicBlock *Default,
  1797. MachineBasicBlock *SwitchBB) {
  1798. // Size is the number of Cases represented by this range.
  1799. size_t Size = CR.Range.second - CR.Range.first;
  1800. if (Size > 3)
  1801. return false;
  1802. // Get the MachineFunction which holds the current MBB. This is used when
  1803. // inserting any additional MBBs necessary to represent the switch.
  1804. MachineFunction *CurMF = FuncInfo.MF;
  1805. // Figure out which block is immediately after the current one.
  1806. MachineBasicBlock *NextBlock = nullptr;
  1807. MachineFunction::iterator BBI = CR.CaseBB;
  1808. if (++BBI != FuncInfo.MF->end())
  1809. NextBlock = BBI;
  1810. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1811. // If any two of the cases has the same destination, and if one value
  1812. // is the same as the other, but has one bit unset that the other has set,
  1813. // use bit manipulation to do two compares at once. For example:
  1814. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  1815. // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
  1816. // TODO: Handle cases where CR.CaseBB != SwitchBB.
  1817. if (Size == 2 && CR.CaseBB == SwitchBB) {
  1818. Case &Small = *CR.Range.first;
  1819. Case &Big = *(CR.Range.second-1);
  1820. if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
  1821. const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
  1822. const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
  1823. // Check that there is only one bit different.
  1824. if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
  1825. (SmallValue | BigValue) == BigValue) {
  1826. // Isolate the common bit.
  1827. APInt CommonBit = BigValue & ~SmallValue;
  1828. assert((SmallValue | CommonBit) == BigValue &&
  1829. CommonBit.countPopulation() == 1 && "Not a common bit?");
  1830. SDValue CondLHS = getValue(SV);
  1831. EVT VT = CondLHS.getValueType();
  1832. SDLoc DL = getCurSDLoc();
  1833. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  1834. DAG.getConstant(CommonBit, VT));
  1835. SDValue Cond = DAG.getSetCC(DL, MVT::i1,
  1836. Or, DAG.getConstant(BigValue, VT),
  1837. ISD::SETEQ);
  1838. // Update successor info.
  1839. // Both Small and Big will jump to Small.BB, so we sum up the weights.
  1840. addSuccessorWithWeight(SwitchBB, Small.BB,
  1841. Small.ExtraWeight + Big.ExtraWeight);
  1842. addSuccessorWithWeight(SwitchBB, Default,
  1843. // The default destination is the first successor in IR.
  1844. BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
  1845. // Insert the true branch.
  1846. SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
  1847. getControlRoot(), Cond,
  1848. DAG.getBasicBlock(Small.BB));
  1849. // Insert the false branch.
  1850. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  1851. DAG.getBasicBlock(Default));
  1852. DAG.setRoot(BrCond);
  1853. return true;
  1854. }
  1855. }
  1856. }
  1857. // Order cases by weight so the most likely case will be checked first.
  1858. uint32_t UnhandledWeights = 0;
  1859. if (BPI) {
  1860. for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
  1861. uint32_t IWeight = I->ExtraWeight;
  1862. UnhandledWeights += IWeight;
  1863. for (CaseItr J = CR.Range.first; J < I; ++J) {
  1864. uint32_t JWeight = J->ExtraWeight;
  1865. if (IWeight > JWeight)
  1866. std::swap(*I, *J);
  1867. }
  1868. }
  1869. }
  1870. // Rearrange the case blocks so that the last one falls through if possible.
  1871. Case &BackCase = *(CR.Range.second-1);
  1872. if (Size > 1 &&
  1873. NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
  1874. // The last case block won't fall through into 'NextBlock' if we emit the
  1875. // branches in this order. See if rearranging a case value would help.
  1876. // We start at the bottom as it's the case with the least weight.
  1877. for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
  1878. if (I->BB == NextBlock) {
  1879. std::swap(*I, BackCase);
  1880. break;
  1881. }
  1882. }
  1883. // Create a CaseBlock record representing a conditional branch to
  1884. // the Case's target mbb if the value being switched on SV is equal
  1885. // to C.
  1886. MachineBasicBlock *CurBlock = CR.CaseBB;
  1887. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  1888. MachineBasicBlock *FallThrough;
  1889. if (I != E-1) {
  1890. FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
  1891. CurMF->insert(BBI, FallThrough);
  1892. // Put SV in a virtual register to make it available from the new blocks.
  1893. ExportFromCurrentBlock(SV);
  1894. } else {
  1895. // If the last case doesn't match, go to the default block.
  1896. FallThrough = Default;
  1897. }
  1898. const Value *RHS, *LHS, *MHS;
  1899. ISD::CondCode CC;
  1900. if (I->High == I->Low) {
  1901. // This is just small small case range :) containing exactly 1 case
  1902. CC = ISD::SETEQ;
  1903. LHS = SV; RHS = I->High; MHS = nullptr;
  1904. } else {
  1905. CC = ISD::SETLE;
  1906. LHS = I->Low; MHS = SV; RHS = I->High;
  1907. }
  1908. // The false weight should be sum of all un-handled cases.
  1909. UnhandledWeights -= I->ExtraWeight;
  1910. CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
  1911. /* me */ CurBlock,
  1912. /* trueweight */ I->ExtraWeight,
  1913. /* falseweight */ UnhandledWeights);
  1914. // If emitting the first comparison, just call visitSwitchCase to emit the
  1915. // code into the current block. Otherwise, push the CaseBlock onto the
  1916. // vector to be later processed by SDISel, and insert the node's MBB
  1917. // before the next MBB.
  1918. if (CurBlock == SwitchBB)
  1919. visitSwitchCase(CB, SwitchBB);
  1920. else
  1921. SwitchCases.push_back(CB);
  1922. CurBlock = FallThrough;
  1923. }
  1924. return true;
  1925. }
  1926. static inline bool areJTsAllowed(const TargetLowering &TLI) {
  1927. return TLI.supportJumpTables() &&
  1928. (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  1929. TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
  1930. }
  1931. static APInt ComputeRange(const APInt &First, const APInt &Last) {
  1932. uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
  1933. APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
  1934. return (LastExt - FirstExt + 1ULL);
  1935. }
  1936. /// handleJTSwitchCase - Emit jumptable for current switch case range
  1937. bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
  1938. CaseRecVector &WorkList,
  1939. const Value *SV,
  1940. MachineBasicBlock *Default,
  1941. MachineBasicBlock *SwitchBB) {
  1942. Case& FrontCase = *CR.Range.first;
  1943. Case& BackCase = *(CR.Range.second-1);
  1944. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  1945. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  1946. APInt TSize(First.getBitWidth(), 0);
  1947. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
  1948. TSize += I->size();
  1949. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  1950. if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
  1951. return false;
  1952. APInt Range = ComputeRange(First, Last);
  1953. // The density is TSize / Range. Require at least 40%.
  1954. // It should not be possible for IntTSize to saturate for sane code, but make
  1955. // sure we handle Range saturation correctly.
  1956. uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
  1957. uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
  1958. if (IntTSize * 10 < IntRange * 4)
  1959. return false;
  1960. DEBUG(dbgs() << "Lowering jump table\n"
  1961. << "First entry: " << First << ". Last entry: " << Last << '\n'
  1962. << "Range: " << Range << ". Size: " << TSize << ".\n\n");
  1963. // Get the MachineFunction which holds the current MBB. This is used when
  1964. // inserting any additional MBBs necessary to represent the switch.
  1965. MachineFunction *CurMF = FuncInfo.MF;
  1966. // Figure out which block is immediately after the current one.
  1967. MachineFunction::iterator BBI = CR.CaseBB;
  1968. ++BBI;
  1969. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1970. // Create a new basic block to hold the code for loading the address
  1971. // of the jump table, and jumping to it. Update successor information;
  1972. // we will either branch to the default case for the switch, or the jump
  1973. // table.
  1974. MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1975. CurMF->insert(BBI, JumpTableBB);
  1976. addSuccessorWithWeight(CR.CaseBB, Default);
  1977. addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
  1978. // Build a vector of destination BBs, corresponding to each target
  1979. // of the jump table. If the value of the jump table slot corresponds to
  1980. // a case statement, push the case's BB onto the vector, otherwise, push
  1981. // the default BB.
  1982. std::vector<MachineBasicBlock*> DestBBs;
  1983. APInt TEI = First;
  1984. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
  1985. const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
  1986. const APInt &High = cast<ConstantInt>(I->High)->getValue();
  1987. if (Low.sle(TEI) && TEI.sle(High)) {
  1988. DestBBs.push_back(I->BB);
  1989. if (TEI==High)
  1990. ++I;
  1991. } else {
  1992. DestBBs.push_back(Default);
  1993. }
  1994. }
  1995. // Calculate weight for each unique destination in CR.
  1996. DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
  1997. if (FuncInfo.BPI)
  1998. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  1999. DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
  2000. DestWeights.find(I->BB);
  2001. if (Itr != DestWeights.end())
  2002. Itr->second += I->ExtraWeight;
  2003. else
  2004. DestWeights[I->BB] = I->ExtraWeight;
  2005. }
  2006. // Update successor info. Add one edge to each unique successor.
  2007. BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
  2008. for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
  2009. E = DestBBs.end(); I != E; ++I) {
  2010. if (!SuccsHandled[(*I)->getNumber()]) {
  2011. SuccsHandled[(*I)->getNumber()] = true;
  2012. DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
  2013. DestWeights.find(*I);
  2014. addSuccessorWithWeight(JumpTableBB, *I,
  2015. Itr != DestWeights.end() ? Itr->second : 0);
  2016. }
  2017. }
  2018. // Create a jump table index for this jump table.
  2019. unsigned JTEncoding = TLI->getJumpTableEncoding();
  2020. unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
  2021. ->createJumpTableIndex(DestBBs);
  2022. // Set the jump table information so that we can codegen it as a second
  2023. // MachineBasicBlock
  2024. JumpTable JT(-1U, JTI, JumpTableBB, Default);
  2025. JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
  2026. if (CR.CaseBB == SwitchBB)
  2027. visitJumpTableHeader(JT, JTH, SwitchBB);
  2028. JTCases.push_back(JumpTableBlock(JTH, JT));
  2029. return true;
  2030. }
  2031. /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
  2032. /// 2 subtrees.
  2033. bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
  2034. CaseRecVector& WorkList,
  2035. const Value* SV,
  2036. MachineBasicBlock* Default,
  2037. MachineBasicBlock* SwitchBB) {
  2038. // Get the MachineFunction which holds the current MBB. This is used when
  2039. // inserting any additional MBBs necessary to represent the switch.
  2040. MachineFunction *CurMF = FuncInfo.MF;
  2041. // Figure out which block is immediately after the current one.
  2042. MachineFunction::iterator BBI = CR.CaseBB;
  2043. ++BBI;
  2044. Case& FrontCase = *CR.Range.first;
  2045. Case& BackCase = *(CR.Range.second-1);
  2046. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  2047. // Size is the number of Cases represented by this range.
  2048. unsigned Size = CR.Range.second - CR.Range.first;
  2049. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  2050. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  2051. double FMetric = 0;
  2052. CaseItr Pivot = CR.Range.first + Size/2;
  2053. // Select optimal pivot, maximizing sum density of LHS and RHS. This will
  2054. // (heuristically) allow us to emit JumpTable's later.
  2055. APInt TSize(First.getBitWidth(), 0);
  2056. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  2057. I!=E; ++I)
  2058. TSize += I->size();
  2059. APInt LSize = FrontCase.size();
  2060. APInt RSize = TSize-LSize;
  2061. DEBUG(dbgs() << "Selecting best pivot: \n"
  2062. << "First: " << First << ", Last: " << Last <<'\n'
  2063. << "LSize: " << LSize << ", RSize: " << RSize << '\n');
  2064. for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
  2065. J!=E; ++I, ++J) {
  2066. const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
  2067. const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
  2068. APInt Range = ComputeRange(LEnd, RBegin);
  2069. assert((Range - 2ULL).isNonNegative() &&
  2070. "Invalid case distance");
  2071. // Use volatile double here to avoid excess precision issues on some hosts,
  2072. // e.g. that use 80-bit X87 registers.
  2073. volatile double LDensity =
  2074. (double)LSize.roundToDouble() /
  2075. (LEnd - First + 1ULL).roundToDouble();
  2076. volatile double RDensity =
  2077. (double)RSize.roundToDouble() /
  2078. (Last - RBegin + 1ULL).roundToDouble();
  2079. volatile double Metric = Range.logBase2()*(LDensity+RDensity);
  2080. // Should always split in some non-trivial place
  2081. DEBUG(dbgs() <<"=>Step\n"
  2082. << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
  2083. << "LDensity: " << LDensity
  2084. << ", RDensity: " << RDensity << '\n'
  2085. << "Metric: " << Metric << '\n');
  2086. if (FMetric < Metric) {
  2087. Pivot = J;
  2088. FMetric = Metric;
  2089. DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
  2090. }
  2091. LSize += J->size();
  2092. RSize -= J->size();
  2093. }
  2094. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  2095. if (areJTsAllowed(*TLI)) {
  2096. // If our case is dense we *really* should handle it earlier!
  2097. assert((FMetric > 0) && "Should handle dense range earlier!");
  2098. } else {
  2099. Pivot = CR.Range.first + Size/2;
  2100. }
  2101. CaseRange LHSR(CR.Range.first, Pivot);
  2102. CaseRange RHSR(Pivot, CR.Range.second);
  2103. const Constant *C = Pivot->Low;
  2104. MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
  2105. // We know that we branch to the LHS if the Value being switched on is
  2106. // less than the Pivot value, C. We use this to optimize our binary
  2107. // tree a bit, by recognizing that if SV is greater than or equal to the
  2108. // LHS's Case Value, and that Case Value is exactly one less than the
  2109. // Pivot's Value, then we can branch directly to the LHS's Target,
  2110. // rather than creating a leaf node for it.
  2111. if ((LHSR.second - LHSR.first) == 1 &&
  2112. LHSR.first->High == CR.GE &&
  2113. cast<ConstantInt>(C)->getValue() ==
  2114. (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
  2115. TrueBB = LHSR.first->BB;
  2116. } else {
  2117. TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  2118. CurMF->insert(BBI, TrueBB);
  2119. WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
  2120. // Put SV in a virtual register to make it available from the new blocks.
  2121. ExportFromCurrentBlock(SV);
  2122. }
  2123. // Similar to the optimization above, if the Value being switched on is
  2124. // known to be less than the Constant CR.LT, and the current Case Value
  2125. // is CR.LT - 1, then we can branch directly to the target block for
  2126. // the current Case Value, rather than emitting a RHS leaf node for it.
  2127. if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
  2128. cast<ConstantInt>(RHSR.first->Low)->getValue() ==
  2129. (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
  2130. FalseBB = RHSR.first->BB;
  2131. } else {
  2132. FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  2133. CurMF->insert(BBI, FalseBB);
  2134. WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
  2135. // Put SV in a virtual register to make it available from the new blocks.
  2136. ExportFromCurrentBlock(SV);
  2137. }
  2138. // Create a CaseBlock record representing a conditional branch to
  2139. // the LHS node if the value being switched on SV is less than C.
  2140. // Otherwise, branch to LHS.
  2141. CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
  2142. if (CR.CaseBB == SwitchBB)
  2143. visitSwitchCase(CB, SwitchBB);
  2144. else
  2145. SwitchCases.push_back(CB);
  2146. return true;
  2147. }
  2148. /// handleBitTestsSwitchCase - if current case range has few destination and
  2149. /// range span less, than machine word bitwidth, encode case range into series
  2150. /// of masks and emit bit tests with these masks.
  2151. bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
  2152. CaseRecVector& WorkList,
  2153. const Value* SV,
  2154. MachineBasicBlock* Default,
  2155. MachineBasicBlock* SwitchBB) {
  2156. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  2157. EVT PTy = TLI->getPointerTy();
  2158. unsigned IntPtrBits = PTy.getSizeInBits();
  2159. Case& FrontCase = *CR.Range.first;
  2160. Case& BackCase = *(CR.Range.second-1);
  2161. // Get the MachineFunction which holds the current MBB. This is used when
  2162. // inserting any additional MBBs necessary to represent the switch.
  2163. MachineFunction *CurMF = FuncInfo.MF;
  2164. // If target does not have legal shift left, do not emit bit tests at all.
  2165. if (!TLI->isOperationLegal(ISD::SHL, PTy))
  2166. return false;
  2167. size_t numCmps = 0;
  2168. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  2169. I!=E; ++I) {
  2170. // Single case counts one, case range - two.
  2171. numCmps += (I->Low == I->High ? 1 : 2);
  2172. }
  2173. // Count unique destinations
  2174. SmallSet<MachineBasicBlock*, 4> Dests;
  2175. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  2176. Dests.insert(I->BB);
  2177. if (Dests.size() > 3)
  2178. // Don't bother the code below, if there are too much unique destinations
  2179. return false;
  2180. }
  2181. DEBUG(dbgs() << "Total number of unique destinations: "
  2182. << Dests.size() << '\n'
  2183. << "Total number of comparisons: " << numCmps << '\n');
  2184. // Compute span of values.
  2185. const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
  2186. const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
  2187. APInt cmpRange = maxValue - minValue;
  2188. DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
  2189. << "Low bound: " << minValue << '\n'
  2190. << "High bound: " << maxValue << '\n');
  2191. if (cmpRange.uge(IntPtrBits) ||
  2192. (!(Dests.size() == 1 && numCmps >= 3) &&
  2193. !(Dests.size() == 2 && numCmps >= 5) &&
  2194. !(Dests.size() >= 3 && numCmps >= 6)))
  2195. return false;
  2196. DEBUG(dbgs() << "Emitting bit tests\n");
  2197. APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
  2198. // Optimize the case where all the case values fit in a
  2199. // word without having to subtract minValue. In this case,
  2200. // we can optimize away the subtraction.
  2201. if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
  2202. cmpRange = maxValue;
  2203. } else {
  2204. lowBound = minValue;
  2205. }
  2206. CaseBitsVector CasesBits;
  2207. unsigned i, count = 0;
  2208. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  2209. MachineBasicBlock* Dest = I->BB;
  2210. for (i = 0; i < count; ++i)
  2211. if (Dest == CasesBits[i].BB)
  2212. break;
  2213. if (i == count) {
  2214. assert((count < 3) && "Too much destinations to test!");
  2215. CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
  2216. count++;
  2217. }
  2218. const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
  2219. const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
  2220. uint64_t lo = (lowValue - lowBound).getZExtValue();
  2221. uint64_t hi = (highValue - lowBound).getZExtValue();
  2222. CasesBits[i].ExtraWeight += I->ExtraWeight;
  2223. for (uint64_t j = lo; j <= hi; j++) {
  2224. CasesBits[i].Mask |= 1ULL << j;
  2225. CasesBits[i].Bits++;
  2226. }
  2227. }
  2228. std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
  2229. BitTestInfo BTC;
  2230. // Figure out which block is immediately after the current one.
  2231. MachineFunction::iterator BBI = CR.CaseBB;
  2232. ++BBI;
  2233. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  2234. DEBUG(dbgs() << "Cases:\n");
  2235. for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
  2236. DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
  2237. << ", Bits: " << CasesBits[i].Bits
  2238. << ", BB: " << CasesBits[i].BB << '\n');
  2239. MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  2240. CurMF->insert(BBI, CaseBB);
  2241. BTC.push_back(BitTestCase(CasesBits[i].Mask,
  2242. CaseBB,
  2243. CasesBits[i].BB, CasesBits[i].ExtraWeight));
  2244. // Put SV in a virtual register to make it available from the new blocks.
  2245. ExportFromCurrentBlock(SV);
  2246. }
  2247. BitTestBlock BTB(lowBound, cmpRange, SV,
  2248. -1U, MVT::Other, (CR.CaseBB == SwitchBB),
  2249. CR.CaseBB, Default, BTC);
  2250. if (CR.CaseBB == SwitchBB)
  2251. visitBitTestHeader(BTB, SwitchBB);
  2252. BitTestCases.push_back(BTB);
  2253. return true;
  2254. }
  2255. /// Clusterify - Transform simple list of Cases into list of CaseRange's
  2256. size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
  2257. const SwitchInst& SI) {
  2258. size_t numCmps = 0;
  2259. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2260. // Start with "simple" cases
  2261. for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
  2262. i != e; ++i) {
  2263. const BasicBlock *SuccBB = i.getCaseSuccessor();
  2264. MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
  2265. uint32_t ExtraWeight =
  2266. BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
  2267. Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
  2268. SMBB, ExtraWeight));
  2269. }
  2270. std::sort(Cases.begin(), Cases.end(), CaseCmp());
  2271. // Merge case into clusters
  2272. if (Cases.size() >= 2)
  2273. // Must recompute end() each iteration because it may be
  2274. // invalidated by erase if we hold on to it
  2275. for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
  2276. J != Cases.end(); ) {
  2277. const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
  2278. const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
  2279. MachineBasicBlock* nextBB = J->BB;
  2280. MachineBasicBlock* currentBB = I->BB;
  2281. // If the two neighboring cases go to the same destination, merge them
  2282. // into a single case.
  2283. if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
  2284. I->High = J->High;
  2285. I->ExtraWeight += J->ExtraWeight;
  2286. J = Cases.erase(J);
  2287. } else {
  2288. I = J++;
  2289. }
  2290. }
  2291. for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
  2292. if (I->Low != I->High)
  2293. // A range counts double, since it requires two compares.
  2294. ++numCmps;
  2295. }
  2296. return numCmps;
  2297. }
  2298. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2299. MachineBasicBlock *Last) {
  2300. // Update JTCases.
  2301. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2302. if (JTCases[i].first.HeaderBB == First)
  2303. JTCases[i].first.HeaderBB = Last;
  2304. // Update BitTestCases.
  2305. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2306. if (BitTestCases[i].Parent == First)
  2307. BitTestCases[i].Parent = Last;
  2308. }
  2309. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  2310. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  2311. // Figure out which block is immediately after the current one.
  2312. MachineBasicBlock *NextBlock = nullptr;
  2313. MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
  2314. // If there is only the default destination, branch to it if it is not the
  2315. // next basic block. Otherwise, just fall through.
  2316. if (!SI.getNumCases()) {
  2317. // Update machine-CFG edges.
  2318. // If this is not a fall-through branch, emit the branch.
  2319. SwitchMBB->addSuccessor(Default);
  2320. if (Default != NextBlock)
  2321. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2322. MVT::Other, getControlRoot(),
  2323. DAG.getBasicBlock(Default)));
  2324. return;
  2325. }
  2326. // If there are any non-default case statements, create a vector of Cases
  2327. // representing each one, and sort the vector so that we can efficiently
  2328. // create a binary search tree from them.
  2329. CaseVector Cases;
  2330. size_t numCmps = Clusterify(Cases, SI);
  2331. DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
  2332. << ". Total compares: " << numCmps << '\n');
  2333. (void)numCmps;
  2334. // Get the Value to be switched on and default basic blocks, which will be
  2335. // inserted into CaseBlock records, representing basic blocks in the binary
  2336. // search tree.
  2337. const Value *SV = SI.getCondition();
  2338. // Push the initial CaseRec onto the worklist
  2339. CaseRecVector WorkList;
  2340. WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
  2341. CaseRange(Cases.begin(),Cases.end())));
  2342. while (!WorkList.empty()) {
  2343. // Grab a record representing a case range to process off the worklist
  2344. CaseRec CR = WorkList.back();
  2345. WorkList.pop_back();
  2346. if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
  2347. continue;
  2348. // If the range has few cases (two or less) emit a series of specific
  2349. // tests.
  2350. if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
  2351. continue;
  2352. // If the switch has more than N blocks, and is at least 40% dense, and the
  2353. // target supports indirect branches, then emit a jump table rather than
  2354. // lowering the switch to a binary tree of conditional branches.
  2355. // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
  2356. if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
  2357. continue;
  2358. // Emit binary tree. We need to pick a pivot, and push left and right ranges
  2359. // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
  2360. handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
  2361. }
  2362. }
  2363. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2364. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2365. // Update machine-CFG edges with unique successors.
  2366. SmallSet<BasicBlock*, 32> Done;
  2367. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2368. BasicBlock *BB = I.getSuccessor(i);
  2369. bool Inserted = Done.insert(BB);
  2370. if (!Inserted)
  2371. continue;
  2372. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2373. addSuccessorWithWeight(IndirectBrMBB, Succ);
  2374. }
  2375. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2376. MVT::Other, getControlRoot(),
  2377. getValue(I.getAddress())));
  2378. }
  2379. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2380. if (DAG.getTarget().Options.TrapUnreachable)
  2381. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2382. }
  2383. void SelectionDAGBuilder::visitFSub(const User &I) {
  2384. // -0.0 - X --> fneg
  2385. Type *Ty = I.getType();
  2386. if (isa<Constant>(I.getOperand(0)) &&
  2387. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2388. SDValue Op2 = getValue(I.getOperand(1));
  2389. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2390. Op2.getValueType(), Op2));
  2391. return;
  2392. }
  2393. visitBinary(I, ISD::FSUB);
  2394. }
  2395. void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
  2396. SDValue Op1 = getValue(I.getOperand(0));
  2397. SDValue Op2 = getValue(I.getOperand(1));
  2398. bool nuw = false;
  2399. bool nsw = false;
  2400. bool exact = false;
  2401. if (const OverflowingBinaryOperator *OFBinOp =
  2402. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2403. nuw = OFBinOp->hasNoUnsignedWrap();
  2404. nsw = OFBinOp->hasNoSignedWrap();
  2405. }
  2406. if (const PossiblyExactOperator *ExactOp =
  2407. dyn_cast<const PossiblyExactOperator>(&I))
  2408. exact = ExactOp->isExact();
  2409. SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
  2410. Op1, Op2, nuw, nsw, exact);
  2411. setValue(&I, BinNodeValue);
  2412. }
  2413. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2414. SDValue Op1 = getValue(I.getOperand(0));
  2415. SDValue Op2 = getValue(I.getOperand(1));
  2416. EVT ShiftTy = TM.getSubtargetImpl()->getTargetLowering()->getShiftAmountTy(
  2417. Op2.getValueType());
  2418. // Coerce the shift amount to the right type if we can.
  2419. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2420. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2421. unsigned Op2Size = Op2.getValueType().getSizeInBits();
  2422. SDLoc DL = getCurSDLoc();
  2423. // If the operand is smaller than the shift count type, promote it.
  2424. if (ShiftSize > Op2Size)
  2425. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2426. // If the operand is larger than the shift count type but the shift
  2427. // count type has enough bits to represent any shift value, truncate
  2428. // it now. This is a common case and it exposes the truncate to
  2429. // optimization early.
  2430. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
  2431. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2432. // Otherwise we'll need to temporarily settle for some other convenient
  2433. // type. Type legalization will make adjustments once the shiftee is split.
  2434. else
  2435. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2436. }
  2437. bool nuw = false;
  2438. bool nsw = false;
  2439. bool exact = false;
  2440. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2441. if (const OverflowingBinaryOperator *OFBinOp =
  2442. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2443. nuw = OFBinOp->hasNoUnsignedWrap();
  2444. nsw = OFBinOp->hasNoSignedWrap();
  2445. }
  2446. if (const PossiblyExactOperator *ExactOp =
  2447. dyn_cast<const PossiblyExactOperator>(&I))
  2448. exact = ExactOp->isExact();
  2449. }
  2450. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2451. nuw, nsw, exact);
  2452. setValue(&I, Res);
  2453. }
  2454. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2455. SDValue Op1 = getValue(I.getOperand(0));
  2456. SDValue Op2 = getValue(I.getOperand(1));
  2457. // Turn exact SDivs into multiplications.
  2458. // FIXME: This should be in DAGCombiner, but it doesn't have access to the
  2459. // exact bit.
  2460. if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
  2461. !isa<ConstantSDNode>(Op1) &&
  2462. isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
  2463. setValue(&I, TM.getSubtargetImpl()->getTargetLowering()->BuildExactSDIV(
  2464. Op1, Op2, getCurSDLoc(), DAG));
  2465. else
  2466. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
  2467. Op1, Op2));
  2468. }
  2469. void SelectionDAGBuilder::visitICmp(const User &I) {
  2470. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2471. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2472. predicate = IC->getPredicate();
  2473. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2474. predicate = ICmpInst::Predicate(IC->getPredicate());
  2475. SDValue Op1 = getValue(I.getOperand(0));
  2476. SDValue Op2 = getValue(I.getOperand(1));
  2477. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2478. EVT DestVT =
  2479. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2480. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2481. }
  2482. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2483. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2484. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2485. predicate = FC->getPredicate();
  2486. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2487. predicate = FCmpInst::Predicate(FC->getPredicate());
  2488. SDValue Op1 = getValue(I.getOperand(0));
  2489. SDValue Op2 = getValue(I.getOperand(1));
  2490. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2491. if (TM.Options.NoNaNsFPMath)
  2492. Condition = getFCmpCodeWithoutNaN(Condition);
  2493. EVT DestVT =
  2494. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2495. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2496. }
  2497. void SelectionDAGBuilder::visitSelect(const User &I) {
  2498. SmallVector<EVT, 4> ValueVTs;
  2499. ComputeValueVTs(*TM.getSubtargetImpl()->getTargetLowering(), I.getType(),
  2500. ValueVTs);
  2501. unsigned NumValues = ValueVTs.size();
  2502. if (NumValues == 0) return;
  2503. SmallVector<SDValue, 4> Values(NumValues);
  2504. SDValue Cond = getValue(I.getOperand(0));
  2505. SDValue TrueVal = getValue(I.getOperand(1));
  2506. SDValue FalseVal = getValue(I.getOperand(2));
  2507. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2508. ISD::VSELECT : ISD::SELECT;
  2509. for (unsigned i = 0; i != NumValues; ++i)
  2510. Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
  2511. TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
  2512. Cond,
  2513. SDValue(TrueVal.getNode(),
  2514. TrueVal.getResNo() + i),
  2515. SDValue(FalseVal.getNode(),
  2516. FalseVal.getResNo() + i));
  2517. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2518. DAG.getVTList(ValueVTs), Values));
  2519. }
  2520. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2521. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2522. SDValue N = getValue(I.getOperand(0));
  2523. EVT DestVT =
  2524. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2525. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2526. }
  2527. void SelectionDAGBuilder::visitZExt(const User &I) {
  2528. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2529. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2530. SDValue N = getValue(I.getOperand(0));
  2531. EVT DestVT =
  2532. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2533. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2534. }
  2535. void SelectionDAGBuilder::visitSExt(const User &I) {
  2536. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2537. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2538. SDValue N = getValue(I.getOperand(0));
  2539. EVT DestVT =
  2540. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2541. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2542. }
  2543. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2544. // FPTrunc is never a no-op cast, no need to check
  2545. SDValue N = getValue(I.getOperand(0));
  2546. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  2547. EVT DestVT = TLI->getValueType(I.getType());
  2548. setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
  2549. DestVT, N,
  2550. DAG.getTargetConstant(0, TLI->getPointerTy())));
  2551. }
  2552. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2553. // FPExt is never a no-op cast, no need to check
  2554. SDValue N = getValue(I.getOperand(0));
  2555. EVT DestVT =
  2556. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2557. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2558. }
  2559. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2560. // FPToUI is never a no-op cast, no need to check
  2561. SDValue N = getValue(I.getOperand(0));
  2562. EVT DestVT =
  2563. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2564. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2565. }
  2566. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2567. // FPToSI is never a no-op cast, no need to check
  2568. SDValue N = getValue(I.getOperand(0));
  2569. EVT DestVT =
  2570. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2571. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2572. }
  2573. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2574. // UIToFP is never a no-op cast, no need to check
  2575. SDValue N = getValue(I.getOperand(0));
  2576. EVT DestVT =
  2577. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2578. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2579. }
  2580. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2581. // SIToFP is never a no-op cast, no need to check
  2582. SDValue N = getValue(I.getOperand(0));
  2583. EVT DestVT =
  2584. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2585. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2586. }
  2587. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2588. // What to do depends on the size of the integer and the size of the pointer.
  2589. // We can either truncate, zero extend, or no-op, accordingly.
  2590. SDValue N = getValue(I.getOperand(0));
  2591. EVT DestVT =
  2592. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2593. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2594. }
  2595. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2596. // What to do depends on the size of the integer and the size of the pointer.
  2597. // We can either truncate, zero extend, or no-op, accordingly.
  2598. SDValue N = getValue(I.getOperand(0));
  2599. EVT DestVT =
  2600. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2601. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2602. }
  2603. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2604. SDValue N = getValue(I.getOperand(0));
  2605. EVT DestVT =
  2606. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2607. // BitCast assures us that source and destination are the same size so this is
  2608. // either a BITCAST or a no-op.
  2609. if (DestVT != N.getValueType())
  2610. setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  2611. DestVT, N)); // convert types.
  2612. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  2613. // might fold any kind of constant expression to an integer constant and that
  2614. // is not what we are looking for. Only regcognize a bitcast of a genuine
  2615. // constant integer as an opaque constant.
  2616. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  2617. setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
  2618. /*isOpaque*/true));
  2619. else
  2620. setValue(&I, N); // noop cast.
  2621. }
  2622. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  2623. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2624. const Value *SV = I.getOperand(0);
  2625. SDValue N = getValue(SV);
  2626. EVT DestVT =
  2627. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  2628. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  2629. unsigned DestAS = I.getType()->getPointerAddressSpace();
  2630. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2631. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  2632. setValue(&I, N);
  2633. }
  2634. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2635. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2636. SDValue InVec = getValue(I.getOperand(0));
  2637. SDValue InVal = getValue(I.getOperand(1));
  2638. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
  2639. getCurSDLoc(), TLI.getVectorIdxTy());
  2640. setValue(&I,
  2641. DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  2642. TM.getSubtargetImpl()->getTargetLowering()->getValueType(
  2643. I.getType()),
  2644. InVec, InVal, InIdx));
  2645. }
  2646. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2647. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2648. SDValue InVec = getValue(I.getOperand(0));
  2649. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
  2650. getCurSDLoc(), TLI.getVectorIdxTy());
  2651. setValue(&I,
  2652. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2653. TM.getSubtargetImpl()->getTargetLowering()->getValueType(
  2654. I.getType()),
  2655. InVec, InIdx));
  2656. }
  2657. // Utility for visitShuffleVector - Return true if every element in Mask,
  2658. // beginning from position Pos and ending in Pos+Size, falls within the
  2659. // specified sequential range [L, L+Pos). or is undef.
  2660. static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
  2661. unsigned Pos, unsigned Size, int Low) {
  2662. for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
  2663. if (Mask[i] >= 0 && Mask[i] != Low)
  2664. return false;
  2665. return true;
  2666. }
  2667. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2668. SDValue Src1 = getValue(I.getOperand(0));
  2669. SDValue Src2 = getValue(I.getOperand(1));
  2670. SmallVector<int, 8> Mask;
  2671. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  2672. unsigned MaskNumElts = Mask.size();
  2673. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  2674. EVT VT = TLI->getValueType(I.getType());
  2675. EVT SrcVT = Src1.getValueType();
  2676. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2677. if (SrcNumElts == MaskNumElts) {
  2678. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2679. &Mask[0]));
  2680. return;
  2681. }
  2682. // Normalize the shuffle vector since mask and vector length don't match.
  2683. if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
  2684. // Mask is longer than the source vectors and is a multiple of the source
  2685. // vectors. We can use concatenate vector to make the mask and vectors
  2686. // lengths match.
  2687. if (SrcNumElts*2 == MaskNumElts) {
  2688. // First check for Src1 in low and Src2 in high
  2689. if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
  2690. isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
  2691. // The shuffle is concatenating two vectors together.
  2692. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
  2693. VT, Src1, Src2));
  2694. return;
  2695. }
  2696. // Then check for Src2 in low and Src1 in high
  2697. if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
  2698. isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
  2699. // The shuffle is concatenating two vectors together.
  2700. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
  2701. VT, Src2, Src1));
  2702. return;
  2703. }
  2704. }
  2705. // Pad both vectors with undefs to make them the same length as the mask.
  2706. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2707. bool Src1U = Src1.getOpcode() == ISD::UNDEF;
  2708. bool Src2U = Src2.getOpcode() == ISD::UNDEF;
  2709. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2710. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2711. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2712. MOps1[0] = Src1;
  2713. MOps2[0] = Src2;
  2714. Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2715. getCurSDLoc(), VT, MOps1);
  2716. Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2717. getCurSDLoc(), VT, MOps2);
  2718. // Readjust mask for new input vector length.
  2719. SmallVector<int, 8> MappedOps;
  2720. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2721. int Idx = Mask[i];
  2722. if (Idx >= (int)SrcNumElts)
  2723. Idx -= SrcNumElts - MaskNumElts;
  2724. MappedOps.push_back(Idx);
  2725. }
  2726. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2727. &MappedOps[0]));
  2728. return;
  2729. }
  2730. if (SrcNumElts > MaskNumElts) {
  2731. // Analyze the access pattern of the vector to see if we can extract
  2732. // two subvectors and do the shuffle. The analysis is done by calculating
  2733. // the range of elements the mask access on both vectors.
  2734. int MinRange[2] = { static_cast<int>(SrcNumElts),
  2735. static_cast<int>(SrcNumElts)};
  2736. int MaxRange[2] = {-1, -1};
  2737. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2738. int Idx = Mask[i];
  2739. unsigned Input = 0;
  2740. if (Idx < 0)
  2741. continue;
  2742. if (Idx >= (int)SrcNumElts) {
  2743. Input = 1;
  2744. Idx -= SrcNumElts;
  2745. }
  2746. if (Idx > MaxRange[Input])
  2747. MaxRange[Input] = Idx;
  2748. if (Idx < MinRange[Input])
  2749. MinRange[Input] = Idx;
  2750. }
  2751. // Check if the access is smaller than the vector size and can we find
  2752. // a reasonable extract index.
  2753. int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
  2754. // Extract.
  2755. int StartIdx[2]; // StartIdx to extract from
  2756. for (unsigned Input = 0; Input < 2; ++Input) {
  2757. if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
  2758. RangeUse[Input] = 0; // Unused
  2759. StartIdx[Input] = 0;
  2760. continue;
  2761. }
  2762. // Find a good start index that is a multiple of the mask length. Then
  2763. // see if the rest of the elements are in range.
  2764. StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
  2765. if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
  2766. StartIdx[Input] + MaskNumElts <= SrcNumElts)
  2767. RangeUse[Input] = 1; // Extract from a multiple of the mask length.
  2768. }
  2769. if (RangeUse[0] == 0 && RangeUse[1] == 0) {
  2770. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2771. return;
  2772. }
  2773. if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
  2774. // Extract appropriate subvector and generate a vector shuffle
  2775. for (unsigned Input = 0; Input < 2; ++Input) {
  2776. SDValue &Src = Input == 0 ? Src1 : Src2;
  2777. if (RangeUse[Input] == 0)
  2778. Src = DAG.getUNDEF(VT);
  2779. else
  2780. Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
  2781. Src, DAG.getConstant(StartIdx[Input],
  2782. TLI->getVectorIdxTy()));
  2783. }
  2784. // Calculate new mask.
  2785. SmallVector<int, 8> MappedOps;
  2786. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2787. int Idx = Mask[i];
  2788. if (Idx >= 0) {
  2789. if (Idx < (int)SrcNumElts)
  2790. Idx -= StartIdx[0];
  2791. else
  2792. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  2793. }
  2794. MappedOps.push_back(Idx);
  2795. }
  2796. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2797. &MappedOps[0]));
  2798. return;
  2799. }
  2800. }
  2801. // We can't use either concat vectors or extract subvectors so fall back to
  2802. // replacing the shuffle with extract and build vector.
  2803. // to insert and build vector.
  2804. EVT EltVT = VT.getVectorElementType();
  2805. EVT IdxVT = TLI->getVectorIdxTy();
  2806. SmallVector<SDValue,8> Ops;
  2807. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2808. int Idx = Mask[i];
  2809. SDValue Res;
  2810. if (Idx < 0) {
  2811. Res = DAG.getUNDEF(EltVT);
  2812. } else {
  2813. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  2814. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  2815. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2816. EltVT, Src, DAG.getConstant(Idx, IdxVT));
  2817. }
  2818. Ops.push_back(Res);
  2819. }
  2820. setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
  2821. }
  2822. void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
  2823. const Value *Op0 = I.getOperand(0);
  2824. const Value *Op1 = I.getOperand(1);
  2825. Type *AggTy = I.getType();
  2826. Type *ValTy = Op1->getType();
  2827. bool IntoUndef = isa<UndefValue>(Op0);
  2828. bool FromUndef = isa<UndefValue>(Op1);
  2829. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2830. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  2831. SmallVector<EVT, 4> AggValueVTs;
  2832. ComputeValueVTs(*TLI, AggTy, AggValueVTs);
  2833. SmallVector<EVT, 4> ValValueVTs;
  2834. ComputeValueVTs(*TLI, ValTy, ValValueVTs);
  2835. unsigned NumAggValues = AggValueVTs.size();
  2836. unsigned NumValValues = ValValueVTs.size();
  2837. SmallVector<SDValue, 4> Values(NumAggValues);
  2838. SDValue Agg = getValue(Op0);
  2839. unsigned i = 0;
  2840. // Copy the beginning value(s) from the original aggregate.
  2841. for (; i != LinearIndex; ++i)
  2842. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2843. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2844. // Copy values from the inserted value(s).
  2845. if (NumValValues) {
  2846. SDValue Val = getValue(Op1);
  2847. for (; i != LinearIndex + NumValValues; ++i)
  2848. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2849. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2850. }
  2851. // Copy remaining value(s) from the original aggregate.
  2852. for (; i != NumAggValues; ++i)
  2853. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2854. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2855. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2856. DAG.getVTList(AggValueVTs), Values));
  2857. }
  2858. void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
  2859. const Value *Op0 = I.getOperand(0);
  2860. Type *AggTy = Op0->getType();
  2861. Type *ValTy = I.getType();
  2862. bool OutOfUndef = isa<UndefValue>(Op0);
  2863. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2864. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  2865. SmallVector<EVT, 4> ValValueVTs;
  2866. ComputeValueVTs(*TLI, ValTy, ValValueVTs);
  2867. unsigned NumValValues = ValValueVTs.size();
  2868. // Ignore a extractvalue that produces an empty object
  2869. if (!NumValValues) {
  2870. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2871. return;
  2872. }
  2873. SmallVector<SDValue, 4> Values(NumValValues);
  2874. SDValue Agg = getValue(Op0);
  2875. // Copy out the selected value(s).
  2876. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2877. Values[i - LinearIndex] =
  2878. OutOfUndef ?
  2879. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2880. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2881. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2882. DAG.getVTList(ValValueVTs), Values));
  2883. }
  2884. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  2885. Value *Op0 = I.getOperand(0);
  2886. // Note that the pointer operand may be a vector of pointers. Take the scalar
  2887. // element which holds a pointer.
  2888. Type *Ty = Op0->getType()->getScalarType();
  2889. unsigned AS = Ty->getPointerAddressSpace();
  2890. SDValue N = getValue(Op0);
  2891. for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
  2892. OI != E; ++OI) {
  2893. const Value *Idx = *OI;
  2894. if (StructType *StTy = dyn_cast<StructType>(Ty)) {
  2895. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  2896. if (Field) {
  2897. // N = N + Offset
  2898. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  2899. N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
  2900. DAG.getConstant(Offset, N.getValueType()));
  2901. }
  2902. Ty = StTy->getElementType(Field);
  2903. } else {
  2904. Ty = cast<SequentialType>(Ty)->getElementType();
  2905. // If this is a constant subscript, handle it quickly.
  2906. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  2907. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
  2908. if (CI->isZero()) continue;
  2909. uint64_t Offs =
  2910. DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
  2911. SDValue OffsVal;
  2912. EVT PTy = TLI->getPointerTy(AS);
  2913. unsigned PtrBits = PTy.getSizeInBits();
  2914. if (PtrBits < 64)
  2915. OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
  2916. DAG.getConstant(Offs, MVT::i64));
  2917. else
  2918. OffsVal = DAG.getConstant(Offs, PTy);
  2919. N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
  2920. OffsVal);
  2921. continue;
  2922. }
  2923. // N = N + Idx * ElementSize;
  2924. APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
  2925. DL->getTypeAllocSize(Ty));
  2926. SDValue IdxN = getValue(Idx);
  2927. // If the index is smaller or larger than intptr_t, truncate or extend
  2928. // it.
  2929. IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
  2930. // If this is a multiply by a power of two, turn it into a shl
  2931. // immediately. This is a very common case.
  2932. if (ElementSize != 1) {
  2933. if (ElementSize.isPowerOf2()) {
  2934. unsigned Amt = ElementSize.logBase2();
  2935. IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
  2936. N.getValueType(), IdxN,
  2937. DAG.getConstant(Amt, IdxN.getValueType()));
  2938. } else {
  2939. SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
  2940. IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
  2941. N.getValueType(), IdxN, Scale);
  2942. }
  2943. }
  2944. N = DAG.getNode(ISD::ADD, getCurSDLoc(),
  2945. N.getValueType(), N, IdxN);
  2946. }
  2947. }
  2948. setValue(&I, N);
  2949. }
  2950. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  2951. // If this is a fixed sized alloca in the entry block of the function,
  2952. // allocate it statically on the stack.
  2953. if (FuncInfo.StaticAllocaMap.count(&I))
  2954. return; // getValue will auto-populate this.
  2955. Type *Ty = I.getAllocatedType();
  2956. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  2957. uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
  2958. unsigned Align =
  2959. std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
  2960. I.getAlignment());
  2961. SDValue AllocSize = getValue(I.getArraySize());
  2962. EVT IntPtr = TLI->getPointerTy();
  2963. if (AllocSize.getValueType() != IntPtr)
  2964. AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
  2965. AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
  2966. AllocSize,
  2967. DAG.getConstant(TySize, IntPtr));
  2968. // Handle alignment. If the requested alignment is less than or equal to
  2969. // the stack alignment, ignore it. If the size is greater than or equal to
  2970. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  2971. unsigned StackAlign =
  2972. TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
  2973. if (Align <= StackAlign)
  2974. Align = 0;
  2975. // Round the size of the allocation up to the stack alignment size
  2976. // by add SA-1 to the size.
  2977. AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
  2978. AllocSize.getValueType(), AllocSize,
  2979. DAG.getIntPtrConstant(StackAlign-1));
  2980. // Mask out the low bits for alignment purposes.
  2981. AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
  2982. AllocSize.getValueType(), AllocSize,
  2983. DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
  2984. SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
  2985. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  2986. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
  2987. setValue(&I, DSA);
  2988. DAG.setRoot(DSA.getValue(1));
  2989. assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
  2990. }
  2991. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  2992. if (I.isAtomic())
  2993. return visitAtomicLoad(I);
  2994. const Value *SV = I.getOperand(0);
  2995. SDValue Ptr = getValue(SV);
  2996. Type *Ty = I.getType();
  2997. bool isVolatile = I.isVolatile();
  2998. bool isNonTemporal = I.getMetadata("nontemporal") != nullptr;
  2999. bool isInvariant = I.getMetadata("invariant.load") != nullptr;
  3000. unsigned Alignment = I.getAlignment();
  3001. AAMDNodes AAInfo;
  3002. I.getAAMetadata(AAInfo);
  3003. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3004. SmallVector<EVT, 4> ValueVTs;
  3005. SmallVector<uint64_t, 4> Offsets;
  3006. ComputeValueVTs(*TM.getSubtargetImpl()->getTargetLowering(), Ty, ValueVTs,
  3007. &Offsets);
  3008. unsigned NumValues = ValueVTs.size();
  3009. if (NumValues == 0)
  3010. return;
  3011. SDValue Root;
  3012. bool ConstantMemory = false;
  3013. if (isVolatile || NumValues > MaxParallelChains)
  3014. // Serialize volatile loads with other side effects.
  3015. Root = getRoot();
  3016. else if (AA->pointsToConstantMemory(
  3017. AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
  3018. // Do not serialize (non-volatile) loads of constant memory with anything.
  3019. Root = DAG.getEntryNode();
  3020. ConstantMemory = true;
  3021. } else {
  3022. // Do not serialize non-volatile loads against each other.
  3023. Root = DAG.getRoot();
  3024. }
  3025. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  3026. if (isVolatile)
  3027. Root = TLI->prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
  3028. SmallVector<SDValue, 4> Values(NumValues);
  3029. SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
  3030. NumValues));
  3031. EVT PtrVT = Ptr.getValueType();
  3032. unsigned ChainI = 0;
  3033. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3034. // Serializing loads here may result in excessive register pressure, and
  3035. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3036. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3037. // they are side-effect free or do not alias. The optimizer should really
  3038. // avoid this case by converting large object/array copies to llvm.memcpy
  3039. // (MaxParallelChains should always remain as failsafe).
  3040. if (ChainI == MaxParallelChains) {
  3041. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3042. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  3043. makeArrayRef(Chains.data(), ChainI));
  3044. Root = Chain;
  3045. ChainI = 0;
  3046. }
  3047. SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
  3048. PtrVT, Ptr,
  3049. DAG.getConstant(Offsets[i], PtrVT));
  3050. SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
  3051. A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
  3052. isNonTemporal, isInvariant, Alignment, AAInfo,
  3053. Ranges);
  3054. Values[i] = L;
  3055. Chains[ChainI] = L.getValue(1);
  3056. }
  3057. if (!ConstantMemory) {
  3058. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  3059. makeArrayRef(Chains.data(), ChainI));
  3060. if (isVolatile)
  3061. DAG.setRoot(Chain);
  3062. else
  3063. PendingLoads.push_back(Chain);
  3064. }
  3065. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3066. DAG.getVTList(ValueVTs), Values));
  3067. }
  3068. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3069. if (I.isAtomic())
  3070. return visitAtomicStore(I);
  3071. const Value *SrcV = I.getOperand(0);
  3072. const Value *PtrV = I.getOperand(1);
  3073. SmallVector<EVT, 4> ValueVTs;
  3074. SmallVector<uint64_t, 4> Offsets;
  3075. ComputeValueVTs(*TM.getSubtargetImpl()->getTargetLowering(), SrcV->getType(),
  3076. ValueVTs, &Offsets);
  3077. unsigned NumValues = ValueVTs.size();
  3078. if (NumValues == 0)
  3079. return;
  3080. // Get the lowered operands. Note that we do this after
  3081. // checking if NumResults is zero, because with zero results
  3082. // the operands won't have values in the map.
  3083. SDValue Src = getValue(SrcV);
  3084. SDValue Ptr = getValue(PtrV);
  3085. SDValue Root = getRoot();
  3086. SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
  3087. NumValues));
  3088. EVT PtrVT = Ptr.getValueType();
  3089. bool isVolatile = I.isVolatile();
  3090. bool isNonTemporal = I.getMetadata("nontemporal") != nullptr;
  3091. unsigned Alignment = I.getAlignment();
  3092. AAMDNodes AAInfo;
  3093. I.getAAMetadata(AAInfo);
  3094. unsigned ChainI = 0;
  3095. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3096. // See visitLoad comments.
  3097. if (ChainI == MaxParallelChains) {
  3098. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  3099. makeArrayRef(Chains.data(), ChainI));
  3100. Root = Chain;
  3101. ChainI = 0;
  3102. }
  3103. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
  3104. DAG.getConstant(Offsets[i], PtrVT));
  3105. SDValue St = DAG.getStore(Root, getCurSDLoc(),
  3106. SDValue(Src.getNode(), Src.getResNo() + i),
  3107. Add, MachinePointerInfo(PtrV, Offsets[i]),
  3108. isVolatile, isNonTemporal, Alignment, AAInfo);
  3109. Chains[ChainI] = St;
  3110. }
  3111. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  3112. makeArrayRef(Chains.data(), ChainI));
  3113. DAG.setRoot(StoreNode);
  3114. }
  3115. static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
  3116. SynchronizationScope Scope,
  3117. bool Before, SDLoc dl,
  3118. SelectionDAG &DAG,
  3119. const TargetLowering &TLI) {
  3120. // Fence, if necessary
  3121. if (Before) {
  3122. if (Order == AcquireRelease || Order == SequentiallyConsistent)
  3123. Order = Release;
  3124. else if (Order == Acquire || Order == Monotonic || Order == Unordered)
  3125. return Chain;
  3126. } else {
  3127. if (Order == AcquireRelease)
  3128. Order = Acquire;
  3129. else if (Order == Release || Order == Monotonic || Order == Unordered)
  3130. return Chain;
  3131. }
  3132. SDValue Ops[3];
  3133. Ops[0] = Chain;
  3134. Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
  3135. Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
  3136. return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
  3137. }
  3138. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3139. SDLoc dl = getCurSDLoc();
  3140. AtomicOrdering SuccessOrder = I.getSuccessOrdering();
  3141. AtomicOrdering FailureOrder = I.getFailureOrdering();
  3142. SynchronizationScope Scope = I.getSynchScope();
  3143. SDValue InChain = getRoot();
  3144. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  3145. if (TLI->getInsertFencesForAtomic())
  3146. InChain = InsertFenceForAtomic(InChain, SuccessOrder, Scope, true, dl,
  3147. DAG, *TLI);
  3148. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3149. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3150. SDValue L = DAG.getAtomicCmpSwap(
  3151. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
  3152. getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
  3153. getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
  3154. 0 /* Alignment */,
  3155. TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder,
  3156. TLI->getInsertFencesForAtomic() ? Monotonic : FailureOrder, Scope);
  3157. SDValue OutChain = L.getValue(2);
  3158. if (TLI->getInsertFencesForAtomic())
  3159. OutChain = InsertFenceForAtomic(OutChain, SuccessOrder, Scope, false, dl,
  3160. DAG, *TLI);
  3161. setValue(&I, L);
  3162. DAG.setRoot(OutChain);
  3163. }
  3164. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3165. SDLoc dl = getCurSDLoc();
  3166. ISD::NodeType NT;
  3167. switch (I.getOperation()) {
  3168. default: llvm_unreachable("Unknown atomicrmw operation");
  3169. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3170. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3171. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3172. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3173. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3174. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3175. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3176. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3177. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3178. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3179. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3180. }
  3181. AtomicOrdering Order = I.getOrdering();
  3182. SynchronizationScope Scope = I.getSynchScope();
  3183. SDValue InChain = getRoot();
  3184. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  3185. if (TLI->getInsertFencesForAtomic())
  3186. InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
  3187. DAG, *TLI);
  3188. SDValue L =
  3189. DAG.getAtomic(NT, dl,
  3190. getValue(I.getValOperand()).getSimpleValueType(),
  3191. InChain,
  3192. getValue(I.getPointerOperand()),
  3193. getValue(I.getValOperand()),
  3194. I.getPointerOperand(), 0 /* Alignment */,
  3195. TLI->getInsertFencesForAtomic() ? Monotonic : Order,
  3196. Scope);
  3197. SDValue OutChain = L.getValue(1);
  3198. if (TLI->getInsertFencesForAtomic())
  3199. OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
  3200. DAG, *TLI);
  3201. setValue(&I, L);
  3202. DAG.setRoot(OutChain);
  3203. }
  3204. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3205. SDLoc dl = getCurSDLoc();
  3206. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  3207. SDValue Ops[3];
  3208. Ops[0] = getRoot();
  3209. Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
  3210. Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
  3211. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3212. }
  3213. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3214. SDLoc dl = getCurSDLoc();
  3215. AtomicOrdering Order = I.getOrdering();
  3216. SynchronizationScope Scope = I.getSynchScope();
  3217. SDValue InChain = getRoot();
  3218. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  3219. EVT VT = TLI->getValueType(I.getType());
  3220. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3221. report_fatal_error("Cannot generate unaligned atomic load");
  3222. MachineMemOperand *MMO =
  3223. DAG.getMachineFunction().
  3224. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3225. MachineMemOperand::MOVolatile |
  3226. MachineMemOperand::MOLoad,
  3227. VT.getStoreSize(),
  3228. I.getAlignment() ? I.getAlignment() :
  3229. DAG.getEVTAlignment(VT));
  3230. InChain = TLI->prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  3231. SDValue L =
  3232. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  3233. getValue(I.getPointerOperand()), MMO,
  3234. TLI->getInsertFencesForAtomic() ? Monotonic : Order,
  3235. Scope);
  3236. SDValue OutChain = L.getValue(1);
  3237. if (TLI->getInsertFencesForAtomic())
  3238. OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
  3239. DAG, *TLI);
  3240. setValue(&I, L);
  3241. DAG.setRoot(OutChain);
  3242. }
  3243. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  3244. SDLoc dl = getCurSDLoc();
  3245. AtomicOrdering Order = I.getOrdering();
  3246. SynchronizationScope Scope = I.getSynchScope();
  3247. SDValue InChain = getRoot();
  3248. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  3249. EVT VT = TLI->getValueType(I.getValueOperand()->getType());
  3250. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3251. report_fatal_error("Cannot generate unaligned atomic store");
  3252. if (TLI->getInsertFencesForAtomic())
  3253. InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
  3254. DAG, *TLI);
  3255. SDValue OutChain =
  3256. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
  3257. InChain,
  3258. getValue(I.getPointerOperand()),
  3259. getValue(I.getValueOperand()),
  3260. I.getPointerOperand(), I.getAlignment(),
  3261. TLI->getInsertFencesForAtomic() ? Monotonic : Order,
  3262. Scope);
  3263. if (TLI->getInsertFencesForAtomic())
  3264. OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
  3265. DAG, *TLI);
  3266. DAG.setRoot(OutChain);
  3267. }
  3268. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  3269. /// node.
  3270. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  3271. unsigned Intrinsic) {
  3272. bool HasChain = !I.doesNotAccessMemory();
  3273. bool OnlyLoad = HasChain && I.onlyReadsMemory();
  3274. // Build the operand list.
  3275. SmallVector<SDValue, 8> Ops;
  3276. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  3277. if (OnlyLoad) {
  3278. // We don't need to serialize loads against other loads.
  3279. Ops.push_back(DAG.getRoot());
  3280. } else {
  3281. Ops.push_back(getRoot());
  3282. }
  3283. }
  3284. // Info is set by getTgtMemInstrinsic
  3285. TargetLowering::IntrinsicInfo Info;
  3286. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  3287. bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
  3288. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  3289. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  3290. Info.opc == ISD::INTRINSIC_W_CHAIN)
  3291. Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
  3292. // Add all operands of the call to the operand list.
  3293. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  3294. SDValue Op = getValue(I.getArgOperand(i));
  3295. Ops.push_back(Op);
  3296. }
  3297. SmallVector<EVT, 4> ValueVTs;
  3298. ComputeValueVTs(*TLI, I.getType(), ValueVTs);
  3299. if (HasChain)
  3300. ValueVTs.push_back(MVT::Other);
  3301. SDVTList VTs = DAG.getVTList(ValueVTs);
  3302. // Create the node.
  3303. SDValue Result;
  3304. if (IsTgtIntrinsic) {
  3305. // This is target intrinsic that touches memory
  3306. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
  3307. VTs, Ops, Info.memVT,
  3308. MachinePointerInfo(Info.ptrVal, Info.offset),
  3309. Info.align, Info.vol,
  3310. Info.readMem, Info.writeMem);
  3311. } else if (!HasChain) {
  3312. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  3313. } else if (!I.getType()->isVoidTy()) {
  3314. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  3315. } else {
  3316. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  3317. }
  3318. if (HasChain) {
  3319. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  3320. if (OnlyLoad)
  3321. PendingLoads.push_back(Chain);
  3322. else
  3323. DAG.setRoot(Chain);
  3324. }
  3325. if (!I.getType()->isVoidTy()) {
  3326. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  3327. EVT VT = TLI->getValueType(PTy);
  3328. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  3329. }
  3330. setValue(&I, Result);
  3331. }
  3332. }
  3333. /// GetSignificand - Get the significand and build it into a floating-point
  3334. /// number with exponent of 1:
  3335. ///
  3336. /// Op = (Op & 0x007fffff) | 0x3f800000;
  3337. ///
  3338. /// where Op is the hexadecimal representation of floating point value.
  3339. static SDValue
  3340. GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
  3341. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3342. DAG.getConstant(0x007fffff, MVT::i32));
  3343. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  3344. DAG.getConstant(0x3f800000, MVT::i32));
  3345. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  3346. }
  3347. /// GetExponent - Get the exponent:
  3348. ///
  3349. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  3350. ///
  3351. /// where Op is the hexadecimal representation of floating point value.
  3352. static SDValue
  3353. GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
  3354. SDLoc dl) {
  3355. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3356. DAG.getConstant(0x7f800000, MVT::i32));
  3357. SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
  3358. DAG.getConstant(23, TLI.getPointerTy()));
  3359. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  3360. DAG.getConstant(127, MVT::i32));
  3361. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  3362. }
  3363. /// getF32Constant - Get 32-bit floating point constant.
  3364. static SDValue
  3365. getF32Constant(SelectionDAG &DAG, unsigned Flt) {
  3366. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
  3367. MVT::f32);
  3368. }
  3369. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  3370. /// limited-precision mode.
  3371. static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3372. const TargetLowering &TLI) {
  3373. if (Op.getValueType() == MVT::f32 &&
  3374. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3375. // Put the exponent in the right bit position for later addition to the
  3376. // final result:
  3377. //
  3378. // #define LOG2OFe 1.4426950f
  3379. // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
  3380. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3381. getF32Constant(DAG, 0x3fb8aa3b));
  3382. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3383. // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
  3384. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3385. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3386. // IntegerPartOfX <<= 23;
  3387. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3388. DAG.getConstant(23, TLI.getPointerTy()));
  3389. SDValue TwoToFracPartOfX;
  3390. if (LimitFloatPrecision <= 6) {
  3391. // For floating-point precision of 6:
  3392. //
  3393. // TwoToFractionalPartOfX =
  3394. // 0.997535578f +
  3395. // (0.735607626f + 0.252464424f * x) * x;
  3396. //
  3397. // error 0.0144103317, which is 6 bits
  3398. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3399. getF32Constant(DAG, 0x3e814304));
  3400. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3401. getF32Constant(DAG, 0x3f3c50c8));
  3402. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3403. TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3404. getF32Constant(DAG, 0x3f7f5e7e));
  3405. } else if (LimitFloatPrecision <= 12) {
  3406. // For floating-point precision of 12:
  3407. //
  3408. // TwoToFractionalPartOfX =
  3409. // 0.999892986f +
  3410. // (0.696457318f +
  3411. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3412. //
  3413. // 0.000107046256 error, which is 13 to 14 bits
  3414. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3415. getF32Constant(DAG, 0x3da235e3));
  3416. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3417. getF32Constant(DAG, 0x3e65b8f3));
  3418. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3419. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3420. getF32Constant(DAG, 0x3f324b07));
  3421. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3422. TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3423. getF32Constant(DAG, 0x3f7ff8fd));
  3424. } else { // LimitFloatPrecision <= 18
  3425. // For floating-point precision of 18:
  3426. //
  3427. // TwoToFractionalPartOfX =
  3428. // 0.999999982f +
  3429. // (0.693148872f +
  3430. // (0.240227044f +
  3431. // (0.554906021e-1f +
  3432. // (0.961591928e-2f +
  3433. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3434. //
  3435. // error 2.47208000*10^(-7), which is better than 18 bits
  3436. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3437. getF32Constant(DAG, 0x3924b03e));
  3438. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3439. getF32Constant(DAG, 0x3ab24b87));
  3440. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3441. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3442. getF32Constant(DAG, 0x3c1d8c17));
  3443. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3444. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3445. getF32Constant(DAG, 0x3d634a1d));
  3446. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3447. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3448. getF32Constant(DAG, 0x3e75fe14));
  3449. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3450. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3451. getF32Constant(DAG, 0x3f317234));
  3452. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3453. TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3454. getF32Constant(DAG, 0x3f800000));
  3455. }
  3456. // Add the exponent into the result in integer domain.
  3457. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
  3458. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3459. DAG.getNode(ISD::ADD, dl, MVT::i32,
  3460. t13, IntegerPartOfX));
  3461. }
  3462. // No special expansion.
  3463. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  3464. }
  3465. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  3466. /// limited-precision mode.
  3467. static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3468. const TargetLowering &TLI) {
  3469. if (Op.getValueType() == MVT::f32 &&
  3470. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3471. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3472. // Scale the exponent by log(2) [0.69314718f].
  3473. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3474. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3475. getF32Constant(DAG, 0x3f317218));
  3476. // Get the significand and build it into a floating-point number with
  3477. // exponent of 1.
  3478. SDValue X = GetSignificand(DAG, Op1, dl);
  3479. SDValue LogOfMantissa;
  3480. if (LimitFloatPrecision <= 6) {
  3481. // For floating-point precision of 6:
  3482. //
  3483. // LogofMantissa =
  3484. // -1.1609546f +
  3485. // (1.4034025f - 0.23903021f * x) * x;
  3486. //
  3487. // error 0.0034276066, which is better than 8 bits
  3488. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3489. getF32Constant(DAG, 0xbe74c456));
  3490. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3491. getF32Constant(DAG, 0x3fb3a2b1));
  3492. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3493. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3494. getF32Constant(DAG, 0x3f949a29));
  3495. } else if (LimitFloatPrecision <= 12) {
  3496. // For floating-point precision of 12:
  3497. //
  3498. // LogOfMantissa =
  3499. // -1.7417939f +
  3500. // (2.8212026f +
  3501. // (-1.4699568f +
  3502. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  3503. //
  3504. // error 0.000061011436, which is 14 bits
  3505. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3506. getF32Constant(DAG, 0xbd67b6d6));
  3507. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3508. getF32Constant(DAG, 0x3ee4f4b8));
  3509. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3510. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3511. getF32Constant(DAG, 0x3fbc278b));
  3512. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3513. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3514. getF32Constant(DAG, 0x40348e95));
  3515. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3516. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3517. getF32Constant(DAG, 0x3fdef31a));
  3518. } else { // LimitFloatPrecision <= 18
  3519. // For floating-point precision of 18:
  3520. //
  3521. // LogOfMantissa =
  3522. // -2.1072184f +
  3523. // (4.2372794f +
  3524. // (-3.7029485f +
  3525. // (2.2781945f +
  3526. // (-0.87823314f +
  3527. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  3528. //
  3529. // error 0.0000023660568, which is better than 18 bits
  3530. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3531. getF32Constant(DAG, 0xbc91e5ac));
  3532. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3533. getF32Constant(DAG, 0x3e4350aa));
  3534. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3535. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3536. getF32Constant(DAG, 0x3f60d3e3));
  3537. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3538. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3539. getF32Constant(DAG, 0x4011cdf0));
  3540. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3541. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3542. getF32Constant(DAG, 0x406cfd1c));
  3543. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3544. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3545. getF32Constant(DAG, 0x408797cb));
  3546. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3547. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3548. getF32Constant(DAG, 0x4006dcab));
  3549. }
  3550. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  3551. }
  3552. // No special expansion.
  3553. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  3554. }
  3555. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  3556. /// limited-precision mode.
  3557. static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3558. const TargetLowering &TLI) {
  3559. if (Op.getValueType() == MVT::f32 &&
  3560. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3561. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3562. // Get the exponent.
  3563. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  3564. // Get the significand and build it into a floating-point number with
  3565. // exponent of 1.
  3566. SDValue X = GetSignificand(DAG, Op1, dl);
  3567. // Different possible minimax approximations of significand in
  3568. // floating-point for various degrees of accuracy over [1,2].
  3569. SDValue Log2ofMantissa;
  3570. if (LimitFloatPrecision <= 6) {
  3571. // For floating-point precision of 6:
  3572. //
  3573. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  3574. //
  3575. // error 0.0049451742, which is more than 7 bits
  3576. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3577. getF32Constant(DAG, 0xbeb08fe0));
  3578. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3579. getF32Constant(DAG, 0x40019463));
  3580. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3581. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3582. getF32Constant(DAG, 0x3fd6633d));
  3583. } else if (LimitFloatPrecision <= 12) {
  3584. // For floating-point precision of 12:
  3585. //
  3586. // Log2ofMantissa =
  3587. // -2.51285454f +
  3588. // (4.07009056f +
  3589. // (-2.12067489f +
  3590. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  3591. //
  3592. // error 0.0000876136000, which is better than 13 bits
  3593. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3594. getF32Constant(DAG, 0xbda7262e));
  3595. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3596. getF32Constant(DAG, 0x3f25280b));
  3597. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3598. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3599. getF32Constant(DAG, 0x4007b923));
  3600. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3601. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3602. getF32Constant(DAG, 0x40823e2f));
  3603. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3604. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3605. getF32Constant(DAG, 0x4020d29c));
  3606. } else { // LimitFloatPrecision <= 18
  3607. // For floating-point precision of 18:
  3608. //
  3609. // Log2ofMantissa =
  3610. // -3.0400495f +
  3611. // (6.1129976f +
  3612. // (-5.3420409f +
  3613. // (3.2865683f +
  3614. // (-1.2669343f +
  3615. // (0.27515199f -
  3616. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  3617. //
  3618. // error 0.0000018516, which is better than 18 bits
  3619. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3620. getF32Constant(DAG, 0xbcd2769e));
  3621. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3622. getF32Constant(DAG, 0x3e8ce0b9));
  3623. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3624. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3625. getF32Constant(DAG, 0x3fa22ae7));
  3626. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3627. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3628. getF32Constant(DAG, 0x40525723));
  3629. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3630. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3631. getF32Constant(DAG, 0x40aaf200));
  3632. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3633. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3634. getF32Constant(DAG, 0x40c39dad));
  3635. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3636. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3637. getF32Constant(DAG, 0x4042902c));
  3638. }
  3639. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  3640. }
  3641. // No special expansion.
  3642. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  3643. }
  3644. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  3645. /// limited-precision mode.
  3646. static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3647. const TargetLowering &TLI) {
  3648. if (Op.getValueType() == MVT::f32 &&
  3649. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3650. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3651. // Scale the exponent by log10(2) [0.30102999f].
  3652. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3653. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3654. getF32Constant(DAG, 0x3e9a209a));
  3655. // Get the significand and build it into a floating-point number with
  3656. // exponent of 1.
  3657. SDValue X = GetSignificand(DAG, Op1, dl);
  3658. SDValue Log10ofMantissa;
  3659. if (LimitFloatPrecision <= 6) {
  3660. // For floating-point precision of 6:
  3661. //
  3662. // Log10ofMantissa =
  3663. // -0.50419619f +
  3664. // (0.60948995f - 0.10380950f * x) * x;
  3665. //
  3666. // error 0.0014886165, which is 6 bits
  3667. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3668. getF32Constant(DAG, 0xbdd49a13));
  3669. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3670. getF32Constant(DAG, 0x3f1c0789));
  3671. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3672. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3673. getF32Constant(DAG, 0x3f011300));
  3674. } else if (LimitFloatPrecision <= 12) {
  3675. // For floating-point precision of 12:
  3676. //
  3677. // Log10ofMantissa =
  3678. // -0.64831180f +
  3679. // (0.91751397f +
  3680. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  3681. //
  3682. // error 0.00019228036, which is better than 12 bits
  3683. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3684. getF32Constant(DAG, 0x3d431f31));
  3685. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3686. getF32Constant(DAG, 0x3ea21fb2));
  3687. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3688. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3689. getF32Constant(DAG, 0x3f6ae232));
  3690. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3691. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3692. getF32Constant(DAG, 0x3f25f7c3));
  3693. } else { // LimitFloatPrecision <= 18
  3694. // For floating-point precision of 18:
  3695. //
  3696. // Log10ofMantissa =
  3697. // -0.84299375f +
  3698. // (1.5327582f +
  3699. // (-1.0688956f +
  3700. // (0.49102474f +
  3701. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  3702. //
  3703. // error 0.0000037995730, which is better than 18 bits
  3704. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3705. getF32Constant(DAG, 0x3c5d51ce));
  3706. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3707. getF32Constant(DAG, 0x3e00685a));
  3708. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3709. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3710. getF32Constant(DAG, 0x3efb6798));
  3711. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3712. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3713. getF32Constant(DAG, 0x3f88d192));
  3714. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3715. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3716. getF32Constant(DAG, 0x3fc4316c));
  3717. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3718. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  3719. getF32Constant(DAG, 0x3f57ce70));
  3720. }
  3721. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  3722. }
  3723. // No special expansion.
  3724. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  3725. }
  3726. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  3727. /// limited-precision mode.
  3728. static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3729. const TargetLowering &TLI) {
  3730. if (Op.getValueType() == MVT::f32 &&
  3731. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3732. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
  3733. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3734. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3735. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
  3736. // IntegerPartOfX <<= 23;
  3737. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3738. DAG.getConstant(23, TLI.getPointerTy()));
  3739. SDValue TwoToFractionalPartOfX;
  3740. if (LimitFloatPrecision <= 6) {
  3741. // For floating-point precision of 6:
  3742. //
  3743. // TwoToFractionalPartOfX =
  3744. // 0.997535578f +
  3745. // (0.735607626f + 0.252464424f * x) * x;
  3746. //
  3747. // error 0.0144103317, which is 6 bits
  3748. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3749. getF32Constant(DAG, 0x3e814304));
  3750. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3751. getF32Constant(DAG, 0x3f3c50c8));
  3752. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3753. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3754. getF32Constant(DAG, 0x3f7f5e7e));
  3755. } else if (LimitFloatPrecision <= 12) {
  3756. // For floating-point precision of 12:
  3757. //
  3758. // TwoToFractionalPartOfX =
  3759. // 0.999892986f +
  3760. // (0.696457318f +
  3761. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3762. //
  3763. // error 0.000107046256, which is 13 to 14 bits
  3764. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3765. getF32Constant(DAG, 0x3da235e3));
  3766. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3767. getF32Constant(DAG, 0x3e65b8f3));
  3768. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3769. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3770. getF32Constant(DAG, 0x3f324b07));
  3771. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3772. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3773. getF32Constant(DAG, 0x3f7ff8fd));
  3774. } else { // LimitFloatPrecision <= 18
  3775. // For floating-point precision of 18:
  3776. //
  3777. // TwoToFractionalPartOfX =
  3778. // 0.999999982f +
  3779. // (0.693148872f +
  3780. // (0.240227044f +
  3781. // (0.554906021e-1f +
  3782. // (0.961591928e-2f +
  3783. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3784. // error 2.47208000*10^(-7), which is better than 18 bits
  3785. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3786. getF32Constant(DAG, 0x3924b03e));
  3787. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3788. getF32Constant(DAG, 0x3ab24b87));
  3789. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3790. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3791. getF32Constant(DAG, 0x3c1d8c17));
  3792. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3793. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3794. getF32Constant(DAG, 0x3d634a1d));
  3795. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3796. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3797. getF32Constant(DAG, 0x3e75fe14));
  3798. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3799. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3800. getF32Constant(DAG, 0x3f317234));
  3801. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3802. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3803. getF32Constant(DAG, 0x3f800000));
  3804. }
  3805. // Add the exponent into the result in integer domain.
  3806. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
  3807. TwoToFractionalPartOfX);
  3808. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3809. DAG.getNode(ISD::ADD, dl, MVT::i32,
  3810. t13, IntegerPartOfX));
  3811. }
  3812. // No special expansion.
  3813. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  3814. }
  3815. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  3816. /// limited-precision mode with x == 10.0f.
  3817. static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
  3818. SelectionDAG &DAG, const TargetLowering &TLI) {
  3819. bool IsExp10 = false;
  3820. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  3821. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3822. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  3823. APFloat Ten(10.0f);
  3824. IsExp10 = LHSC->isExactlyValue(Ten);
  3825. }
  3826. }
  3827. if (IsExp10) {
  3828. // Put the exponent in the right bit position for later addition to the
  3829. // final result:
  3830. //
  3831. // #define LOG2OF10 3.3219281f
  3832. // IntegerPartOfX = (int32_t)(x * LOG2OF10);
  3833. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  3834. getF32Constant(DAG, 0x40549a78));
  3835. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3836. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3837. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3838. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3839. // IntegerPartOfX <<= 23;
  3840. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3841. DAG.getConstant(23, TLI.getPointerTy()));
  3842. SDValue TwoToFractionalPartOfX;
  3843. if (LimitFloatPrecision <= 6) {
  3844. // For floating-point precision of 6:
  3845. //
  3846. // twoToFractionalPartOfX =
  3847. // 0.997535578f +
  3848. // (0.735607626f + 0.252464424f * x) * x;
  3849. //
  3850. // error 0.0144103317, which is 6 bits
  3851. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3852. getF32Constant(DAG, 0x3e814304));
  3853. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3854. getF32Constant(DAG, 0x3f3c50c8));
  3855. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3856. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3857. getF32Constant(DAG, 0x3f7f5e7e));
  3858. } else if (LimitFloatPrecision <= 12) {
  3859. // For floating-point precision of 12:
  3860. //
  3861. // TwoToFractionalPartOfX =
  3862. // 0.999892986f +
  3863. // (0.696457318f +
  3864. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3865. //
  3866. // error 0.000107046256, which is 13 to 14 bits
  3867. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3868. getF32Constant(DAG, 0x3da235e3));
  3869. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3870. getF32Constant(DAG, 0x3e65b8f3));
  3871. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3872. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3873. getF32Constant(DAG, 0x3f324b07));
  3874. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3875. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3876. getF32Constant(DAG, 0x3f7ff8fd));
  3877. } else { // LimitFloatPrecision <= 18
  3878. // For floating-point precision of 18:
  3879. //
  3880. // TwoToFractionalPartOfX =
  3881. // 0.999999982f +
  3882. // (0.693148872f +
  3883. // (0.240227044f +
  3884. // (0.554906021e-1f +
  3885. // (0.961591928e-2f +
  3886. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3887. // error 2.47208000*10^(-7), which is better than 18 bits
  3888. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3889. getF32Constant(DAG, 0x3924b03e));
  3890. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3891. getF32Constant(DAG, 0x3ab24b87));
  3892. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3893. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3894. getF32Constant(DAG, 0x3c1d8c17));
  3895. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3896. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3897. getF32Constant(DAG, 0x3d634a1d));
  3898. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3899. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3900. getF32Constant(DAG, 0x3e75fe14));
  3901. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3902. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3903. getF32Constant(DAG, 0x3f317234));
  3904. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3905. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3906. getF32Constant(DAG, 0x3f800000));
  3907. }
  3908. SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
  3909. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3910. DAG.getNode(ISD::ADD, dl, MVT::i32,
  3911. t13, IntegerPartOfX));
  3912. }
  3913. // No special expansion.
  3914. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  3915. }
  3916. /// ExpandPowI - Expand a llvm.powi intrinsic.
  3917. static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
  3918. SelectionDAG &DAG) {
  3919. // If RHS is a constant, we can expand this out to a multiplication tree,
  3920. // otherwise we end up lowering to a call to __powidf2 (for example). When
  3921. // optimizing for size, we only want to do this if the expansion would produce
  3922. // a small number of multiplies, otherwise we do the full expansion.
  3923. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  3924. // Get the exponent as a positive value.
  3925. unsigned Val = RHSC->getSExtValue();
  3926. if ((int)Val < 0) Val = -Val;
  3927. // powi(x, 0) -> 1.0
  3928. if (Val == 0)
  3929. return DAG.getConstantFP(1.0, LHS.getValueType());
  3930. const Function *F = DAG.getMachineFunction().getFunction();
  3931. if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  3932. Attribute::OptimizeForSize) ||
  3933. // If optimizing for size, don't insert too many multiplies. This
  3934. // inserts up to 5 multiplies.
  3935. CountPopulation_32(Val)+Log2_32(Val) < 7) {
  3936. // We use the simple binary decomposition method to generate the multiply
  3937. // sequence. There are more optimal ways to do this (for example,
  3938. // powi(x,15) generates one more multiply than it should), but this has
  3939. // the benefit of being both really simple and much better than a libcall.
  3940. SDValue Res; // Logically starts equal to 1.0
  3941. SDValue CurSquare = LHS;
  3942. while (Val) {
  3943. if (Val & 1) {
  3944. if (Res.getNode())
  3945. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  3946. else
  3947. Res = CurSquare; // 1.0*CurSquare.
  3948. }
  3949. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  3950. CurSquare, CurSquare);
  3951. Val >>= 1;
  3952. }
  3953. // If the original was negative, invert the result, producing 1/(x*x*x).
  3954. if (RHSC->getSExtValue() < 0)
  3955. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  3956. DAG.getConstantFP(1.0, LHS.getValueType()), Res);
  3957. return Res;
  3958. }
  3959. }
  3960. // Otherwise, expand to a libcall.
  3961. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  3962. }
  3963. // getTruncatedArgReg - Find underlying register used for an truncated
  3964. // argument.
  3965. static unsigned getTruncatedArgReg(const SDValue &N) {
  3966. if (N.getOpcode() != ISD::TRUNCATE)
  3967. return 0;
  3968. const SDValue &Ext = N.getOperand(0);
  3969. if (Ext.getOpcode() == ISD::AssertZext ||
  3970. Ext.getOpcode() == ISD::AssertSext) {
  3971. const SDValue &CFR = Ext.getOperand(0);
  3972. if (CFR.getOpcode() == ISD::CopyFromReg)
  3973. return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
  3974. if (CFR.getOpcode() == ISD::TRUNCATE)
  3975. return getTruncatedArgReg(CFR);
  3976. }
  3977. return 0;
  3978. }
  3979. /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
  3980. /// argument, create the corresponding DBG_VALUE machine instruction for it now.
  3981. /// At the end of instruction selection, they will be inserted to the entry BB.
  3982. bool
  3983. SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
  3984. int64_t Offset, bool IsIndirect,
  3985. const SDValue &N) {
  3986. const Argument *Arg = dyn_cast<Argument>(V);
  3987. if (!Arg)
  3988. return false;
  3989. MachineFunction &MF = DAG.getMachineFunction();
  3990. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  3991. // Ignore inlined function arguments here.
  3992. DIVariable DV(Variable);
  3993. if (DV.isInlinedFnArgument(MF.getFunction()))
  3994. return false;
  3995. Optional<MachineOperand> Op;
  3996. // Some arguments' frame index is recorded during argument lowering.
  3997. if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
  3998. Op = MachineOperand::CreateFI(FI);
  3999. if (!Op && N.getNode()) {
  4000. unsigned Reg;
  4001. if (N.getOpcode() == ISD::CopyFromReg)
  4002. Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4003. else
  4004. Reg = getTruncatedArgReg(N);
  4005. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4006. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4007. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4008. if (PR)
  4009. Reg = PR;
  4010. }
  4011. if (Reg)
  4012. Op = MachineOperand::CreateReg(Reg, false);
  4013. }
  4014. if (!Op) {
  4015. // Check if ValueMap has reg number.
  4016. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4017. if (VMI != FuncInfo.ValueMap.end())
  4018. Op = MachineOperand::CreateReg(VMI->second, false);
  4019. }
  4020. if (!Op && N.getNode())
  4021. // Check if frame index is available.
  4022. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  4023. if (FrameIndexSDNode *FINode =
  4024. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4025. Op = MachineOperand::CreateFI(FINode->getIndex());
  4026. if (!Op)
  4027. return false;
  4028. if (Op->isReg())
  4029. FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
  4030. TII->get(TargetOpcode::DBG_VALUE),
  4031. IsIndirect,
  4032. Op->getReg(), Offset, Variable));
  4033. else
  4034. FuncInfo.ArgDbgValues.push_back(
  4035. BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
  4036. .addOperand(*Op).addImm(Offset).addMetadata(Variable));
  4037. return true;
  4038. }
  4039. // VisualStudio defines setjmp as _setjmp
  4040. #if defined(_MSC_VER) && defined(setjmp) && \
  4041. !defined(setjmp_undefined_for_msvc)
  4042. # pragma push_macro("setjmp")
  4043. # undef setjmp
  4044. # define setjmp_undefined_for_msvc
  4045. #endif
  4046. /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
  4047. /// we want to emit this as a call to a named external function, return the name
  4048. /// otherwise lower it and return null.
  4049. const char *
  4050. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  4051. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  4052. SDLoc sdl = getCurSDLoc();
  4053. DebugLoc dl = getCurDebugLoc();
  4054. SDValue Res;
  4055. switch (Intrinsic) {
  4056. default:
  4057. // By default, turn this into a target intrinsic node.
  4058. visitTargetIntrinsic(I, Intrinsic);
  4059. return nullptr;
  4060. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  4061. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  4062. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  4063. case Intrinsic::returnaddress:
  4064. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
  4065. getValue(I.getArgOperand(0))));
  4066. return nullptr;
  4067. case Intrinsic::frameaddress:
  4068. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
  4069. getValue(I.getArgOperand(0))));
  4070. return nullptr;
  4071. case Intrinsic::read_register: {
  4072. Value *Reg = I.getArgOperand(0);
  4073. SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
  4074. EVT VT =
  4075. TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
  4076. setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
  4077. return nullptr;
  4078. }
  4079. case Intrinsic::write_register: {
  4080. Value *Reg = I.getArgOperand(0);
  4081. Value *RegValue = I.getArgOperand(1);
  4082. SDValue Chain = getValue(RegValue).getOperand(0);
  4083. SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
  4084. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4085. RegName, getValue(RegValue)));
  4086. return nullptr;
  4087. }
  4088. case Intrinsic::setjmp:
  4089. return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
  4090. case Intrinsic::longjmp:
  4091. return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
  4092. case Intrinsic::memcpy: {
  4093. // Assert for address < 256 since we support only user defined address
  4094. // spaces.
  4095. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  4096. < 256 &&
  4097. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  4098. < 256 &&
  4099. "Unknown address space");
  4100. SDValue Op1 = getValue(I.getArgOperand(0));
  4101. SDValue Op2 = getValue(I.getArgOperand(1));
  4102. SDValue Op3 = getValue(I.getArgOperand(2));
  4103. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4104. if (!Align)
  4105. Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4106. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4107. DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
  4108. MachinePointerInfo(I.getArgOperand(0)),
  4109. MachinePointerInfo(I.getArgOperand(1))));
  4110. return nullptr;
  4111. }
  4112. case Intrinsic::memset: {
  4113. // Assert for address < 256 since we support only user defined address
  4114. // spaces.
  4115. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  4116. < 256 &&
  4117. "Unknown address space");
  4118. SDValue Op1 = getValue(I.getArgOperand(0));
  4119. SDValue Op2 = getValue(I.getArgOperand(1));
  4120. SDValue Op3 = getValue(I.getArgOperand(2));
  4121. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4122. if (!Align)
  4123. Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
  4124. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4125. DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4126. MachinePointerInfo(I.getArgOperand(0))));
  4127. return nullptr;
  4128. }
  4129. case Intrinsic::memmove: {
  4130. // Assert for address < 256 since we support only user defined address
  4131. // spaces.
  4132. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  4133. < 256 &&
  4134. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  4135. < 256 &&
  4136. "Unknown address space");
  4137. SDValue Op1 = getValue(I.getArgOperand(0));
  4138. SDValue Op2 = getValue(I.getArgOperand(1));
  4139. SDValue Op3 = getValue(I.getArgOperand(2));
  4140. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4141. if (!Align)
  4142. Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4143. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4144. DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4145. MachinePointerInfo(I.getArgOperand(0)),
  4146. MachinePointerInfo(I.getArgOperand(1))));
  4147. return nullptr;
  4148. }
  4149. case Intrinsic::dbg_declare: {
  4150. const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
  4151. MDNode *Variable = DI.getVariable();
  4152. const Value *Address = DI.getAddress();
  4153. DIVariable DIVar(Variable);
  4154. assert((!DIVar || DIVar.isVariable()) &&
  4155. "Variable in DbgDeclareInst should be either null or a DIVariable.");
  4156. if (!Address || !DIVar) {
  4157. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4158. return nullptr;
  4159. }
  4160. // Check if address has undef value.
  4161. if (isa<UndefValue>(Address) ||
  4162. (Address->use_empty() && !isa<Argument>(Address))) {
  4163. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4164. return nullptr;
  4165. }
  4166. SDValue &N = NodeMap[Address];
  4167. if (!N.getNode() && isa<Argument>(Address))
  4168. // Check unused arguments map.
  4169. N = UnusedArgNodeMap[Address];
  4170. SDDbgValue *SDV;
  4171. if (N.getNode()) {
  4172. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  4173. Address = BCI->getOperand(0);
  4174. // Parameters are handled specially.
  4175. bool isParameter =
  4176. (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
  4177. isa<Argument>(Address));
  4178. const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
  4179. if (isParameter && !AI) {
  4180. FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  4181. if (FINode)
  4182. // Byval parameter. We have a frame index at this point.
  4183. SDV = DAG.getFrameIndexDbgValue(Variable, FINode->getIndex(),
  4184. 0, dl, SDNodeOrder);
  4185. else {
  4186. // Address is an argument, so try to emit its dbg value using
  4187. // virtual register info from the FuncInfo.ValueMap.
  4188. EmitFuncArgumentDbgValue(Address, Variable, 0, false, N);
  4189. return nullptr;
  4190. }
  4191. } else if (AI)
  4192. SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
  4193. true, 0, dl, SDNodeOrder);
  4194. else {
  4195. // Can't do anything with other non-AI cases yet.
  4196. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4197. DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
  4198. DEBUG(Address->dump());
  4199. return nullptr;
  4200. }
  4201. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  4202. } else {
  4203. // If Address is an argument then try to emit its dbg value using
  4204. // virtual register info from the FuncInfo.ValueMap.
  4205. if (!EmitFuncArgumentDbgValue(Address, Variable, 0, false, N)) {
  4206. // If variable is pinned by a alloca in dominating bb then
  4207. // use StaticAllocaMap.
  4208. if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
  4209. if (AI->getParent() != DI.getParent()) {
  4210. DenseMap<const AllocaInst*, int>::iterator SI =
  4211. FuncInfo.StaticAllocaMap.find(AI);
  4212. if (SI != FuncInfo.StaticAllocaMap.end()) {
  4213. SDV = DAG.getFrameIndexDbgValue(Variable, SI->second,
  4214. 0, dl, SDNodeOrder);
  4215. DAG.AddDbgValue(SDV, nullptr, false);
  4216. return nullptr;
  4217. }
  4218. }
  4219. }
  4220. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4221. }
  4222. }
  4223. return nullptr;
  4224. }
  4225. case Intrinsic::dbg_value: {
  4226. const DbgValueInst &DI = cast<DbgValueInst>(I);
  4227. DIVariable DIVar(DI.getVariable());
  4228. assert((!DIVar || DIVar.isVariable()) &&
  4229. "Variable in DbgValueInst should be either null or a DIVariable.");
  4230. if (!DIVar)
  4231. return nullptr;
  4232. MDNode *Variable = DI.getVariable();
  4233. uint64_t Offset = DI.getOffset();
  4234. const Value *V = DI.getValue();
  4235. if (!V)
  4236. return nullptr;
  4237. SDDbgValue *SDV;
  4238. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
  4239. SDV = DAG.getConstantDbgValue(Variable, V, Offset, dl, SDNodeOrder);
  4240. DAG.AddDbgValue(SDV, nullptr, false);
  4241. } else {
  4242. // Do not use getValue() in here; we don't want to generate code at
  4243. // this point if it hasn't been done yet.
  4244. SDValue N = NodeMap[V];
  4245. if (!N.getNode() && isa<Argument>(V))
  4246. // Check unused arguments map.
  4247. N = UnusedArgNodeMap[V];
  4248. if (N.getNode()) {
  4249. // A dbg.value for an alloca is always indirect.
  4250. bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
  4251. if (!EmitFuncArgumentDbgValue(V, Variable, Offset, IsIndirect, N)) {
  4252. SDV = DAG.getDbgValue(Variable, N.getNode(),
  4253. N.getResNo(), IsIndirect,
  4254. Offset, dl, SDNodeOrder);
  4255. DAG.AddDbgValue(SDV, N.getNode(), false);
  4256. }
  4257. } else if (!V->use_empty() ) {
  4258. // Do not call getValue(V) yet, as we don't want to generate code.
  4259. // Remember it for later.
  4260. DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
  4261. DanglingDebugInfoMap[V] = DDI;
  4262. } else {
  4263. // We may expand this to cover more cases. One case where we have no
  4264. // data available is an unreferenced parameter.
  4265. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4266. }
  4267. }
  4268. // Build a debug info table entry.
  4269. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
  4270. V = BCI->getOperand(0);
  4271. const AllocaInst *AI = dyn_cast<AllocaInst>(V);
  4272. // Don't handle byval struct arguments or VLAs, for example.
  4273. if (!AI) {
  4274. DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
  4275. DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
  4276. return nullptr;
  4277. }
  4278. DenseMap<const AllocaInst*, int>::iterator SI =
  4279. FuncInfo.StaticAllocaMap.find(AI);
  4280. if (SI == FuncInfo.StaticAllocaMap.end())
  4281. return nullptr; // VLAs.
  4282. return nullptr;
  4283. }
  4284. case Intrinsic::eh_typeid_for: {
  4285. // Find the type id for the given typeinfo.
  4286. GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
  4287. unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
  4288. Res = DAG.getConstant(TypeID, MVT::i32);
  4289. setValue(&I, Res);
  4290. return nullptr;
  4291. }
  4292. case Intrinsic::eh_return_i32:
  4293. case Intrinsic::eh_return_i64:
  4294. DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
  4295. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  4296. MVT::Other,
  4297. getControlRoot(),
  4298. getValue(I.getArgOperand(0)),
  4299. getValue(I.getArgOperand(1))));
  4300. return nullptr;
  4301. case Intrinsic::eh_unwind_init:
  4302. DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
  4303. return nullptr;
  4304. case Intrinsic::eh_dwarf_cfa: {
  4305. SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
  4306. TLI->getPointerTy());
  4307. SDValue Offset = DAG.getNode(ISD::ADD, sdl,
  4308. CfaArg.getValueType(),
  4309. DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
  4310. CfaArg.getValueType()),
  4311. CfaArg);
  4312. SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
  4313. TLI->getPointerTy(),
  4314. DAG.getConstant(0, TLI->getPointerTy()));
  4315. setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
  4316. FA, Offset));
  4317. return nullptr;
  4318. }
  4319. case Intrinsic::eh_sjlj_callsite: {
  4320. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4321. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  4322. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  4323. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  4324. MMI.setCurrentCallSite(CI->getZExtValue());
  4325. return nullptr;
  4326. }
  4327. case Intrinsic::eh_sjlj_functioncontext: {
  4328. // Get and store the index of the function context.
  4329. MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
  4330. AllocaInst *FnCtx =
  4331. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  4332. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  4333. MFI->setFunctionContextIndex(FI);
  4334. return nullptr;
  4335. }
  4336. case Intrinsic::eh_sjlj_setjmp: {
  4337. SDValue Ops[2];
  4338. Ops[0] = getRoot();
  4339. Ops[1] = getValue(I.getArgOperand(0));
  4340. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  4341. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  4342. setValue(&I, Op.getValue(0));
  4343. DAG.setRoot(Op.getValue(1));
  4344. return nullptr;
  4345. }
  4346. case Intrinsic::eh_sjlj_longjmp: {
  4347. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  4348. getRoot(), getValue(I.getArgOperand(0))));
  4349. return nullptr;
  4350. }
  4351. case Intrinsic::x86_mmx_pslli_w:
  4352. case Intrinsic::x86_mmx_pslli_d:
  4353. case Intrinsic::x86_mmx_pslli_q:
  4354. case Intrinsic::x86_mmx_psrli_w:
  4355. case Intrinsic::x86_mmx_psrli_d:
  4356. case Intrinsic::x86_mmx_psrli_q:
  4357. case Intrinsic::x86_mmx_psrai_w:
  4358. case Intrinsic::x86_mmx_psrai_d: {
  4359. SDValue ShAmt = getValue(I.getArgOperand(1));
  4360. if (isa<ConstantSDNode>(ShAmt)) {
  4361. visitTargetIntrinsic(I, Intrinsic);
  4362. return nullptr;
  4363. }
  4364. unsigned NewIntrinsic = 0;
  4365. EVT ShAmtVT = MVT::v2i32;
  4366. switch (Intrinsic) {
  4367. case Intrinsic::x86_mmx_pslli_w:
  4368. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  4369. break;
  4370. case Intrinsic::x86_mmx_pslli_d:
  4371. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  4372. break;
  4373. case Intrinsic::x86_mmx_pslli_q:
  4374. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  4375. break;
  4376. case Intrinsic::x86_mmx_psrli_w:
  4377. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  4378. break;
  4379. case Intrinsic::x86_mmx_psrli_d:
  4380. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  4381. break;
  4382. case Intrinsic::x86_mmx_psrli_q:
  4383. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  4384. break;
  4385. case Intrinsic::x86_mmx_psrai_w:
  4386. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  4387. break;
  4388. case Intrinsic::x86_mmx_psrai_d:
  4389. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  4390. break;
  4391. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4392. }
  4393. // The vector shift intrinsics with scalars uses 32b shift amounts but
  4394. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  4395. // to be zero.
  4396. // We must do this early because v2i32 is not a legal type.
  4397. SDValue ShOps[2];
  4398. ShOps[0] = ShAmt;
  4399. ShOps[1] = DAG.getConstant(0, MVT::i32);
  4400. ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
  4401. EVT DestVT = TLI->getValueType(I.getType());
  4402. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  4403. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  4404. DAG.getConstant(NewIntrinsic, MVT::i32),
  4405. getValue(I.getArgOperand(0)), ShAmt);
  4406. setValue(&I, Res);
  4407. return nullptr;
  4408. }
  4409. case Intrinsic::x86_avx_vinsertf128_pd_256:
  4410. case Intrinsic::x86_avx_vinsertf128_ps_256:
  4411. case Intrinsic::x86_avx_vinsertf128_si_256:
  4412. case Intrinsic::x86_avx2_vinserti128: {
  4413. EVT DestVT = TLI->getValueType(I.getType());
  4414. EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
  4415. uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
  4416. ElVT.getVectorNumElements();
  4417. Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
  4418. getValue(I.getArgOperand(0)),
  4419. getValue(I.getArgOperand(1)),
  4420. DAG.getConstant(Idx, TLI->getVectorIdxTy()));
  4421. setValue(&I, Res);
  4422. return nullptr;
  4423. }
  4424. case Intrinsic::x86_avx_vextractf128_pd_256:
  4425. case Intrinsic::x86_avx_vextractf128_ps_256:
  4426. case Intrinsic::x86_avx_vextractf128_si_256:
  4427. case Intrinsic::x86_avx2_vextracti128: {
  4428. EVT DestVT = TLI->getValueType(I.getType());
  4429. uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
  4430. DestVT.getVectorNumElements();
  4431. Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
  4432. getValue(I.getArgOperand(0)),
  4433. DAG.getConstant(Idx, TLI->getVectorIdxTy()));
  4434. setValue(&I, Res);
  4435. return nullptr;
  4436. }
  4437. case Intrinsic::convertff:
  4438. case Intrinsic::convertfsi:
  4439. case Intrinsic::convertfui:
  4440. case Intrinsic::convertsif:
  4441. case Intrinsic::convertuif:
  4442. case Intrinsic::convertss:
  4443. case Intrinsic::convertsu:
  4444. case Intrinsic::convertus:
  4445. case Intrinsic::convertuu: {
  4446. ISD::CvtCode Code = ISD::CVT_INVALID;
  4447. switch (Intrinsic) {
  4448. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4449. case Intrinsic::convertff: Code = ISD::CVT_FF; break;
  4450. case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
  4451. case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
  4452. case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
  4453. case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
  4454. case Intrinsic::convertss: Code = ISD::CVT_SS; break;
  4455. case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
  4456. case Intrinsic::convertus: Code = ISD::CVT_US; break;
  4457. case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
  4458. }
  4459. EVT DestVT = TLI->getValueType(I.getType());
  4460. const Value *Op1 = I.getArgOperand(0);
  4461. Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
  4462. DAG.getValueType(DestVT),
  4463. DAG.getValueType(getValue(Op1).getValueType()),
  4464. getValue(I.getArgOperand(1)),
  4465. getValue(I.getArgOperand(2)),
  4466. Code);
  4467. setValue(&I, Res);
  4468. return nullptr;
  4469. }
  4470. case Intrinsic::powi:
  4471. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  4472. getValue(I.getArgOperand(1)), DAG));
  4473. return nullptr;
  4474. case Intrinsic::log:
  4475. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4476. return nullptr;
  4477. case Intrinsic::log2:
  4478. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4479. return nullptr;
  4480. case Intrinsic::log10:
  4481. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4482. return nullptr;
  4483. case Intrinsic::exp:
  4484. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4485. return nullptr;
  4486. case Intrinsic::exp2:
  4487. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4488. return nullptr;
  4489. case Intrinsic::pow:
  4490. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  4491. getValue(I.getArgOperand(1)), DAG, *TLI));
  4492. return nullptr;
  4493. case Intrinsic::sqrt:
  4494. case Intrinsic::fabs:
  4495. case Intrinsic::sin:
  4496. case Intrinsic::cos:
  4497. case Intrinsic::floor:
  4498. case Intrinsic::ceil:
  4499. case Intrinsic::trunc:
  4500. case Intrinsic::rint:
  4501. case Intrinsic::nearbyint:
  4502. case Intrinsic::round: {
  4503. unsigned Opcode;
  4504. switch (Intrinsic) {
  4505. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4506. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  4507. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  4508. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  4509. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  4510. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  4511. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  4512. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  4513. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  4514. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  4515. case Intrinsic::round: Opcode = ISD::FROUND; break;
  4516. }
  4517. setValue(&I, DAG.getNode(Opcode, sdl,
  4518. getValue(I.getArgOperand(0)).getValueType(),
  4519. getValue(I.getArgOperand(0))));
  4520. return nullptr;
  4521. }
  4522. case Intrinsic::copysign:
  4523. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  4524. getValue(I.getArgOperand(0)).getValueType(),
  4525. getValue(I.getArgOperand(0)),
  4526. getValue(I.getArgOperand(1))));
  4527. return nullptr;
  4528. case Intrinsic::fma:
  4529. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4530. getValue(I.getArgOperand(0)).getValueType(),
  4531. getValue(I.getArgOperand(0)),
  4532. getValue(I.getArgOperand(1)),
  4533. getValue(I.getArgOperand(2))));
  4534. return nullptr;
  4535. case Intrinsic::fmuladd: {
  4536. EVT VT = TLI->getValueType(I.getType());
  4537. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  4538. TLI->isFMAFasterThanFMulAndFAdd(VT)) {
  4539. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4540. getValue(I.getArgOperand(0)).getValueType(),
  4541. getValue(I.getArgOperand(0)),
  4542. getValue(I.getArgOperand(1)),
  4543. getValue(I.getArgOperand(2))));
  4544. } else {
  4545. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  4546. getValue(I.getArgOperand(0)).getValueType(),
  4547. getValue(I.getArgOperand(0)),
  4548. getValue(I.getArgOperand(1)));
  4549. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  4550. getValue(I.getArgOperand(0)).getValueType(),
  4551. Mul,
  4552. getValue(I.getArgOperand(2)));
  4553. setValue(&I, Add);
  4554. }
  4555. return nullptr;
  4556. }
  4557. case Intrinsic::convert_to_fp16:
  4558. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  4559. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  4560. getValue(I.getArgOperand(0)),
  4561. DAG.getTargetConstant(0, MVT::i32))));
  4562. return nullptr;
  4563. case Intrinsic::convert_from_fp16:
  4564. setValue(&I,
  4565. DAG.getNode(ISD::FP_EXTEND, sdl, TLI->getValueType(I.getType()),
  4566. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  4567. getValue(I.getArgOperand(0)))));
  4568. return nullptr;
  4569. case Intrinsic::pcmarker: {
  4570. SDValue Tmp = getValue(I.getArgOperand(0));
  4571. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  4572. return nullptr;
  4573. }
  4574. case Intrinsic::readcyclecounter: {
  4575. SDValue Op = getRoot();
  4576. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  4577. DAG.getVTList(MVT::i64, MVT::Other), Op);
  4578. setValue(&I, Res);
  4579. DAG.setRoot(Res.getValue(1));
  4580. return nullptr;
  4581. }
  4582. case Intrinsic::bswap:
  4583. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  4584. getValue(I.getArgOperand(0)).getValueType(),
  4585. getValue(I.getArgOperand(0))));
  4586. return nullptr;
  4587. case Intrinsic::cttz: {
  4588. SDValue Arg = getValue(I.getArgOperand(0));
  4589. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4590. EVT Ty = Arg.getValueType();
  4591. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  4592. sdl, Ty, Arg));
  4593. return nullptr;
  4594. }
  4595. case Intrinsic::ctlz: {
  4596. SDValue Arg = getValue(I.getArgOperand(0));
  4597. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4598. EVT Ty = Arg.getValueType();
  4599. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  4600. sdl, Ty, Arg));
  4601. return nullptr;
  4602. }
  4603. case Intrinsic::ctpop: {
  4604. SDValue Arg = getValue(I.getArgOperand(0));
  4605. EVT Ty = Arg.getValueType();
  4606. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  4607. return nullptr;
  4608. }
  4609. case Intrinsic::stacksave: {
  4610. SDValue Op = getRoot();
  4611. Res = DAG.getNode(ISD::STACKSAVE, sdl,
  4612. DAG.getVTList(TLI->getPointerTy(), MVT::Other), Op);
  4613. setValue(&I, Res);
  4614. DAG.setRoot(Res.getValue(1));
  4615. return nullptr;
  4616. }
  4617. case Intrinsic::stackrestore: {
  4618. Res = getValue(I.getArgOperand(0));
  4619. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  4620. return nullptr;
  4621. }
  4622. case Intrinsic::stackprotector: {
  4623. // Emit code into the DAG to store the stack guard onto the stack.
  4624. MachineFunction &MF = DAG.getMachineFunction();
  4625. MachineFrameInfo *MFI = MF.getFrameInfo();
  4626. EVT PtrTy = TLI->getPointerTy();
  4627. SDValue Src, Chain = getRoot();
  4628. if (TLI->useLoadStackGuardNode()) {
  4629. // Emit a LOAD_STACK_GUARD node.
  4630. MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
  4631. sdl, PtrTy, Chain);
  4632. LoadInst *LI = cast<LoadInst>(I.getArgOperand(0));
  4633. MachinePointerInfo MPInfo(LI->getPointerOperand());
  4634. MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
  4635. unsigned Flags = MachineMemOperand::MOLoad |
  4636. MachineMemOperand::MOInvariant;
  4637. *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
  4638. PtrTy.getSizeInBits() / 8,
  4639. DAG.getEVTAlignment(PtrTy));
  4640. Node->setMemRefs(MemRefs, MemRefs + 1);
  4641. // Copy the guard value to a virtual register so that it can be
  4642. // retrieved in the epilogue.
  4643. Src = SDValue(Node, 0);
  4644. const TargetRegisterClass *RC =
  4645. TLI->getRegClassFor(Src.getSimpleValueType());
  4646. unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
  4647. SPDescriptor.setGuardReg(Reg);
  4648. Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
  4649. } else {
  4650. Src = getValue(I.getArgOperand(0)); // The guard's value.
  4651. }
  4652. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  4653. int FI = FuncInfo.StaticAllocaMap[Slot];
  4654. MFI->setStackProtectorIndex(FI);
  4655. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  4656. // Store the stack protector onto the stack.
  4657. Res = DAG.getStore(Chain, sdl, Src, FIN,
  4658. MachinePointerInfo::getFixedStack(FI),
  4659. true, false, 0);
  4660. setValue(&I, Res);
  4661. DAG.setRoot(Res);
  4662. return nullptr;
  4663. }
  4664. case Intrinsic::objectsize: {
  4665. // If we don't know by now, we're never going to know.
  4666. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  4667. assert(CI && "Non-constant type in __builtin_object_size?");
  4668. SDValue Arg = getValue(I.getCalledValue());
  4669. EVT Ty = Arg.getValueType();
  4670. if (CI->isZero())
  4671. Res = DAG.getConstant(-1ULL, Ty);
  4672. else
  4673. Res = DAG.getConstant(0, Ty);
  4674. setValue(&I, Res);
  4675. return nullptr;
  4676. }
  4677. case Intrinsic::annotation:
  4678. case Intrinsic::ptr_annotation:
  4679. // Drop the intrinsic, but forward the value
  4680. setValue(&I, getValue(I.getOperand(0)));
  4681. return nullptr;
  4682. case Intrinsic::assume:
  4683. case Intrinsic::var_annotation:
  4684. // Discard annotate attributes and assumptions
  4685. return nullptr;
  4686. case Intrinsic::init_trampoline: {
  4687. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  4688. SDValue Ops[6];
  4689. Ops[0] = getRoot();
  4690. Ops[1] = getValue(I.getArgOperand(0));
  4691. Ops[2] = getValue(I.getArgOperand(1));
  4692. Ops[3] = getValue(I.getArgOperand(2));
  4693. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  4694. Ops[5] = DAG.getSrcValue(F);
  4695. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  4696. DAG.setRoot(Res);
  4697. return nullptr;
  4698. }
  4699. case Intrinsic::adjust_trampoline: {
  4700. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  4701. TLI->getPointerTy(),
  4702. getValue(I.getArgOperand(0))));
  4703. return nullptr;
  4704. }
  4705. case Intrinsic::gcroot:
  4706. if (GFI) {
  4707. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  4708. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  4709. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  4710. GFI->addStackRoot(FI->getIndex(), TypeMap);
  4711. }
  4712. return nullptr;
  4713. case Intrinsic::gcread:
  4714. case Intrinsic::gcwrite:
  4715. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  4716. case Intrinsic::flt_rounds:
  4717. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  4718. return nullptr;
  4719. case Intrinsic::expect: {
  4720. // Just replace __builtin_expect(exp, c) with EXP.
  4721. setValue(&I, getValue(I.getArgOperand(0)));
  4722. return nullptr;
  4723. }
  4724. case Intrinsic::debugtrap:
  4725. case Intrinsic::trap: {
  4726. StringRef TrapFuncName = TM.Options.getTrapFunctionName();
  4727. if (TrapFuncName.empty()) {
  4728. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  4729. ISD::TRAP : ISD::DEBUGTRAP;
  4730. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  4731. return nullptr;
  4732. }
  4733. TargetLowering::ArgListTy Args;
  4734. TargetLowering::CallLoweringInfo CLI(DAG);
  4735. CLI.setDebugLoc(sdl).setChain(getRoot())
  4736. .setCallee(CallingConv::C, I.getType(),
  4737. DAG.getExternalSymbol(TrapFuncName.data(), TLI->getPointerTy()),
  4738. std::move(Args), 0);
  4739. std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
  4740. DAG.setRoot(Result.second);
  4741. return nullptr;
  4742. }
  4743. case Intrinsic::uadd_with_overflow:
  4744. case Intrinsic::sadd_with_overflow:
  4745. case Intrinsic::usub_with_overflow:
  4746. case Intrinsic::ssub_with_overflow:
  4747. case Intrinsic::umul_with_overflow:
  4748. case Intrinsic::smul_with_overflow: {
  4749. ISD::NodeType Op;
  4750. switch (Intrinsic) {
  4751. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4752. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  4753. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  4754. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  4755. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  4756. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  4757. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  4758. }
  4759. SDValue Op1 = getValue(I.getArgOperand(0));
  4760. SDValue Op2 = getValue(I.getArgOperand(1));
  4761. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  4762. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  4763. return nullptr;
  4764. }
  4765. case Intrinsic::prefetch: {
  4766. SDValue Ops[5];
  4767. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  4768. Ops[0] = getRoot();
  4769. Ops[1] = getValue(I.getArgOperand(0));
  4770. Ops[2] = getValue(I.getArgOperand(1));
  4771. Ops[3] = getValue(I.getArgOperand(2));
  4772. Ops[4] = getValue(I.getArgOperand(3));
  4773. DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  4774. DAG.getVTList(MVT::Other), Ops,
  4775. EVT::getIntegerVT(*Context, 8),
  4776. MachinePointerInfo(I.getArgOperand(0)),
  4777. 0, /* align */
  4778. false, /* volatile */
  4779. rw==0, /* read */
  4780. rw==1)); /* write */
  4781. return nullptr;
  4782. }
  4783. case Intrinsic::lifetime_start:
  4784. case Intrinsic::lifetime_end: {
  4785. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  4786. // Stack coloring is not enabled in O0, discard region information.
  4787. if (TM.getOptLevel() == CodeGenOpt::None)
  4788. return nullptr;
  4789. SmallVector<Value *, 4> Allocas;
  4790. GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
  4791. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  4792. E = Allocas.end(); Object != E; ++Object) {
  4793. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  4794. // Could not find an Alloca.
  4795. if (!LifetimeObject)
  4796. continue;
  4797. int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
  4798. SDValue Ops[2];
  4799. Ops[0] = getRoot();
  4800. Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
  4801. unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
  4802. Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
  4803. DAG.setRoot(Res);
  4804. }
  4805. return nullptr;
  4806. }
  4807. case Intrinsic::invariant_start:
  4808. // Discard region information.
  4809. setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
  4810. return nullptr;
  4811. case Intrinsic::invariant_end:
  4812. // Discard region information.
  4813. return nullptr;
  4814. case Intrinsic::stackprotectorcheck: {
  4815. // Do not actually emit anything for this basic block. Instead we initialize
  4816. // the stack protector descriptor and export the guard variable so we can
  4817. // access it in FinishBasicBlock.
  4818. const BasicBlock *BB = I.getParent();
  4819. SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
  4820. ExportFromCurrentBlock(SPDescriptor.getGuard());
  4821. // Flush our exports since we are going to process a terminator.
  4822. (void)getControlRoot();
  4823. return nullptr;
  4824. }
  4825. case Intrinsic::clear_cache:
  4826. return TLI->getClearCacheBuiltinName();
  4827. case Intrinsic::donothing:
  4828. // ignore
  4829. return nullptr;
  4830. case Intrinsic::experimental_stackmap: {
  4831. visitStackmap(I);
  4832. return nullptr;
  4833. }
  4834. case Intrinsic::experimental_patchpoint_void:
  4835. case Intrinsic::experimental_patchpoint_i64: {
  4836. visitPatchpoint(I);
  4837. return nullptr;
  4838. }
  4839. }
  4840. }
  4841. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  4842. bool isTailCall,
  4843. MachineBasicBlock *LandingPad) {
  4844. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  4845. PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
  4846. FunctionType *FTy = cast<FunctionType>(PT->getElementType());
  4847. Type *RetTy = FTy->getReturnType();
  4848. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4849. MCSymbol *BeginLabel = nullptr;
  4850. TargetLowering::ArgListTy Args;
  4851. TargetLowering::ArgListEntry Entry;
  4852. Args.reserve(CS.arg_size());
  4853. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  4854. i != e; ++i) {
  4855. const Value *V = *i;
  4856. // Skip empty types
  4857. if (V->getType()->isEmptyTy())
  4858. continue;
  4859. SDValue ArgNode = getValue(V);
  4860. Entry.Node = ArgNode; Entry.Ty = V->getType();
  4861. // Skip the first return-type Attribute to get to params.
  4862. Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
  4863. Args.push_back(Entry);
  4864. }
  4865. if (LandingPad) {
  4866. // Insert a label before the invoke call to mark the try range. This can be
  4867. // used to detect deletion of the invoke via the MachineModuleInfo.
  4868. BeginLabel = MMI.getContext().CreateTempSymbol();
  4869. // For SjLj, keep track of which landing pads go with which invokes
  4870. // so as to maintain the ordering of pads in the LSDA.
  4871. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  4872. if (CallSiteIndex) {
  4873. MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  4874. LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
  4875. // Now that the call site is handled, stop tracking it.
  4876. MMI.setCurrentCallSite(0);
  4877. }
  4878. // Both PendingLoads and PendingExports must be flushed here;
  4879. // this call might not return.
  4880. (void)getRoot();
  4881. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  4882. }
  4883. // Check if target-independent constraints permit a tail call here.
  4884. // Target-dependent constraints are checked within TLI->LowerCallTo.
  4885. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  4886. isTailCall = false;
  4887. TargetLowering::CallLoweringInfo CLI(DAG);
  4888. CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
  4889. .setCallee(RetTy, FTy, Callee, std::move(Args), CS).setTailCall(isTailCall);
  4890. std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
  4891. assert((isTailCall || Result.second.getNode()) &&
  4892. "Non-null chain expected with non-tail call!");
  4893. assert((Result.second.getNode() || !Result.first.getNode()) &&
  4894. "Null value expected with tail call!");
  4895. if (Result.first.getNode())
  4896. setValue(CS.getInstruction(), Result.first);
  4897. if (!Result.second.getNode()) {
  4898. // As a special case, a null chain means that a tail call has been emitted
  4899. // and the DAG root is already updated.
  4900. HasTailCall = true;
  4901. // Since there's no actual continuation from this block, nothing can be
  4902. // relying on us setting vregs for them.
  4903. PendingExports.clear();
  4904. } else {
  4905. DAG.setRoot(Result.second);
  4906. }
  4907. if (LandingPad) {
  4908. // Insert a label at the end of the invoke call to mark the try range. This
  4909. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  4910. MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
  4911. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  4912. // Inform MachineModuleInfo of range.
  4913. MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
  4914. }
  4915. }
  4916. /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
  4917. /// value is equal or not-equal to zero.
  4918. static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
  4919. for (const User *U : V->users()) {
  4920. if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
  4921. if (IC->isEquality())
  4922. if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  4923. if (C->isNullValue())
  4924. continue;
  4925. // Unknown instruction.
  4926. return false;
  4927. }
  4928. return true;
  4929. }
  4930. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  4931. Type *LoadTy,
  4932. SelectionDAGBuilder &Builder) {
  4933. // Check to see if this load can be trivially constant folded, e.g. if the
  4934. // input is from a string literal.
  4935. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  4936. // Cast pointer to the type we really want to load.
  4937. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  4938. PointerType::getUnqual(LoadTy));
  4939. if (const Constant *LoadCst =
  4940. ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
  4941. Builder.DL))
  4942. return Builder.getValue(LoadCst);
  4943. }
  4944. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  4945. // still constant memory, the input chain can be the entry node.
  4946. SDValue Root;
  4947. bool ConstantMemory = false;
  4948. // Do not serialize (non-volatile) loads of constant memory with anything.
  4949. if (Builder.AA->pointsToConstantMemory(PtrVal)) {
  4950. Root = Builder.DAG.getEntryNode();
  4951. ConstantMemory = true;
  4952. } else {
  4953. // Do not serialize non-volatile loads against each other.
  4954. Root = Builder.DAG.getRoot();
  4955. }
  4956. SDValue Ptr = Builder.getValue(PtrVal);
  4957. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  4958. Ptr, MachinePointerInfo(PtrVal),
  4959. false /*volatile*/,
  4960. false /*nontemporal*/,
  4961. false /*isinvariant*/, 1 /* align=1 */);
  4962. if (!ConstantMemory)
  4963. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  4964. return LoadVal;
  4965. }
  4966. /// processIntegerCallValue - Record the value for an instruction that
  4967. /// produces an integer result, converting the type where necessary.
  4968. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  4969. SDValue Value,
  4970. bool IsSigned) {
  4971. EVT VT = TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType(),
  4972. true);
  4973. if (IsSigned)
  4974. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  4975. else
  4976. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  4977. setValue(&I, Value);
  4978. }
  4979. /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
  4980. /// If so, return true and lower it, otherwise return false and it will be
  4981. /// lowered like a normal call.
  4982. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  4983. // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
  4984. if (I.getNumArgOperands() != 3)
  4985. return false;
  4986. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  4987. if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
  4988. !I.getArgOperand(2)->getType()->isIntegerTy() ||
  4989. !I.getType()->isIntegerTy())
  4990. return false;
  4991. const Value *Size = I.getArgOperand(2);
  4992. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  4993. if (CSize && CSize->getZExtValue() == 0) {
  4994. EVT CallVT = TM.getSubtargetImpl()->getTargetLowering()->getValueType(
  4995. I.getType(), true);
  4996. setValue(&I, DAG.getConstant(0, CallVT));
  4997. return true;
  4998. }
  4999. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5000. std::pair<SDValue, SDValue> Res =
  5001. TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5002. getValue(LHS), getValue(RHS), getValue(Size),
  5003. MachinePointerInfo(LHS),
  5004. MachinePointerInfo(RHS));
  5005. if (Res.first.getNode()) {
  5006. processIntegerCallValue(I, Res.first, true);
  5007. PendingLoads.push_back(Res.second);
  5008. return true;
  5009. }
  5010. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  5011. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  5012. if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
  5013. bool ActuallyDoIt = true;
  5014. MVT LoadVT;
  5015. Type *LoadTy;
  5016. switch (CSize->getZExtValue()) {
  5017. default:
  5018. LoadVT = MVT::Other;
  5019. LoadTy = nullptr;
  5020. ActuallyDoIt = false;
  5021. break;
  5022. case 2:
  5023. LoadVT = MVT::i16;
  5024. LoadTy = Type::getInt16Ty(CSize->getContext());
  5025. break;
  5026. case 4:
  5027. LoadVT = MVT::i32;
  5028. LoadTy = Type::getInt32Ty(CSize->getContext());
  5029. break;
  5030. case 8:
  5031. LoadVT = MVT::i64;
  5032. LoadTy = Type::getInt64Ty(CSize->getContext());
  5033. break;
  5034. /*
  5035. case 16:
  5036. LoadVT = MVT::v4i32;
  5037. LoadTy = Type::getInt32Ty(CSize->getContext());
  5038. LoadTy = VectorType::get(LoadTy, 4);
  5039. break;
  5040. */
  5041. }
  5042. // This turns into unaligned loads. We only do this if the target natively
  5043. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  5044. // we'll only produce a small number of byte loads.
  5045. // Require that we can find a legal MVT, and only do this if the target
  5046. // supports unaligned loads of that type. Expanding into byte loads would
  5047. // bloat the code.
  5048. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  5049. if (ActuallyDoIt && CSize->getZExtValue() > 4) {
  5050. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  5051. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  5052. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  5053. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  5054. // TODO: Check alignment of src and dest ptrs.
  5055. if (!TLI->isTypeLegal(LoadVT) ||
  5056. !TLI->allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
  5057. !TLI->allowsMisalignedMemoryAccesses(LoadVT, DstAS))
  5058. ActuallyDoIt = false;
  5059. }
  5060. if (ActuallyDoIt) {
  5061. SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
  5062. SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
  5063. SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
  5064. ISD::SETNE);
  5065. processIntegerCallValue(I, Res, false);
  5066. return true;
  5067. }
  5068. }
  5069. return false;
  5070. }
  5071. /// visitMemChrCall -- See if we can lower a memchr call into an optimized
  5072. /// form. If so, return true and lower it, otherwise return false and it
  5073. /// will be lowered like a normal call.
  5074. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  5075. // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
  5076. if (I.getNumArgOperands() != 3)
  5077. return false;
  5078. const Value *Src = I.getArgOperand(0);
  5079. const Value *Char = I.getArgOperand(1);
  5080. const Value *Length = I.getArgOperand(2);
  5081. if (!Src->getType()->isPointerTy() ||
  5082. !Char->getType()->isIntegerTy() ||
  5083. !Length->getType()->isIntegerTy() ||
  5084. !I.getType()->isPointerTy())
  5085. return false;
  5086. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5087. std::pair<SDValue, SDValue> Res =
  5088. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  5089. getValue(Src), getValue(Char), getValue(Length),
  5090. MachinePointerInfo(Src));
  5091. if (Res.first.getNode()) {
  5092. setValue(&I, Res.first);
  5093. PendingLoads.push_back(Res.second);
  5094. return true;
  5095. }
  5096. return false;
  5097. }
  5098. /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
  5099. /// optimized form. If so, return true and lower it, otherwise return false
  5100. /// and it will be lowered like a normal call.
  5101. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  5102. // Verify that the prototype makes sense. char *strcpy(char *, char *)
  5103. if (I.getNumArgOperands() != 2)
  5104. return false;
  5105. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5106. if (!Arg0->getType()->isPointerTy() ||
  5107. !Arg1->getType()->isPointerTy() ||
  5108. !I.getType()->isPointerTy())
  5109. return false;
  5110. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5111. std::pair<SDValue, SDValue> Res =
  5112. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  5113. getValue(Arg0), getValue(Arg1),
  5114. MachinePointerInfo(Arg0),
  5115. MachinePointerInfo(Arg1), isStpcpy);
  5116. if (Res.first.getNode()) {
  5117. setValue(&I, Res.first);
  5118. DAG.setRoot(Res.second);
  5119. return true;
  5120. }
  5121. return false;
  5122. }
  5123. /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
  5124. /// If so, return true and lower it, otherwise return false and it will be
  5125. /// lowered like a normal call.
  5126. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  5127. // Verify that the prototype makes sense. int strcmp(void*,void*)
  5128. if (I.getNumArgOperands() != 2)
  5129. return false;
  5130. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5131. if (!Arg0->getType()->isPointerTy() ||
  5132. !Arg1->getType()->isPointerTy() ||
  5133. !I.getType()->isIntegerTy())
  5134. return false;
  5135. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5136. std::pair<SDValue, SDValue> Res =
  5137. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5138. getValue(Arg0), getValue(Arg1),
  5139. MachinePointerInfo(Arg0),
  5140. MachinePointerInfo(Arg1));
  5141. if (Res.first.getNode()) {
  5142. processIntegerCallValue(I, Res.first, true);
  5143. PendingLoads.push_back(Res.second);
  5144. return true;
  5145. }
  5146. return false;
  5147. }
  5148. /// visitStrLenCall -- See if we can lower a strlen call into an optimized
  5149. /// form. If so, return true and lower it, otherwise return false and it
  5150. /// will be lowered like a normal call.
  5151. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  5152. // Verify that the prototype makes sense. size_t strlen(char *)
  5153. if (I.getNumArgOperands() != 1)
  5154. return false;
  5155. const Value *Arg0 = I.getArgOperand(0);
  5156. if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
  5157. return false;
  5158. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5159. std::pair<SDValue, SDValue> Res =
  5160. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5161. getValue(Arg0), MachinePointerInfo(Arg0));
  5162. if (Res.first.getNode()) {
  5163. processIntegerCallValue(I, Res.first, false);
  5164. PendingLoads.push_back(Res.second);
  5165. return true;
  5166. }
  5167. return false;
  5168. }
  5169. /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
  5170. /// form. If so, return true and lower it, otherwise return false and it
  5171. /// will be lowered like a normal call.
  5172. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  5173. // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
  5174. if (I.getNumArgOperands() != 2)
  5175. return false;
  5176. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5177. if (!Arg0->getType()->isPointerTy() ||
  5178. !Arg1->getType()->isIntegerTy() ||
  5179. !I.getType()->isIntegerTy())
  5180. return false;
  5181. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5182. std::pair<SDValue, SDValue> Res =
  5183. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5184. getValue(Arg0), getValue(Arg1),
  5185. MachinePointerInfo(Arg0));
  5186. if (Res.first.getNode()) {
  5187. processIntegerCallValue(I, Res.first, false);
  5188. PendingLoads.push_back(Res.second);
  5189. return true;
  5190. }
  5191. return false;
  5192. }
  5193. /// visitUnaryFloatCall - If a call instruction is a unary floating-point
  5194. /// operation (as expected), translate it to an SDNode with the specified opcode
  5195. /// and return true.
  5196. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  5197. unsigned Opcode) {
  5198. // Sanity check that it really is a unary floating-point call.
  5199. if (I.getNumArgOperands() != 1 ||
  5200. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  5201. I.getType() != I.getArgOperand(0)->getType() ||
  5202. !I.onlyReadsMemory())
  5203. return false;
  5204. SDValue Tmp = getValue(I.getArgOperand(0));
  5205. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  5206. return true;
  5207. }
  5208. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  5209. // Handle inline assembly differently.
  5210. if (isa<InlineAsm>(I.getCalledValue())) {
  5211. visitInlineAsm(&I);
  5212. return;
  5213. }
  5214. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5215. ComputeUsesVAFloatArgument(I, &MMI);
  5216. const char *RenameFn = nullptr;
  5217. if (Function *F = I.getCalledFunction()) {
  5218. if (F->isDeclaration()) {
  5219. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
  5220. if (unsigned IID = II->getIntrinsicID(F)) {
  5221. RenameFn = visitIntrinsicCall(I, IID);
  5222. if (!RenameFn)
  5223. return;
  5224. }
  5225. }
  5226. if (unsigned IID = F->getIntrinsicID()) {
  5227. RenameFn = visitIntrinsicCall(I, IID);
  5228. if (!RenameFn)
  5229. return;
  5230. }
  5231. }
  5232. // Check for well-known libc/libm calls. If the function is internal, it
  5233. // can't be a library call.
  5234. LibFunc::Func Func;
  5235. if (!F->hasLocalLinkage() && F->hasName() &&
  5236. LibInfo->getLibFunc(F->getName(), Func) &&
  5237. LibInfo->hasOptimizedCodeGen(Func)) {
  5238. switch (Func) {
  5239. default: break;
  5240. case LibFunc::copysign:
  5241. case LibFunc::copysignf:
  5242. case LibFunc::copysignl:
  5243. if (I.getNumArgOperands() == 2 && // Basic sanity checks.
  5244. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  5245. I.getType() == I.getArgOperand(0)->getType() &&
  5246. I.getType() == I.getArgOperand(1)->getType() &&
  5247. I.onlyReadsMemory()) {
  5248. SDValue LHS = getValue(I.getArgOperand(0));
  5249. SDValue RHS = getValue(I.getArgOperand(1));
  5250. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  5251. LHS.getValueType(), LHS, RHS));
  5252. return;
  5253. }
  5254. break;
  5255. case LibFunc::fabs:
  5256. case LibFunc::fabsf:
  5257. case LibFunc::fabsl:
  5258. if (visitUnaryFloatCall(I, ISD::FABS))
  5259. return;
  5260. break;
  5261. case LibFunc::sin:
  5262. case LibFunc::sinf:
  5263. case LibFunc::sinl:
  5264. if (visitUnaryFloatCall(I, ISD::FSIN))
  5265. return;
  5266. break;
  5267. case LibFunc::cos:
  5268. case LibFunc::cosf:
  5269. case LibFunc::cosl:
  5270. if (visitUnaryFloatCall(I, ISD::FCOS))
  5271. return;
  5272. break;
  5273. case LibFunc::sqrt:
  5274. case LibFunc::sqrtf:
  5275. case LibFunc::sqrtl:
  5276. case LibFunc::sqrt_finite:
  5277. case LibFunc::sqrtf_finite:
  5278. case LibFunc::sqrtl_finite:
  5279. if (visitUnaryFloatCall(I, ISD::FSQRT))
  5280. return;
  5281. break;
  5282. case LibFunc::floor:
  5283. case LibFunc::floorf:
  5284. case LibFunc::floorl:
  5285. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  5286. return;
  5287. break;
  5288. case LibFunc::nearbyint:
  5289. case LibFunc::nearbyintf:
  5290. case LibFunc::nearbyintl:
  5291. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  5292. return;
  5293. break;
  5294. case LibFunc::ceil:
  5295. case LibFunc::ceilf:
  5296. case LibFunc::ceill:
  5297. if (visitUnaryFloatCall(I, ISD::FCEIL))
  5298. return;
  5299. break;
  5300. case LibFunc::rint:
  5301. case LibFunc::rintf:
  5302. case LibFunc::rintl:
  5303. if (visitUnaryFloatCall(I, ISD::FRINT))
  5304. return;
  5305. break;
  5306. case LibFunc::round:
  5307. case LibFunc::roundf:
  5308. case LibFunc::roundl:
  5309. if (visitUnaryFloatCall(I, ISD::FROUND))
  5310. return;
  5311. break;
  5312. case LibFunc::trunc:
  5313. case LibFunc::truncf:
  5314. case LibFunc::truncl:
  5315. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  5316. return;
  5317. break;
  5318. case LibFunc::log2:
  5319. case LibFunc::log2f:
  5320. case LibFunc::log2l:
  5321. if (visitUnaryFloatCall(I, ISD::FLOG2))
  5322. return;
  5323. break;
  5324. case LibFunc::exp2:
  5325. case LibFunc::exp2f:
  5326. case LibFunc::exp2l:
  5327. if (visitUnaryFloatCall(I, ISD::FEXP2))
  5328. return;
  5329. break;
  5330. case LibFunc::memcmp:
  5331. if (visitMemCmpCall(I))
  5332. return;
  5333. break;
  5334. case LibFunc::memchr:
  5335. if (visitMemChrCall(I))
  5336. return;
  5337. break;
  5338. case LibFunc::strcpy:
  5339. if (visitStrCpyCall(I, false))
  5340. return;
  5341. break;
  5342. case LibFunc::stpcpy:
  5343. if (visitStrCpyCall(I, true))
  5344. return;
  5345. break;
  5346. case LibFunc::strcmp:
  5347. if (visitStrCmpCall(I))
  5348. return;
  5349. break;
  5350. case LibFunc::strlen:
  5351. if (visitStrLenCall(I))
  5352. return;
  5353. break;
  5354. case LibFunc::strnlen:
  5355. if (visitStrNLenCall(I))
  5356. return;
  5357. break;
  5358. }
  5359. }
  5360. }
  5361. SDValue Callee;
  5362. if (!RenameFn)
  5363. Callee = getValue(I.getCalledValue());
  5364. else
  5365. Callee = DAG.getExternalSymbol(
  5366. RenameFn, TM.getSubtargetImpl()->getTargetLowering()->getPointerTy());
  5367. // Check if we can potentially perform a tail call. More detailed checking is
  5368. // be done within LowerCallTo, after more information about the call is known.
  5369. LowerCallTo(&I, Callee, I.isTailCall());
  5370. }
  5371. namespace {
  5372. /// AsmOperandInfo - This contains information for each constraint that we are
  5373. /// lowering.
  5374. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  5375. public:
  5376. /// CallOperand - If this is the result output operand or a clobber
  5377. /// this is null, otherwise it is the incoming operand to the CallInst.
  5378. /// This gets modified as the asm is processed.
  5379. SDValue CallOperand;
  5380. /// AssignedRegs - If this is a register or register class operand, this
  5381. /// contains the set of register corresponding to the operand.
  5382. RegsForValue AssignedRegs;
  5383. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  5384. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
  5385. }
  5386. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  5387. /// corresponds to. If there is no Value* for this operand, it returns
  5388. /// MVT::Other.
  5389. EVT getCallOperandValEVT(LLVMContext &Context,
  5390. const TargetLowering &TLI,
  5391. const DataLayout *DL) const {
  5392. if (!CallOperandVal) return MVT::Other;
  5393. if (isa<BasicBlock>(CallOperandVal))
  5394. return TLI.getPointerTy();
  5395. llvm::Type *OpTy = CallOperandVal->getType();
  5396. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  5397. // If this is an indirect operand, the operand is a pointer to the
  5398. // accessed type.
  5399. if (isIndirect) {
  5400. llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  5401. if (!PtrTy)
  5402. report_fatal_error("Indirect operand for inline asm not a pointer!");
  5403. OpTy = PtrTy->getElementType();
  5404. }
  5405. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  5406. if (StructType *STy = dyn_cast<StructType>(OpTy))
  5407. if (STy->getNumElements() == 1)
  5408. OpTy = STy->getElementType(0);
  5409. // If OpTy is not a single value, it may be a struct/union that we
  5410. // can tile with integers.
  5411. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  5412. unsigned BitSize = DL->getTypeSizeInBits(OpTy);
  5413. switch (BitSize) {
  5414. default: break;
  5415. case 1:
  5416. case 8:
  5417. case 16:
  5418. case 32:
  5419. case 64:
  5420. case 128:
  5421. OpTy = IntegerType::get(Context, BitSize);
  5422. break;
  5423. }
  5424. }
  5425. return TLI.getValueType(OpTy, true);
  5426. }
  5427. };
  5428. typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
  5429. } // end anonymous namespace
  5430. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  5431. /// specified operand. We prefer to assign virtual registers, to allow the
  5432. /// register allocator to handle the assignment process. However, if the asm
  5433. /// uses features that we can't model on machineinstrs, we have SDISel do the
  5434. /// allocation. This produces generally horrible, but correct, code.
  5435. ///
  5436. /// OpInfo describes the operand.
  5437. ///
  5438. static void GetRegistersForValue(SelectionDAG &DAG,
  5439. const TargetLowering &TLI,
  5440. SDLoc DL,
  5441. SDISelAsmOperandInfo &OpInfo) {
  5442. LLVMContext &Context = *DAG.getContext();
  5443. MachineFunction &MF = DAG.getMachineFunction();
  5444. SmallVector<unsigned, 4> Regs;
  5445. // If this is a constraint for a single physreg, or a constraint for a
  5446. // register class, find it.
  5447. std::pair<unsigned, const TargetRegisterClass*> PhysReg =
  5448. TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
  5449. OpInfo.ConstraintVT);
  5450. unsigned NumRegs = 1;
  5451. if (OpInfo.ConstraintVT != MVT::Other) {
  5452. // If this is a FP input in an integer register (or visa versa) insert a bit
  5453. // cast of the input value. More generally, handle any case where the input
  5454. // value disagrees with the register class we plan to stick this in.
  5455. if (OpInfo.Type == InlineAsm::isInput &&
  5456. PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
  5457. // Try to convert to the first EVT that the reg class contains. If the
  5458. // types are identical size, use a bitcast to convert (e.g. two differing
  5459. // vector types).
  5460. MVT RegVT = *PhysReg.second->vt_begin();
  5461. if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
  5462. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5463. RegVT, OpInfo.CallOperand);
  5464. OpInfo.ConstraintVT = RegVT;
  5465. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  5466. // If the input is a FP value and we want it in FP registers, do a
  5467. // bitcast to the corresponding integer type. This turns an f64 value
  5468. // into i64, which can be passed with two i32 values on a 32-bit
  5469. // machine.
  5470. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  5471. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5472. RegVT, OpInfo.CallOperand);
  5473. OpInfo.ConstraintVT = RegVT;
  5474. }
  5475. }
  5476. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  5477. }
  5478. MVT RegVT;
  5479. EVT ValueVT = OpInfo.ConstraintVT;
  5480. // If this is a constraint for a specific physical register, like {r17},
  5481. // assign it now.
  5482. if (unsigned AssignedReg = PhysReg.first) {
  5483. const TargetRegisterClass *RC = PhysReg.second;
  5484. if (OpInfo.ConstraintVT == MVT::Other)
  5485. ValueVT = *RC->vt_begin();
  5486. // Get the actual register value type. This is important, because the user
  5487. // may have asked for (e.g.) the AX register in i32 type. We need to
  5488. // remember that AX is actually i16 to get the right extension.
  5489. RegVT = *RC->vt_begin();
  5490. // This is a explicit reference to a physical register.
  5491. Regs.push_back(AssignedReg);
  5492. // If this is an expanded reference, add the rest of the regs to Regs.
  5493. if (NumRegs != 1) {
  5494. TargetRegisterClass::iterator I = RC->begin();
  5495. for (; *I != AssignedReg; ++I)
  5496. assert(I != RC->end() && "Didn't find reg!");
  5497. // Already added the first reg.
  5498. --NumRegs; ++I;
  5499. for (; NumRegs; --NumRegs, ++I) {
  5500. assert(I != RC->end() && "Ran out of registers to allocate!");
  5501. Regs.push_back(*I);
  5502. }
  5503. }
  5504. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5505. return;
  5506. }
  5507. // Otherwise, if this was a reference to an LLVM register class, create vregs
  5508. // for this reference.
  5509. if (const TargetRegisterClass *RC = PhysReg.second) {
  5510. RegVT = *RC->vt_begin();
  5511. if (OpInfo.ConstraintVT == MVT::Other)
  5512. ValueVT = RegVT;
  5513. // Create the appropriate number of virtual registers.
  5514. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  5515. for (; NumRegs; --NumRegs)
  5516. Regs.push_back(RegInfo.createVirtualRegister(RC));
  5517. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5518. return;
  5519. }
  5520. // Otherwise, we couldn't allocate enough registers for this.
  5521. }
  5522. /// visitInlineAsm - Handle a call to an InlineAsm object.
  5523. ///
  5524. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  5525. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  5526. /// ConstraintOperands - Information about all of the constraints.
  5527. SDISelAsmOperandInfoVector ConstraintOperands;
  5528. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  5529. TargetLowering::AsmOperandInfoVector
  5530. TargetConstraints = TLI->ParseConstraints(CS);
  5531. bool hasMemory = false;
  5532. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  5533. unsigned ResNo = 0; // ResNo - The result number of the next output.
  5534. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  5535. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  5536. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  5537. MVT OpVT = MVT::Other;
  5538. // Compute the value type for each operand.
  5539. switch (OpInfo.Type) {
  5540. case InlineAsm::isOutput:
  5541. // Indirect outputs just consume an argument.
  5542. if (OpInfo.isIndirect) {
  5543. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  5544. break;
  5545. }
  5546. // The return value of the call is this value. As such, there is no
  5547. // corresponding argument.
  5548. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  5549. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  5550. OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo));
  5551. } else {
  5552. assert(ResNo == 0 && "Asm only has one result!");
  5553. OpVT = TLI->getSimpleValueType(CS.getType());
  5554. }
  5555. ++ResNo;
  5556. break;
  5557. case InlineAsm::isInput:
  5558. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  5559. break;
  5560. case InlineAsm::isClobber:
  5561. // Nothing to do.
  5562. break;
  5563. }
  5564. // If this is an input or an indirect output, process the call argument.
  5565. // BasicBlocks are labels, currently appearing only in asm's.
  5566. if (OpInfo.CallOperandVal) {
  5567. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  5568. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  5569. } else {
  5570. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  5571. }
  5572. OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, DL).
  5573. getSimpleVT();
  5574. }
  5575. OpInfo.ConstraintVT = OpVT;
  5576. // Indirect operand accesses access memory.
  5577. if (OpInfo.isIndirect)
  5578. hasMemory = true;
  5579. else {
  5580. for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
  5581. TargetLowering::ConstraintType
  5582. CType = TLI->getConstraintType(OpInfo.Codes[j]);
  5583. if (CType == TargetLowering::C_Memory) {
  5584. hasMemory = true;
  5585. break;
  5586. }
  5587. }
  5588. }
  5589. }
  5590. SDValue Chain, Flag;
  5591. // We won't need to flush pending loads if this asm doesn't touch
  5592. // memory and is nonvolatile.
  5593. if (hasMemory || IA->hasSideEffects())
  5594. Chain = getRoot();
  5595. else
  5596. Chain = DAG.getRoot();
  5597. // Second pass over the constraints: compute which constraint option to use
  5598. // and assign registers to constraints that want a specific physreg.
  5599. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5600. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5601. // If this is an output operand with a matching input operand, look up the
  5602. // matching input. If their types mismatch, e.g. one is an integer, the
  5603. // other is floating point, or their sizes are different, flag it as an
  5604. // error.
  5605. if (OpInfo.hasMatchingInput()) {
  5606. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  5607. if (OpInfo.ConstraintVT != Input.ConstraintVT) {
  5608. std::pair<unsigned, const TargetRegisterClass*> MatchRC =
  5609. TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
  5610. OpInfo.ConstraintVT);
  5611. std::pair<unsigned, const TargetRegisterClass*> InputRC =
  5612. TLI->getRegForInlineAsmConstraint(Input.ConstraintCode,
  5613. Input.ConstraintVT);
  5614. if ((OpInfo.ConstraintVT.isInteger() !=
  5615. Input.ConstraintVT.isInteger()) ||
  5616. (MatchRC.second != InputRC.second)) {
  5617. report_fatal_error("Unsupported asm: input constraint"
  5618. " with a matching output constraint of"
  5619. " incompatible type!");
  5620. }
  5621. Input.ConstraintVT = OpInfo.ConstraintVT;
  5622. }
  5623. }
  5624. // Compute the constraint code and ConstraintType to use.
  5625. TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  5626. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  5627. OpInfo.Type == InlineAsm::isClobber)
  5628. continue;
  5629. // If this is a memory input, and if the operand is not indirect, do what we
  5630. // need to to provide an address for the memory input.
  5631. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  5632. !OpInfo.isIndirect) {
  5633. assert((OpInfo.isMultipleAlternative ||
  5634. (OpInfo.Type == InlineAsm::isInput)) &&
  5635. "Can only indirectify direct input operands!");
  5636. // Memory operands really want the address of the value. If we don't have
  5637. // an indirect input, put it in the constpool if we can, otherwise spill
  5638. // it to a stack slot.
  5639. // TODO: This isn't quite right. We need to handle these according to
  5640. // the addressing mode that the constraint wants. Also, this may take
  5641. // an additional register for the computation and we don't want that
  5642. // either.
  5643. // If the operand is a float, integer, or vector constant, spill to a
  5644. // constant pool entry to get its address.
  5645. const Value *OpVal = OpInfo.CallOperandVal;
  5646. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  5647. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  5648. OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
  5649. TLI->getPointerTy());
  5650. } else {
  5651. // Otherwise, create a stack slot and emit a store to it before the
  5652. // asm.
  5653. Type *Ty = OpVal->getType();
  5654. uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
  5655. unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty);
  5656. MachineFunction &MF = DAG.getMachineFunction();
  5657. int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  5658. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy());
  5659. Chain = DAG.getStore(Chain, getCurSDLoc(),
  5660. OpInfo.CallOperand, StackSlot,
  5661. MachinePointerInfo::getFixedStack(SSFI),
  5662. false, false, 0);
  5663. OpInfo.CallOperand = StackSlot;
  5664. }
  5665. // There is no longer a Value* corresponding to this operand.
  5666. OpInfo.CallOperandVal = nullptr;
  5667. // It is now an indirect operand.
  5668. OpInfo.isIndirect = true;
  5669. }
  5670. // If this constraint is for a specific register, allocate it before
  5671. // anything else.
  5672. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  5673. GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
  5674. }
  5675. // Second pass - Loop over all of the operands, assigning virtual or physregs
  5676. // to register class operands.
  5677. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5678. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5679. // C_Register operands have already been allocated, Other/Memory don't need
  5680. // to be.
  5681. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  5682. GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
  5683. }
  5684. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  5685. std::vector<SDValue> AsmNodeOperands;
  5686. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  5687. AsmNodeOperands.push_back(
  5688. DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
  5689. TLI->getPointerTy()));
  5690. // If we have a !srcloc metadata node associated with it, we want to attach
  5691. // this to the ultimately generated inline asm machineinstr. To do this, we
  5692. // pass in the third operand as this (potentially null) inline asm MDNode.
  5693. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  5694. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  5695. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  5696. // bits as operand 3.
  5697. unsigned ExtraInfo = 0;
  5698. if (IA->hasSideEffects())
  5699. ExtraInfo |= InlineAsm::Extra_HasSideEffects;
  5700. if (IA->isAlignStack())
  5701. ExtraInfo |= InlineAsm::Extra_IsAlignStack;
  5702. // Set the asm dialect.
  5703. ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  5704. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  5705. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  5706. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  5707. // Compute the constraint code and ConstraintType to use.
  5708. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  5709. // Ideally, we would only check against memory constraints. However, the
  5710. // meaning of an other constraint can be target-specific and we can't easily
  5711. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  5712. // for other constriants as well.
  5713. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  5714. OpInfo.ConstraintType == TargetLowering::C_Other) {
  5715. if (OpInfo.Type == InlineAsm::isInput)
  5716. ExtraInfo |= InlineAsm::Extra_MayLoad;
  5717. else if (OpInfo.Type == InlineAsm::isOutput)
  5718. ExtraInfo |= InlineAsm::Extra_MayStore;
  5719. else if (OpInfo.Type == InlineAsm::isClobber)
  5720. ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  5721. }
  5722. }
  5723. AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
  5724. TLI->getPointerTy()));
  5725. // Loop over all of the inputs, copying the operand values into the
  5726. // appropriate registers and processing the output regs.
  5727. RegsForValue RetValRegs;
  5728. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  5729. std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
  5730. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5731. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5732. switch (OpInfo.Type) {
  5733. case InlineAsm::isOutput: {
  5734. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  5735. OpInfo.ConstraintType != TargetLowering::C_Register) {
  5736. // Memory output, or 'other' output (e.g. 'X' constraint).
  5737. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  5738. // Add information to the INLINEASM node to know about this output.
  5739. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5740. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
  5741. TLI->getPointerTy()));
  5742. AsmNodeOperands.push_back(OpInfo.CallOperand);
  5743. break;
  5744. }
  5745. // Otherwise, this is a register or register class output.
  5746. // Copy the output from the appropriate register. Find a register that
  5747. // we can use.
  5748. if (OpInfo.AssignedRegs.Regs.empty()) {
  5749. LLVMContext &Ctx = *DAG.getContext();
  5750. Ctx.emitError(CS.getInstruction(),
  5751. "couldn't allocate output register for constraint '" +
  5752. Twine(OpInfo.ConstraintCode) + "'");
  5753. return;
  5754. }
  5755. // If this is an indirect operand, store through the pointer after the
  5756. // asm.
  5757. if (OpInfo.isIndirect) {
  5758. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  5759. OpInfo.CallOperandVal));
  5760. } else {
  5761. // This is the result value of the call.
  5762. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  5763. // Concatenate this output onto the outputs list.
  5764. RetValRegs.append(OpInfo.AssignedRegs);
  5765. }
  5766. // Add information to the INLINEASM node to know that this register is
  5767. // set.
  5768. OpInfo.AssignedRegs
  5769. .AddInlineAsmOperands(OpInfo.isEarlyClobber
  5770. ? InlineAsm::Kind_RegDefEarlyClobber
  5771. : InlineAsm::Kind_RegDef,
  5772. false, 0, DAG, AsmNodeOperands);
  5773. break;
  5774. }
  5775. case InlineAsm::isInput: {
  5776. SDValue InOperandVal = OpInfo.CallOperand;
  5777. if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
  5778. // If this is required to match an output register we have already set,
  5779. // just use its register.
  5780. unsigned OperandNo = OpInfo.getMatchedOperand();
  5781. // Scan until we find the definition we already emitted of this operand.
  5782. // When we find it, create a RegsForValue operand.
  5783. unsigned CurOp = InlineAsm::Op_FirstOperand;
  5784. for (; OperandNo; --OperandNo) {
  5785. // Advance to the next operand.
  5786. unsigned OpFlag =
  5787. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5788. assert((InlineAsm::isRegDefKind(OpFlag) ||
  5789. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  5790. InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
  5791. CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
  5792. }
  5793. unsigned OpFlag =
  5794. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5795. if (InlineAsm::isRegDefKind(OpFlag) ||
  5796. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  5797. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  5798. if (OpInfo.isIndirect) {
  5799. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  5800. LLVMContext &Ctx = *DAG.getContext();
  5801. Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
  5802. " don't know how to handle tied "
  5803. "indirect register inputs");
  5804. return;
  5805. }
  5806. RegsForValue MatchedRegs;
  5807. MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
  5808. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  5809. MatchedRegs.RegVTs.push_back(RegVT);
  5810. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  5811. for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
  5812. i != e; ++i) {
  5813. if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT))
  5814. MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
  5815. else {
  5816. LLVMContext &Ctx = *DAG.getContext();
  5817. Ctx.emitError(CS.getInstruction(),
  5818. "inline asm error: This value"
  5819. " type register class is not natively supported!");
  5820. return;
  5821. }
  5822. }
  5823. // Use the produced MatchedRegs object to
  5824. MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
  5825. Chain, &Flag, CS.getInstruction());
  5826. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  5827. true, OpInfo.getMatchedOperand(),
  5828. DAG, AsmNodeOperands);
  5829. break;
  5830. }
  5831. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  5832. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  5833. "Unexpected number of operands");
  5834. // Add information to the INLINEASM node to know about this input.
  5835. // See InlineAsm.h isUseOperandTiedToDef.
  5836. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  5837. OpInfo.getMatchedOperand());
  5838. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
  5839. TLI->getPointerTy()));
  5840. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  5841. break;
  5842. }
  5843. // Treat indirect 'X' constraint as memory.
  5844. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  5845. OpInfo.isIndirect)
  5846. OpInfo.ConstraintType = TargetLowering::C_Memory;
  5847. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  5848. std::vector<SDValue> Ops;
  5849. TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  5850. Ops, DAG);
  5851. if (Ops.empty()) {
  5852. LLVMContext &Ctx = *DAG.getContext();
  5853. Ctx.emitError(CS.getInstruction(),
  5854. "invalid operand for inline asm constraint '" +
  5855. Twine(OpInfo.ConstraintCode) + "'");
  5856. return;
  5857. }
  5858. // Add information to the INLINEASM node to know about this input.
  5859. unsigned ResOpType =
  5860. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  5861. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  5862. TLI->getPointerTy()));
  5863. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  5864. break;
  5865. }
  5866. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  5867. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  5868. assert(InOperandVal.getValueType() == TLI->getPointerTy() &&
  5869. "Memory operands expect pointer values");
  5870. // Add information to the INLINEASM node to know about this input.
  5871. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5872. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  5873. TLI->getPointerTy()));
  5874. AsmNodeOperands.push_back(InOperandVal);
  5875. break;
  5876. }
  5877. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  5878. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  5879. "Unknown constraint type!");
  5880. // TODO: Support this.
  5881. if (OpInfo.isIndirect) {
  5882. LLVMContext &Ctx = *DAG.getContext();
  5883. Ctx.emitError(CS.getInstruction(),
  5884. "Don't know how to handle indirect register inputs yet "
  5885. "for constraint '" +
  5886. Twine(OpInfo.ConstraintCode) + "'");
  5887. return;
  5888. }
  5889. // Copy the input into the appropriate registers.
  5890. if (OpInfo.AssignedRegs.Regs.empty()) {
  5891. LLVMContext &Ctx = *DAG.getContext();
  5892. Ctx.emitError(CS.getInstruction(),
  5893. "couldn't allocate input reg for constraint '" +
  5894. Twine(OpInfo.ConstraintCode) + "'");
  5895. return;
  5896. }
  5897. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
  5898. Chain, &Flag, CS.getInstruction());
  5899. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  5900. DAG, AsmNodeOperands);
  5901. break;
  5902. }
  5903. case InlineAsm::isClobber: {
  5904. // Add the clobbered value to the operand list, so that the register
  5905. // allocator is aware that the physreg got clobbered.
  5906. if (!OpInfo.AssignedRegs.Regs.empty())
  5907. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  5908. false, 0, DAG,
  5909. AsmNodeOperands);
  5910. break;
  5911. }
  5912. }
  5913. }
  5914. // Finish up input operands. Set the input chain and add the flag last.
  5915. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  5916. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  5917. Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
  5918. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  5919. Flag = Chain.getValue(1);
  5920. // If this asm returns a register value, copy the result from that register
  5921. // and set it as the value of the call.
  5922. if (!RetValRegs.Regs.empty()) {
  5923. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  5924. Chain, &Flag, CS.getInstruction());
  5925. // FIXME: Why don't we do this for inline asms with MRVs?
  5926. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  5927. EVT ResultType = TLI->getValueType(CS.getType());
  5928. // If any of the results of the inline asm is a vector, it may have the
  5929. // wrong width/num elts. This can happen for register classes that can
  5930. // contain multiple different value types. The preg or vreg allocated may
  5931. // not have the same VT as was expected. Convert it to the right type
  5932. // with bit_convert.
  5933. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  5934. Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  5935. ResultType, Val);
  5936. } else if (ResultType != Val.getValueType() &&
  5937. ResultType.isInteger() && Val.getValueType().isInteger()) {
  5938. // If a result value was tied to an input value, the computed result may
  5939. // have a wider width than the expected result. Extract the relevant
  5940. // portion.
  5941. Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
  5942. }
  5943. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  5944. }
  5945. setValue(CS.getInstruction(), Val);
  5946. // Don't need to use this as a chain in this case.
  5947. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  5948. return;
  5949. }
  5950. std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
  5951. // Process indirect outputs, first output all of the flagged copies out of
  5952. // physregs.
  5953. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  5954. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  5955. const Value *Ptr = IndirectStoresToEmit[i].second;
  5956. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  5957. Chain, &Flag, IA);
  5958. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  5959. }
  5960. // Emit the non-flagged stores from the physregs.
  5961. SmallVector<SDValue, 8> OutChains;
  5962. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  5963. SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
  5964. StoresToEmit[i].first,
  5965. getValue(StoresToEmit[i].second),
  5966. MachinePointerInfo(StoresToEmit[i].second),
  5967. false, false, 0);
  5968. OutChains.push_back(Val);
  5969. }
  5970. if (!OutChains.empty())
  5971. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  5972. DAG.setRoot(Chain);
  5973. }
  5974. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  5975. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  5976. MVT::Other, getRoot(),
  5977. getValue(I.getArgOperand(0)),
  5978. DAG.getSrcValue(I.getArgOperand(0))));
  5979. }
  5980. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  5981. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  5982. const DataLayout &DL = *TLI->getDataLayout();
  5983. SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(),
  5984. getRoot(), getValue(I.getOperand(0)),
  5985. DAG.getSrcValue(I.getOperand(0)),
  5986. DL.getABITypeAlignment(I.getType()));
  5987. setValue(&I, V);
  5988. DAG.setRoot(V.getValue(1));
  5989. }
  5990. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  5991. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  5992. MVT::Other, getRoot(),
  5993. getValue(I.getArgOperand(0)),
  5994. DAG.getSrcValue(I.getArgOperand(0))));
  5995. }
  5996. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  5997. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  5998. MVT::Other, getRoot(),
  5999. getValue(I.getArgOperand(0)),
  6000. getValue(I.getArgOperand(1)),
  6001. DAG.getSrcValue(I.getArgOperand(0)),
  6002. DAG.getSrcValue(I.getArgOperand(1))));
  6003. }
  6004. /// \brief Lower an argument list according to the target calling convention.
  6005. ///
  6006. /// \return A tuple of <return-value, token-chain>
  6007. ///
  6008. /// This is a helper for lowering intrinsics that follow a target calling
  6009. /// convention or require stack pointer adjustment. Only a subset of the
  6010. /// intrinsic's operands need to participate in the calling convention.
  6011. std::pair<SDValue, SDValue>
  6012. SelectionDAGBuilder::LowerCallOperands(const CallInst &CI, unsigned ArgIdx,
  6013. unsigned NumArgs, SDValue Callee,
  6014. bool useVoidTy) {
  6015. TargetLowering::ArgListTy Args;
  6016. Args.reserve(NumArgs);
  6017. // Populate the argument list.
  6018. // Attributes for args start at offset 1, after the return attribute.
  6019. ImmutableCallSite CS(&CI);
  6020. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
  6021. ArgI != ArgE; ++ArgI) {
  6022. const Value *V = CI.getOperand(ArgI);
  6023. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  6024. TargetLowering::ArgListEntry Entry;
  6025. Entry.Node = getValue(V);
  6026. Entry.Ty = V->getType();
  6027. Entry.setAttributes(&CS, AttrI);
  6028. Args.push_back(Entry);
  6029. }
  6030. Type *retTy = useVoidTy ? Type::getVoidTy(*DAG.getContext()) : CI.getType();
  6031. TargetLowering::CallLoweringInfo CLI(DAG);
  6032. CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
  6033. .setCallee(CI.getCallingConv(), retTy, Callee, std::move(Args), NumArgs)
  6034. .setDiscardResult(!CI.use_empty());
  6035. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  6036. return TLI->LowerCallTo(CLI);
  6037. }
  6038. /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
  6039. /// or patchpoint target node's operand list.
  6040. ///
  6041. /// Constants are converted to TargetConstants purely as an optimization to
  6042. /// avoid constant materialization and register allocation.
  6043. ///
  6044. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  6045. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  6046. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  6047. /// address materialization and register allocation, but may also be required
  6048. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  6049. /// alloca in the entry block, then the runtime may assume that the alloca's
  6050. /// StackMap location can be read immediately after compilation and that the
  6051. /// location is valid at any point during execution (this is similar to the
  6052. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  6053. /// only available in a register, then the runtime would need to trap when
  6054. /// execution reaches the StackMap in order to read the alloca's location.
  6055. static void addStackMapLiveVars(const CallInst &CI, unsigned StartIdx,
  6056. SmallVectorImpl<SDValue> &Ops,
  6057. SelectionDAGBuilder &Builder) {
  6058. for (unsigned i = StartIdx, e = CI.getNumArgOperands(); i != e; ++i) {
  6059. SDValue OpVal = Builder.getValue(CI.getArgOperand(i));
  6060. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  6061. Ops.push_back(
  6062. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
  6063. Ops.push_back(
  6064. Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
  6065. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  6066. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  6067. Ops.push_back(
  6068. Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
  6069. } else
  6070. Ops.push_back(OpVal);
  6071. }
  6072. }
  6073. /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
  6074. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  6075. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  6076. // [live variables...])
  6077. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  6078. SDValue Chain, InFlag, Callee, NullPtr;
  6079. SmallVector<SDValue, 32> Ops;
  6080. SDLoc DL = getCurSDLoc();
  6081. Callee = getValue(CI.getCalledValue());
  6082. NullPtr = DAG.getIntPtrConstant(0, true);
  6083. // The stackmap intrinsic only records the live variables (the arguemnts
  6084. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  6085. // intrinsic, this won't be lowered to a function call. This means we don't
  6086. // have to worry about calling conventions and target specific lowering code.
  6087. // Instead we perform the call lowering right here.
  6088. //
  6089. // chain, flag = CALLSEQ_START(chain, 0)
  6090. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  6091. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  6092. //
  6093. Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
  6094. InFlag = Chain.getValue(1);
  6095. // Add the <id> and <numBytes> constants.
  6096. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  6097. Ops.push_back(DAG.getTargetConstant(
  6098. cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
  6099. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  6100. Ops.push_back(DAG.getTargetConstant(
  6101. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
  6102. // Push live variables for the stack map.
  6103. addStackMapLiveVars(CI, 2, Ops, *this);
  6104. // We are not pushing any register mask info here on the operands list,
  6105. // because the stackmap doesn't clobber anything.
  6106. // Push the chain and the glue flag.
  6107. Ops.push_back(Chain);
  6108. Ops.push_back(InFlag);
  6109. // Create the STACKMAP node.
  6110. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6111. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  6112. Chain = SDValue(SM, 0);
  6113. InFlag = Chain.getValue(1);
  6114. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  6115. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  6116. // Set the root to the target-lowered call chain.
  6117. DAG.setRoot(Chain);
  6118. // Inform the Frame Information that we have a stackmap in this function.
  6119. FuncInfo.MF->getFrameInfo()->setHasStackMap();
  6120. }
  6121. /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
  6122. void SelectionDAGBuilder::visitPatchpoint(const CallInst &CI) {
  6123. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  6124. // i32 <numBytes>,
  6125. // i8* <target>,
  6126. // i32 <numArgs>,
  6127. // [Args...],
  6128. // [live variables...])
  6129. CallingConv::ID CC = CI.getCallingConv();
  6130. bool isAnyRegCC = CC == CallingConv::AnyReg;
  6131. bool hasDef = !CI.getType()->isVoidTy();
  6132. SDValue Callee = getValue(CI.getOperand(2)); // <target>
  6133. // Get the real number of arguments participating in the call <numArgs>
  6134. SDValue NArgVal = getValue(CI.getArgOperand(PatchPointOpers::NArgPos));
  6135. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  6136. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  6137. // Intrinsics include all meta-operands up to but not including CC.
  6138. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  6139. assert(CI.getNumArgOperands() >= NumMetaOpers + NumArgs &&
  6140. "Not enough arguments provided to the patchpoint intrinsic");
  6141. // For AnyRegCC the arguments are lowered later on manually.
  6142. unsigned NumCallArgs = isAnyRegCC ? 0 : NumArgs;
  6143. std::pair<SDValue, SDValue> Result =
  6144. LowerCallOperands(CI, NumMetaOpers, NumCallArgs, Callee, isAnyRegCC);
  6145. // Set the root to the target-lowered call chain.
  6146. SDValue Chain = Result.second;
  6147. DAG.setRoot(Chain);
  6148. SDNode *CallEnd = Chain.getNode();
  6149. if (hasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  6150. CallEnd = CallEnd->getOperand(0).getNode();
  6151. /// Get a call instruction from the call sequence chain.
  6152. /// Tail calls are not allowed.
  6153. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  6154. "Expected a callseq node.");
  6155. SDNode *Call = CallEnd->getOperand(0).getNode();
  6156. bool hasGlue = Call->getGluedNode();
  6157. // Replace the target specific call node with the patchable intrinsic.
  6158. SmallVector<SDValue, 8> Ops;
  6159. // Add the <id> and <numBytes> constants.
  6160. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  6161. Ops.push_back(DAG.getTargetConstant(
  6162. cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
  6163. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  6164. Ops.push_back(DAG.getTargetConstant(
  6165. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
  6166. // Assume that the Callee is a constant address.
  6167. // FIXME: handle function symbols in the future.
  6168. Ops.push_back(
  6169. DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
  6170. /*isTarget=*/true));
  6171. // Adjust <numArgs> to account for any arguments that have been passed on the
  6172. // stack instead.
  6173. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  6174. unsigned NumCallRegArgs = Call->getNumOperands() - (hasGlue ? 4 : 3);
  6175. NumCallRegArgs = isAnyRegCC ? NumArgs : NumCallRegArgs;
  6176. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
  6177. // Add the calling convention
  6178. Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
  6179. // Add the arguments we omitted previously. The register allocator should
  6180. // place these in any free register.
  6181. if (isAnyRegCC)
  6182. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  6183. Ops.push_back(getValue(CI.getArgOperand(i)));
  6184. // Push the arguments from the call instruction up to the register mask.
  6185. SDNode::op_iterator e = hasGlue ? Call->op_end()-2 : Call->op_end()-1;
  6186. for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
  6187. Ops.push_back(*i);
  6188. // Push live variables for the stack map.
  6189. addStackMapLiveVars(CI, NumMetaOpers + NumArgs, Ops, *this);
  6190. // Push the register mask info.
  6191. if (hasGlue)
  6192. Ops.push_back(*(Call->op_end()-2));
  6193. else
  6194. Ops.push_back(*(Call->op_end()-1));
  6195. // Push the chain (this is originally the first operand of the call, but
  6196. // becomes now the last or second to last operand).
  6197. Ops.push_back(*(Call->op_begin()));
  6198. // Push the glue flag (last operand).
  6199. if (hasGlue)
  6200. Ops.push_back(*(Call->op_end()-1));
  6201. SDVTList NodeTys;
  6202. if (isAnyRegCC && hasDef) {
  6203. // Create the return types based on the intrinsic definition
  6204. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6205. SmallVector<EVT, 3> ValueVTs;
  6206. ComputeValueVTs(TLI, CI.getType(), ValueVTs);
  6207. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  6208. // There is always a chain and a glue type at the end
  6209. ValueVTs.push_back(MVT::Other);
  6210. ValueVTs.push_back(MVT::Glue);
  6211. NodeTys = DAG.getVTList(ValueVTs);
  6212. } else
  6213. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6214. // Replace the target specific call node with a PATCHPOINT node.
  6215. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  6216. getCurSDLoc(), NodeTys, Ops);
  6217. // Update the NodeMap.
  6218. if (hasDef) {
  6219. if (isAnyRegCC)
  6220. setValue(&CI, SDValue(MN, 0));
  6221. else
  6222. setValue(&CI, Result.first);
  6223. }
  6224. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  6225. // call sequence. Furthermore the location of the chain and glue can change
  6226. // when the AnyReg calling convention is used and the intrinsic returns a
  6227. // value.
  6228. if (isAnyRegCC && hasDef) {
  6229. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  6230. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  6231. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  6232. } else
  6233. DAG.ReplaceAllUsesWith(Call, MN);
  6234. DAG.DeleteNode(Call);
  6235. // Inform the Frame Information that we have a patchpoint in this function.
  6236. FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
  6237. }
  6238. /// Returns an AttributeSet representing the attributes applied to the return
  6239. /// value of the given call.
  6240. static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  6241. SmallVector<Attribute::AttrKind, 2> Attrs;
  6242. if (CLI.RetSExt)
  6243. Attrs.push_back(Attribute::SExt);
  6244. if (CLI.RetZExt)
  6245. Attrs.push_back(Attribute::ZExt);
  6246. if (CLI.IsInReg)
  6247. Attrs.push_back(Attribute::InReg);
  6248. return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
  6249. Attrs);
  6250. }
  6251. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  6252. /// implementation, which just calls LowerCall.
  6253. /// FIXME: When all targets are
  6254. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  6255. std::pair<SDValue, SDValue>
  6256. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  6257. // Handle the incoming return values from the call.
  6258. CLI.Ins.clear();
  6259. Type *OrigRetTy = CLI.RetTy;
  6260. SmallVector<EVT, 4> RetTys;
  6261. SmallVector<uint64_t, 4> Offsets;
  6262. ComputeValueVTs(*this, CLI.RetTy, RetTys, &Offsets);
  6263. SmallVector<ISD::OutputArg, 4> Outs;
  6264. GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this);
  6265. bool CanLowerReturn =
  6266. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  6267. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  6268. SDValue DemoteStackSlot;
  6269. int DemoteStackIdx = -100;
  6270. if (!CanLowerReturn) {
  6271. // FIXME: equivalent assert?
  6272. // assert(!CS.hasInAllocaArgument() &&
  6273. // "sret demotion is incompatible with inalloca");
  6274. uint64_t TySize = getDataLayout()->getTypeAllocSize(CLI.RetTy);
  6275. unsigned Align = getDataLayout()->getPrefTypeAlignment(CLI.RetTy);
  6276. MachineFunction &MF = CLI.DAG.getMachineFunction();
  6277. DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  6278. Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
  6279. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
  6280. ArgListEntry Entry;
  6281. Entry.Node = DemoteStackSlot;
  6282. Entry.Ty = StackSlotPtrType;
  6283. Entry.isSExt = false;
  6284. Entry.isZExt = false;
  6285. Entry.isInReg = false;
  6286. Entry.isSRet = true;
  6287. Entry.isNest = false;
  6288. Entry.isByVal = false;
  6289. Entry.isReturned = false;
  6290. Entry.Alignment = Align;
  6291. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  6292. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  6293. } else {
  6294. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  6295. EVT VT = RetTys[I];
  6296. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6297. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  6298. for (unsigned i = 0; i != NumRegs; ++i) {
  6299. ISD::InputArg MyFlags;
  6300. MyFlags.VT = RegisterVT;
  6301. MyFlags.ArgVT = VT;
  6302. MyFlags.Used = CLI.IsReturnValueUsed;
  6303. if (CLI.RetSExt)
  6304. MyFlags.Flags.setSExt();
  6305. if (CLI.RetZExt)
  6306. MyFlags.Flags.setZExt();
  6307. if (CLI.IsInReg)
  6308. MyFlags.Flags.setInReg();
  6309. CLI.Ins.push_back(MyFlags);
  6310. }
  6311. }
  6312. }
  6313. // Handle all of the outgoing arguments.
  6314. CLI.Outs.clear();
  6315. CLI.OutVals.clear();
  6316. ArgListTy &Args = CLI.getArgs();
  6317. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  6318. SmallVector<EVT, 4> ValueVTs;
  6319. ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
  6320. Type *FinalType = Args[i].Ty;
  6321. if (Args[i].isByVal)
  6322. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  6323. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  6324. FinalType, CLI.CallConv, CLI.IsVarArg);
  6325. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  6326. ++Value) {
  6327. EVT VT = ValueVTs[Value];
  6328. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  6329. SDValue Op = SDValue(Args[i].Node.getNode(),
  6330. Args[i].Node.getResNo() + Value);
  6331. ISD::ArgFlagsTy Flags;
  6332. unsigned OriginalAlignment = getDataLayout()->getABITypeAlignment(ArgTy);
  6333. if (Args[i].isZExt)
  6334. Flags.setZExt();
  6335. if (Args[i].isSExt)
  6336. Flags.setSExt();
  6337. if (Args[i].isInReg)
  6338. Flags.setInReg();
  6339. if (Args[i].isSRet)
  6340. Flags.setSRet();
  6341. if (Args[i].isByVal)
  6342. Flags.setByVal();
  6343. if (Args[i].isInAlloca) {
  6344. Flags.setInAlloca();
  6345. // Set the byval flag for CCAssignFn callbacks that don't know about
  6346. // inalloca. This way we can know how many bytes we should've allocated
  6347. // and how many bytes a callee cleanup function will pop. If we port
  6348. // inalloca to more targets, we'll have to add custom inalloca handling
  6349. // in the various CC lowering callbacks.
  6350. Flags.setByVal();
  6351. }
  6352. if (Args[i].isByVal || Args[i].isInAlloca) {
  6353. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  6354. Type *ElementTy = Ty->getElementType();
  6355. Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
  6356. // For ByVal, alignment should come from FE. BE will guess if this
  6357. // info is not there but there are cases it cannot get right.
  6358. unsigned FrameAlign;
  6359. if (Args[i].Alignment)
  6360. FrameAlign = Args[i].Alignment;
  6361. else
  6362. FrameAlign = getByValTypeAlignment(ElementTy);
  6363. Flags.setByValAlign(FrameAlign);
  6364. }
  6365. if (Args[i].isNest)
  6366. Flags.setNest();
  6367. if (NeedsRegBlock)
  6368. Flags.setInConsecutiveRegs();
  6369. Flags.setOrigAlign(OriginalAlignment);
  6370. MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6371. unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
  6372. SmallVector<SDValue, 4> Parts(NumParts);
  6373. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  6374. if (Args[i].isSExt)
  6375. ExtendKind = ISD::SIGN_EXTEND;
  6376. else if (Args[i].isZExt)
  6377. ExtendKind = ISD::ZERO_EXTEND;
  6378. // Conservatively only handle 'returned' on non-vectors for now
  6379. if (Args[i].isReturned && !Op.getValueType().isVector()) {
  6380. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  6381. "unexpected use of 'returned'");
  6382. // Before passing 'returned' to the target lowering code, ensure that
  6383. // either the register MVT and the actual EVT are the same size or that
  6384. // the return value and argument are extended in the same way; in these
  6385. // cases it's safe to pass the argument register value unchanged as the
  6386. // return register value (although it's at the target's option whether
  6387. // to do so)
  6388. // TODO: allow code generation to take advantage of partially preserved
  6389. // registers rather than clobbering the entire register when the
  6390. // parameter extension method is not compatible with the return
  6391. // extension method
  6392. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  6393. (ExtendKind != ISD::ANY_EXTEND &&
  6394. CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
  6395. Flags.setReturned();
  6396. }
  6397. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  6398. CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
  6399. for (unsigned j = 0; j != NumParts; ++j) {
  6400. // if it isn't first piece, alignment must be 1
  6401. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  6402. i < CLI.NumFixedArgs,
  6403. i, j*Parts[j].getValueType().getStoreSize());
  6404. if (NumParts > 1 && j == 0)
  6405. MyFlags.Flags.setSplit();
  6406. else if (j != 0)
  6407. MyFlags.Flags.setOrigAlign(1);
  6408. // Only mark the end at the last register of the last value.
  6409. if (NeedsRegBlock && Value == NumValues - 1 && j == NumParts - 1)
  6410. MyFlags.Flags.setInConsecutiveRegsLast();
  6411. CLI.Outs.push_back(MyFlags);
  6412. CLI.OutVals.push_back(Parts[j]);
  6413. }
  6414. }
  6415. }
  6416. SmallVector<SDValue, 4> InVals;
  6417. CLI.Chain = LowerCall(CLI, InVals);
  6418. // Verify that the target's LowerCall behaved as expected.
  6419. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  6420. "LowerCall didn't return a valid chain!");
  6421. assert((!CLI.IsTailCall || InVals.empty()) &&
  6422. "LowerCall emitted a return value for a tail call!");
  6423. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  6424. "LowerCall didn't emit the correct number of values!");
  6425. // For a tail call, the return value is merely live-out and there aren't
  6426. // any nodes in the DAG representing it. Return a special value to
  6427. // indicate that a tail call has been emitted and no more Instructions
  6428. // should be processed in the current block.
  6429. if (CLI.IsTailCall) {
  6430. CLI.DAG.setRoot(CLI.Chain);
  6431. return std::make_pair(SDValue(), SDValue());
  6432. }
  6433. DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  6434. assert(InVals[i].getNode() &&
  6435. "LowerCall emitted a null value!");
  6436. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  6437. "LowerCall emitted a value with the wrong type!");
  6438. });
  6439. SmallVector<SDValue, 4> ReturnValues;
  6440. if (!CanLowerReturn) {
  6441. // The instruction result is the result of loading from the
  6442. // hidden sret parameter.
  6443. SmallVector<EVT, 1> PVTs;
  6444. Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
  6445. ComputeValueVTs(*this, PtrRetTy, PVTs);
  6446. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  6447. EVT PtrVT = PVTs[0];
  6448. unsigned NumValues = RetTys.size();
  6449. ReturnValues.resize(NumValues);
  6450. SmallVector<SDValue, 4> Chains(NumValues);
  6451. for (unsigned i = 0; i < NumValues; ++i) {
  6452. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  6453. CLI.DAG.getConstant(Offsets[i], PtrVT));
  6454. SDValue L = CLI.DAG.getLoad(
  6455. RetTys[i], CLI.DL, CLI.Chain, Add,
  6456. MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
  6457. false, false, 1);
  6458. ReturnValues[i] = L;
  6459. Chains[i] = L.getValue(1);
  6460. }
  6461. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  6462. } else {
  6463. // Collect the legal value parts into potentially illegal values
  6464. // that correspond to the original function's return values.
  6465. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6466. if (CLI.RetSExt)
  6467. AssertOp = ISD::AssertSext;
  6468. else if (CLI.RetZExt)
  6469. AssertOp = ISD::AssertZext;
  6470. unsigned CurReg = 0;
  6471. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  6472. EVT VT = RetTys[I];
  6473. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6474. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  6475. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  6476. NumRegs, RegisterVT, VT, nullptr,
  6477. AssertOp));
  6478. CurReg += NumRegs;
  6479. }
  6480. // For a function returning void, there is no return value. We can't create
  6481. // such a node, so we just return a null return value in that case. In
  6482. // that case, nothing will actually look at the value.
  6483. if (ReturnValues.empty())
  6484. return std::make_pair(SDValue(), CLI.Chain);
  6485. }
  6486. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  6487. CLI.DAG.getVTList(RetTys), ReturnValues);
  6488. return std::make_pair(Res, CLI.Chain);
  6489. }
  6490. void TargetLowering::LowerOperationWrapper(SDNode *N,
  6491. SmallVectorImpl<SDValue> &Results,
  6492. SelectionDAG &DAG) const {
  6493. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  6494. if (Res.getNode())
  6495. Results.push_back(Res);
  6496. }
  6497. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  6498. llvm_unreachable("LowerOperation not implemented for this target!");
  6499. }
  6500. void
  6501. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  6502. SDValue Op = getNonRegisterValue(V);
  6503. assert((Op.getOpcode() != ISD::CopyFromReg ||
  6504. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  6505. "Copy from a reg to the same reg!");
  6506. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  6507. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  6508. RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType());
  6509. SDValue Chain = DAG.getEntryNode();
  6510. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V);
  6511. PendingExports.push_back(Chain);
  6512. }
  6513. #include "llvm/CodeGen/SelectionDAGISel.h"
  6514. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  6515. /// entry block, return true. This includes arguments used by switches, since
  6516. /// the switch may expand into multiple basic blocks.
  6517. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  6518. // With FastISel active, we may be splitting blocks, so force creation
  6519. // of virtual registers for all non-dead arguments.
  6520. if (FastISel)
  6521. return A->use_empty();
  6522. const BasicBlock *Entry = A->getParent()->begin();
  6523. for (const User *U : A->users())
  6524. if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
  6525. return false; // Use not in entry block.
  6526. return true;
  6527. }
  6528. void SelectionDAGISel::LowerArguments(const Function &F) {
  6529. SelectionDAG &DAG = SDB->DAG;
  6530. SDLoc dl = SDB->getCurSDLoc();
  6531. const TargetLowering *TLI = getTargetLowering();
  6532. const DataLayout *DL = TLI->getDataLayout();
  6533. SmallVector<ISD::InputArg, 16> Ins;
  6534. if (!FuncInfo->CanLowerReturn) {
  6535. // Put in an sret pointer parameter before all the other parameters.
  6536. SmallVector<EVT, 1> ValueVTs;
  6537. ComputeValueVTs(*getTargetLowering(),
  6538. PointerType::getUnqual(F.getReturnType()), ValueVTs);
  6539. // NOTE: Assuming that a pointer will never break down to more than one VT
  6540. // or one register.
  6541. ISD::ArgFlagsTy Flags;
  6542. Flags.setSRet();
  6543. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  6544. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
  6545. Ins.push_back(RetArg);
  6546. }
  6547. // Set up the incoming argument description vector.
  6548. unsigned Idx = 1;
  6549. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
  6550. I != E; ++I, ++Idx) {
  6551. SmallVector<EVT, 4> ValueVTs;
  6552. ComputeValueVTs(*TLI, I->getType(), ValueVTs);
  6553. bool isArgValueUsed = !I->use_empty();
  6554. unsigned PartBase = 0;
  6555. Type *FinalType = I->getType();
  6556. if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
  6557. FinalType = cast<PointerType>(FinalType)->getElementType();
  6558. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  6559. FinalType, F.getCallingConv(), F.isVarArg());
  6560. for (unsigned Value = 0, NumValues = ValueVTs.size();
  6561. Value != NumValues; ++Value) {
  6562. EVT VT = ValueVTs[Value];
  6563. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  6564. ISD::ArgFlagsTy Flags;
  6565. unsigned OriginalAlignment = DL->getABITypeAlignment(ArgTy);
  6566. if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  6567. Flags.setZExt();
  6568. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  6569. Flags.setSExt();
  6570. if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
  6571. Flags.setInReg();
  6572. if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
  6573. Flags.setSRet();
  6574. if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
  6575. Flags.setByVal();
  6576. if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
  6577. Flags.setInAlloca();
  6578. // Set the byval flag for CCAssignFn callbacks that don't know about
  6579. // inalloca. This way we can know how many bytes we should've allocated
  6580. // and how many bytes a callee cleanup function will pop. If we port
  6581. // inalloca to more targets, we'll have to add custom inalloca handling
  6582. // in the various CC lowering callbacks.
  6583. Flags.setByVal();
  6584. }
  6585. if (Flags.isByVal() || Flags.isInAlloca()) {
  6586. PointerType *Ty = cast<PointerType>(I->getType());
  6587. Type *ElementTy = Ty->getElementType();
  6588. Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
  6589. // For ByVal, alignment should be passed from FE. BE will guess if
  6590. // this info is not there but there are cases it cannot get right.
  6591. unsigned FrameAlign;
  6592. if (F.getParamAlignment(Idx))
  6593. FrameAlign = F.getParamAlignment(Idx);
  6594. else
  6595. FrameAlign = TLI->getByValTypeAlignment(ElementTy);
  6596. Flags.setByValAlign(FrameAlign);
  6597. }
  6598. if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
  6599. Flags.setNest();
  6600. if (NeedsRegBlock)
  6601. Flags.setInConsecutiveRegs();
  6602. Flags.setOrigAlign(OriginalAlignment);
  6603. MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6604. unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  6605. for (unsigned i = 0; i != NumRegs; ++i) {
  6606. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  6607. Idx-1, PartBase+i*RegisterVT.getStoreSize());
  6608. if (NumRegs > 1 && i == 0)
  6609. MyFlags.Flags.setSplit();
  6610. // if it isn't first piece, alignment must be 1
  6611. else if (i > 0)
  6612. MyFlags.Flags.setOrigAlign(1);
  6613. // Only mark the end at the last register of the last value.
  6614. if (NeedsRegBlock && Value == NumValues - 1 && i == NumRegs - 1)
  6615. MyFlags.Flags.setInConsecutiveRegsLast();
  6616. Ins.push_back(MyFlags);
  6617. }
  6618. PartBase += VT.getStoreSize();
  6619. }
  6620. }
  6621. // Call the target to set up the argument values.
  6622. SmallVector<SDValue, 8> InVals;
  6623. SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
  6624. F.isVarArg(), Ins,
  6625. dl, DAG, InVals);
  6626. // Verify that the target's LowerFormalArguments behaved as expected.
  6627. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  6628. "LowerFormalArguments didn't return a valid chain!");
  6629. assert(InVals.size() == Ins.size() &&
  6630. "LowerFormalArguments didn't emit the correct number of values!");
  6631. DEBUG({
  6632. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  6633. assert(InVals[i].getNode() &&
  6634. "LowerFormalArguments emitted a null value!");
  6635. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  6636. "LowerFormalArguments emitted a value with the wrong type!");
  6637. }
  6638. });
  6639. // Update the DAG with the new chain value resulting from argument lowering.
  6640. DAG.setRoot(NewRoot);
  6641. // Set up the argument values.
  6642. unsigned i = 0;
  6643. Idx = 1;
  6644. if (!FuncInfo->CanLowerReturn) {
  6645. // Create a virtual register for the sret pointer, and put in a copy
  6646. // from the sret argument into it.
  6647. SmallVector<EVT, 1> ValueVTs;
  6648. ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
  6649. MVT VT = ValueVTs[0].getSimpleVT();
  6650. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6651. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6652. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  6653. RegVT, VT, nullptr, AssertOp);
  6654. MachineFunction& MF = SDB->DAG.getMachineFunction();
  6655. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  6656. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  6657. FuncInfo->DemoteRegister = SRetReg;
  6658. NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(),
  6659. SRetReg, ArgValue);
  6660. DAG.setRoot(NewRoot);
  6661. // i indexes lowered arguments. Bump it past the hidden sret argument.
  6662. // Idx indexes LLVM arguments. Don't touch it.
  6663. ++i;
  6664. }
  6665. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
  6666. ++I, ++Idx) {
  6667. SmallVector<SDValue, 4> ArgValues;
  6668. SmallVector<EVT, 4> ValueVTs;
  6669. ComputeValueVTs(*TLI, I->getType(), ValueVTs);
  6670. unsigned NumValues = ValueVTs.size();
  6671. // If this argument is unused then remember its value. It is used to generate
  6672. // debugging information.
  6673. if (I->use_empty() && NumValues) {
  6674. SDB->setUnusedArgValue(I, InVals[i]);
  6675. // Also remember any frame index for use in FastISel.
  6676. if (FrameIndexSDNode *FI =
  6677. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  6678. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6679. }
  6680. for (unsigned Val = 0; Val != NumValues; ++Val) {
  6681. EVT VT = ValueVTs[Val];
  6682. MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6683. unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  6684. if (!I->use_empty()) {
  6685. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6686. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  6687. AssertOp = ISD::AssertSext;
  6688. else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  6689. AssertOp = ISD::AssertZext;
  6690. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
  6691. NumParts, PartVT, VT,
  6692. nullptr, AssertOp));
  6693. }
  6694. i += NumParts;
  6695. }
  6696. // We don't need to do anything else for unused arguments.
  6697. if (ArgValues.empty())
  6698. continue;
  6699. // Note down frame index.
  6700. if (FrameIndexSDNode *FI =
  6701. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  6702. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6703. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  6704. SDB->getCurSDLoc());
  6705. SDB->setValue(I, Res);
  6706. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  6707. if (LoadSDNode *LNode =
  6708. dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
  6709. if (FrameIndexSDNode *FI =
  6710. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  6711. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6712. }
  6713. // If this argument is live outside of the entry block, insert a copy from
  6714. // wherever we got it to the vreg that other BB's will reference it as.
  6715. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  6716. // If we can, though, try to skip creating an unnecessary vreg.
  6717. // FIXME: This isn't very clean... it would be nice to make this more
  6718. // general. It's also subtly incompatible with the hacks FastISel
  6719. // uses with vregs.
  6720. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  6721. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  6722. FuncInfo->ValueMap[I] = Reg;
  6723. continue;
  6724. }
  6725. }
  6726. if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
  6727. FuncInfo->InitializeRegForValue(I);
  6728. SDB->CopyToExportRegsIfNeeded(I);
  6729. }
  6730. }
  6731. assert(i == InVals.size() && "Argument register count mismatch!");
  6732. // Finally, if the target has anything special to do, allow it to do so.
  6733. // FIXME: this should insert code into the DAG!
  6734. EmitFunctionEntryCode();
  6735. }
  6736. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  6737. /// ensure constants are generated when needed. Remember the virtual registers
  6738. /// that need to be added to the Machine PHI nodes as input. We cannot just
  6739. /// directly add them, because expansion might result in multiple MBB's for one
  6740. /// BB. As such, the start of the BB might correspond to a different MBB than
  6741. /// the end.
  6742. ///
  6743. void
  6744. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  6745. const TerminatorInst *TI = LLVMBB->getTerminator();
  6746. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  6747. // Check successor nodes' PHI nodes that expect a constant to be available
  6748. // from this block.
  6749. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  6750. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  6751. if (!isa<PHINode>(SuccBB->begin())) continue;
  6752. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  6753. // If this terminator has multiple identical successors (common for
  6754. // switches), only handle each succ once.
  6755. if (!SuccsHandled.insert(SuccMBB)) continue;
  6756. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  6757. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  6758. // nodes and Machine PHI nodes, but the incoming operands have not been
  6759. // emitted yet.
  6760. for (BasicBlock::const_iterator I = SuccBB->begin();
  6761. const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  6762. // Ignore dead phi's.
  6763. if (PN->use_empty()) continue;
  6764. // Skip empty types
  6765. if (PN->getType()->isEmptyTy())
  6766. continue;
  6767. unsigned Reg;
  6768. const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  6769. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  6770. unsigned &RegOut = ConstantsOut[C];
  6771. if (RegOut == 0) {
  6772. RegOut = FuncInfo.CreateRegs(C->getType());
  6773. CopyValueToVirtualRegister(C, RegOut);
  6774. }
  6775. Reg = RegOut;
  6776. } else {
  6777. DenseMap<const Value *, unsigned>::iterator I =
  6778. FuncInfo.ValueMap.find(PHIOp);
  6779. if (I != FuncInfo.ValueMap.end())
  6780. Reg = I->second;
  6781. else {
  6782. assert(isa<AllocaInst>(PHIOp) &&
  6783. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  6784. "Didn't codegen value into a register!??");
  6785. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  6786. CopyValueToVirtualRegister(PHIOp, Reg);
  6787. }
  6788. }
  6789. // Remember that this register needs to added to the machine PHI node as
  6790. // the input for this MBB.
  6791. SmallVector<EVT, 4> ValueVTs;
  6792. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  6793. ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
  6794. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  6795. EVT VT = ValueVTs[vti];
  6796. unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT);
  6797. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  6798. FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
  6799. Reg += NumRegisters;
  6800. }
  6801. }
  6802. }
  6803. ConstantsOut.clear();
  6804. }
  6805. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  6806. /// is 0.
  6807. MachineBasicBlock *
  6808. SelectionDAGBuilder::StackProtectorDescriptor::
  6809. AddSuccessorMBB(const BasicBlock *BB,
  6810. MachineBasicBlock *ParentMBB,
  6811. MachineBasicBlock *SuccMBB) {
  6812. // If SuccBB has not been created yet, create it.
  6813. if (!SuccMBB) {
  6814. MachineFunction *MF = ParentMBB->getParent();
  6815. MachineFunction::iterator BBI = ParentMBB;
  6816. SuccMBB = MF->CreateMachineBasicBlock(BB);
  6817. MF->insert(++BBI, SuccMBB);
  6818. }
  6819. // Add it as a successor of ParentMBB.
  6820. ParentMBB->addSuccessor(SuccMBB);
  6821. return SuccMBB;
  6822. }