SelectionDAGBuilder.cpp 294 KB

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