SelectionDAGBuilder.cpp 268 KB

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