SelectionDAGBuilder.cpp 270 KB

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