SelectionDAGBuild.cpp 235 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058
  1. //===-- SelectionDAGBuild.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 "SelectionDAGBuild.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/Analysis/AliasAnalysis.h"
  18. #include "llvm/Constants.h"
  19. #include "llvm/CallingConv.h"
  20. #include "llvm/DerivedTypes.h"
  21. #include "llvm/Function.h"
  22. #include "llvm/GlobalVariable.h"
  23. #include "llvm/InlineAsm.h"
  24. #include "llvm/Instructions.h"
  25. #include "llvm/Intrinsics.h"
  26. #include "llvm/IntrinsicInst.h"
  27. #include "llvm/Module.h"
  28. #include "llvm/CodeGen/FastISel.h"
  29. #include "llvm/CodeGen/GCStrategy.h"
  30. #include "llvm/CodeGen/GCMetadata.h"
  31. #include "llvm/CodeGen/MachineFunction.h"
  32. #include "llvm/CodeGen/MachineFrameInfo.h"
  33. #include "llvm/CodeGen/MachineInstrBuilder.h"
  34. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  35. #include "llvm/CodeGen/MachineModuleInfo.h"
  36. #include "llvm/CodeGen/MachineRegisterInfo.h"
  37. #include "llvm/CodeGen/PseudoSourceValue.h"
  38. #include "llvm/CodeGen/SelectionDAG.h"
  39. #include "llvm/CodeGen/DwarfWriter.h"
  40. #include "llvm/Analysis/DebugInfo.h"
  41. #include "llvm/Target/TargetRegisterInfo.h"
  42. #include "llvm/Target/TargetData.h"
  43. #include "llvm/Target/TargetFrameInfo.h"
  44. #include "llvm/Target/TargetInstrInfo.h"
  45. #include "llvm/Target/TargetIntrinsicInfo.h"
  46. #include "llvm/Target/TargetLowering.h"
  47. #include "llvm/Target/TargetMachine.h"
  48. #include "llvm/Target/TargetOptions.h"
  49. #include "llvm/Support/Compiler.h"
  50. #include "llvm/Support/CommandLine.h"
  51. #include "llvm/Support/Debug.h"
  52. #include "llvm/Support/MathExtras.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include <algorithm>
  55. using namespace llvm;
  56. /// LimitFloatPrecision - Generate low-precision inline sequences for
  57. /// some float libcalls (6, 8 or 12 bits).
  58. static unsigned LimitFloatPrecision;
  59. static cl::opt<unsigned, true>
  60. LimitFPPrecision("limit-float-precision",
  61. cl::desc("Generate low-precision inline sequences "
  62. "for some float libcalls"),
  63. cl::location(LimitFloatPrecision),
  64. cl::init(0));
  65. /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
  66. /// of insertvalue or extractvalue indices that identify a member, return
  67. /// the linearized index of the start of the member.
  68. ///
  69. static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
  70. const unsigned *Indices,
  71. const unsigned *IndicesEnd,
  72. unsigned CurIndex = 0) {
  73. // Base case: We're done.
  74. if (Indices && Indices == IndicesEnd)
  75. return CurIndex;
  76. // Given a struct type, recursively traverse the elements.
  77. if (const StructType *STy = dyn_cast<StructType>(Ty)) {
  78. for (StructType::element_iterator EB = STy->element_begin(),
  79. EI = EB,
  80. EE = STy->element_end();
  81. EI != EE; ++EI) {
  82. if (Indices && *Indices == unsigned(EI - EB))
  83. return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
  84. CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
  85. }
  86. return CurIndex;
  87. }
  88. // Given an array type, recursively traverse the elements.
  89. else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  90. const Type *EltTy = ATy->getElementType();
  91. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
  92. if (Indices && *Indices == i)
  93. return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
  94. CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
  95. }
  96. return CurIndex;
  97. }
  98. // We haven't found the type we're looking for, so keep searching.
  99. return CurIndex + 1;
  100. }
  101. /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
  102. /// MVTs that represent all the individual underlying
  103. /// non-aggregate types that comprise it.
  104. ///
  105. /// If Offsets is non-null, it points to a vector to be filled in
  106. /// with the in-memory offsets of each of the individual values.
  107. ///
  108. static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
  109. SmallVectorImpl<MVT> &ValueVTs,
  110. SmallVectorImpl<uint64_t> *Offsets = 0,
  111. uint64_t StartingOffset = 0) {
  112. // Given a struct type, recursively traverse the elements.
  113. if (const StructType *STy = dyn_cast<StructType>(Ty)) {
  114. const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
  115. for (StructType::element_iterator EB = STy->element_begin(),
  116. EI = EB,
  117. EE = STy->element_end();
  118. EI != EE; ++EI)
  119. ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
  120. StartingOffset + SL->getElementOffset(EI - EB));
  121. return;
  122. }
  123. // Given an array type, recursively traverse the elements.
  124. if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  125. const Type *EltTy = ATy->getElementType();
  126. uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
  127. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
  128. ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
  129. StartingOffset + i * EltSize);
  130. return;
  131. }
  132. // Interpret void as zero return values.
  133. if (Ty == Type::VoidTy)
  134. return;
  135. // Base case: we can get an MVT for this LLVM IR type.
  136. ValueVTs.push_back(TLI.getValueType(Ty));
  137. if (Offsets)
  138. Offsets->push_back(StartingOffset);
  139. }
  140. namespace llvm {
  141. /// RegsForValue - This struct represents the registers (physical or virtual)
  142. /// that a particular set of values is assigned, and the type information about
  143. /// the value. The most common situation is to represent one value at a time,
  144. /// but struct or array values are handled element-wise as multiple values.
  145. /// The splitting of aggregates is performed recursively, so that we never
  146. /// have aggregate-typed registers. The values at this point do not necessarily
  147. /// have legal types, so each value may require one or more registers of some
  148. /// legal type.
  149. ///
  150. struct VISIBILITY_HIDDEN RegsForValue {
  151. /// TLI - The TargetLowering object.
  152. ///
  153. const TargetLowering *TLI;
  154. /// ValueVTs - The value types of the values, which may not be legal, and
  155. /// may need be promoted or synthesized from one or more registers.
  156. ///
  157. SmallVector<MVT, 4> ValueVTs;
  158. /// RegVTs - The value types of the registers. This is the same size as
  159. /// ValueVTs and it records, for each value, what the type of the assigned
  160. /// register or registers are. (Individual values are never synthesized
  161. /// from more than one type of register.)
  162. ///
  163. /// With virtual registers, the contents of RegVTs is redundant with TLI's
  164. /// getRegisterType member function, however when with physical registers
  165. /// it is necessary to have a separate record of the types.
  166. ///
  167. SmallVector<MVT, 4> RegVTs;
  168. /// Regs - This list holds the registers assigned to the values.
  169. /// Each legal or promoted value requires one register, and each
  170. /// expanded value requires multiple registers.
  171. ///
  172. SmallVector<unsigned, 4> Regs;
  173. RegsForValue() : TLI(0) {}
  174. RegsForValue(const TargetLowering &tli,
  175. const SmallVector<unsigned, 4> &regs,
  176. MVT regvt, MVT valuevt)
  177. : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
  178. RegsForValue(const TargetLowering &tli,
  179. const SmallVector<unsigned, 4> &regs,
  180. const SmallVector<MVT, 4> &regvts,
  181. const SmallVector<MVT, 4> &valuevts)
  182. : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
  183. RegsForValue(const TargetLowering &tli,
  184. unsigned Reg, const Type *Ty) : TLI(&tli) {
  185. ComputeValueVTs(tli, Ty, ValueVTs);
  186. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  187. MVT ValueVT = ValueVTs[Value];
  188. unsigned NumRegs = TLI->getNumRegisters(ValueVT);
  189. MVT RegisterVT = TLI->getRegisterType(ValueVT);
  190. for (unsigned i = 0; i != NumRegs; ++i)
  191. Regs.push_back(Reg + i);
  192. RegVTs.push_back(RegisterVT);
  193. Reg += NumRegs;
  194. }
  195. }
  196. /// append - Add the specified values to this one.
  197. void append(const RegsForValue &RHS) {
  198. TLI = RHS.TLI;
  199. ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
  200. RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
  201. Regs.append(RHS.Regs.begin(), RHS.Regs.end());
  202. }
  203. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  204. /// this value and returns the result as a ValueVTs value. This uses
  205. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  206. /// If the Flag pointer is NULL, no flag is used.
  207. SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
  208. SDValue &Chain, SDValue *Flag) const;
  209. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  210. /// specified value into the registers specified by this object. This uses
  211. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  212. /// If the Flag pointer is NULL, no flag is used.
  213. void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
  214. SDValue &Chain, SDValue *Flag) const;
  215. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  216. /// operand list. This adds the code marker, matching input operand index
  217. /// (if applicable), and includes the number of values added into it.
  218. void AddInlineAsmOperands(unsigned Code,
  219. bool HasMatching, unsigned MatchingIdx,
  220. SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
  221. };
  222. }
  223. /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
  224. /// PHI nodes or outside of the basic block that defines it, or used by a
  225. /// switch or atomic instruction, which may expand to multiple basic blocks.
  226. static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
  227. if (isa<PHINode>(I)) return true;
  228. BasicBlock *BB = I->getParent();
  229. for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
  230. if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
  231. return true;
  232. return false;
  233. }
  234. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  235. /// entry block, return true. This includes arguments used by switches, since
  236. /// the switch may expand into multiple basic blocks.
  237. static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
  238. // With FastISel active, we may be splitting blocks, so force creation
  239. // of virtual registers for all non-dead arguments.
  240. // Don't force virtual registers for byval arguments though, because
  241. // fast-isel can't handle those in all cases.
  242. if (EnableFastISel && !A->hasByValAttr())
  243. return A->use_empty();
  244. BasicBlock *Entry = A->getParent()->begin();
  245. for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
  246. if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
  247. return false; // Use not in entry block.
  248. return true;
  249. }
  250. FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
  251. : TLI(tli) {
  252. }
  253. void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
  254. SelectionDAG &DAG,
  255. bool EnableFastISel) {
  256. Fn = &fn;
  257. MF = &mf;
  258. RegInfo = &MF->getRegInfo();
  259. // Create a vreg for each argument register that is not dead and is used
  260. // outside of the entry block for the function.
  261. for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
  262. AI != E; ++AI)
  263. if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
  264. InitializeRegForValue(AI);
  265. // Initialize the mapping of values to registers. This is only set up for
  266. // instruction values that are used outside of the block that defines
  267. // them.
  268. Function::iterator BB = Fn->begin(), EB = Fn->end();
  269. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  270. if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
  271. if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
  272. const Type *Ty = AI->getAllocatedType();
  273. uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
  274. unsigned Align =
  275. std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
  276. AI->getAlignment());
  277. TySize *= CUI->getZExtValue(); // Get total allocated size.
  278. if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
  279. StaticAllocaMap[AI] =
  280. MF->getFrameInfo()->CreateStackObject(TySize, Align);
  281. }
  282. for (; BB != EB; ++BB)
  283. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  284. if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
  285. if (!isa<AllocaInst>(I) ||
  286. !StaticAllocaMap.count(cast<AllocaInst>(I)))
  287. InitializeRegForValue(I);
  288. // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
  289. // also creates the initial PHI MachineInstrs, though none of the input
  290. // operands are populated.
  291. for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
  292. MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
  293. MBBMap[BB] = MBB;
  294. MF->push_back(MBB);
  295. // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
  296. // appropriate.
  297. PHINode *PN;
  298. DebugLoc DL;
  299. for (BasicBlock::iterator
  300. I = BB->begin(), E = BB->end(); I != E; ++I) {
  301. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  302. if (Function *F = CI->getCalledFunction()) {
  303. switch (F->getIntrinsicID()) {
  304. default: break;
  305. case Intrinsic::dbg_stoppoint: {
  306. DwarfWriter *DW = DAG.getDwarfWriter();
  307. DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
  308. if (DW && DW->ValidDebugInfo(SPI->getContext(), false)) {
  309. DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
  310. std::string Dir, FN;
  311. unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
  312. CU.getFilename(FN));
  313. unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
  314. SPI->getLine(),
  315. SPI->getColumn());
  316. DL = DebugLoc::get(idx);
  317. }
  318. break;
  319. }
  320. case Intrinsic::dbg_func_start: {
  321. DwarfWriter *DW = DAG.getDwarfWriter();
  322. if (DW) {
  323. DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
  324. Value *SP = FSI->getSubprogram();
  325. if (DW->ValidDebugInfo(SP, false)) {
  326. DISubprogram Subprogram(cast<GlobalVariable>(SP));
  327. DICompileUnit CU(Subprogram.getCompileUnit());
  328. std::string Dir, FN;
  329. unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
  330. CU.getFilename(FN));
  331. unsigned Line = Subprogram.getLineNumber();
  332. DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
  333. }
  334. }
  335. break;
  336. }
  337. }
  338. }
  339. }
  340. PN = dyn_cast<PHINode>(I);
  341. if (!PN || PN->use_empty()) continue;
  342. unsigned PHIReg = ValueMap[PN];
  343. assert(PHIReg && "PHI node does not have an assigned virtual register!");
  344. SmallVector<MVT, 4> ValueVTs;
  345. ComputeValueVTs(TLI, PN->getType(), ValueVTs);
  346. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  347. MVT VT = ValueVTs[vti];
  348. unsigned NumRegisters = TLI.getNumRegisters(VT);
  349. const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
  350. for (unsigned i = 0; i != NumRegisters; ++i)
  351. BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
  352. PHIReg += NumRegisters;
  353. }
  354. }
  355. }
  356. }
  357. unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
  358. return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
  359. }
  360. /// CreateRegForValue - Allocate the appropriate number of virtual registers of
  361. /// the correctly promoted or expanded types. Assign these registers
  362. /// consecutive vreg numbers and return the first assigned number.
  363. ///
  364. /// In the case that the given value has struct or array type, this function
  365. /// will assign registers for each member or element.
  366. ///
  367. unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
  368. SmallVector<MVT, 4> ValueVTs;
  369. ComputeValueVTs(TLI, V->getType(), ValueVTs);
  370. unsigned FirstReg = 0;
  371. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  372. MVT ValueVT = ValueVTs[Value];
  373. MVT RegisterVT = TLI.getRegisterType(ValueVT);
  374. unsigned NumRegs = TLI.getNumRegisters(ValueVT);
  375. for (unsigned i = 0; i != NumRegs; ++i) {
  376. unsigned R = MakeReg(RegisterVT);
  377. if (!FirstReg) FirstReg = R;
  378. }
  379. }
  380. return FirstReg;
  381. }
  382. /// getCopyFromParts - Create a value that contains the specified legal parts
  383. /// combined into the value they represent. If the parts combine to a type
  384. /// larger then ValueVT then AssertOp can be used to specify whether the extra
  385. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  386. /// (ISD::AssertSext).
  387. static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
  388. const SDValue *Parts,
  389. unsigned NumParts, MVT PartVT, MVT ValueVT,
  390. ISD::NodeType AssertOp = ISD::DELETED_NODE) {
  391. assert(NumParts > 0 && "No parts to assemble!");
  392. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  393. SDValue Val = Parts[0];
  394. if (NumParts > 1) {
  395. // Assemble the value from multiple parts.
  396. if (!ValueVT.isVector()) {
  397. unsigned PartBits = PartVT.getSizeInBits();
  398. unsigned ValueBits = ValueVT.getSizeInBits();
  399. // Assemble the power of 2 part.
  400. unsigned RoundParts = NumParts & (NumParts - 1) ?
  401. 1 << Log2_32(NumParts) : NumParts;
  402. unsigned RoundBits = PartBits * RoundParts;
  403. MVT RoundVT = RoundBits == ValueBits ?
  404. ValueVT : MVT::getIntegerVT(RoundBits);
  405. SDValue Lo, Hi;
  406. MVT HalfVT = ValueVT.isInteger() ?
  407. MVT::getIntegerVT(RoundBits/2) :
  408. MVT::getFloatingPointVT(RoundBits/2);
  409. if (RoundParts > 2) {
  410. Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
  411. Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
  412. PartVT, HalfVT);
  413. } else {
  414. Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
  415. Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
  416. }
  417. if (TLI.isBigEndian())
  418. std::swap(Lo, Hi);
  419. Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
  420. if (RoundParts < NumParts) {
  421. // Assemble the trailing non-power-of-2 part.
  422. unsigned OddParts = NumParts - RoundParts;
  423. MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
  424. Hi = getCopyFromParts(DAG, dl,
  425. Parts+RoundParts, OddParts, PartVT, OddVT);
  426. // Combine the round and odd parts.
  427. Lo = Val;
  428. if (TLI.isBigEndian())
  429. std::swap(Lo, Hi);
  430. MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
  431. Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
  432. Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
  433. DAG.getConstant(Lo.getValueType().getSizeInBits(),
  434. TLI.getPointerTy()));
  435. Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
  436. Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
  437. }
  438. } else {
  439. // Handle a multi-element vector.
  440. MVT IntermediateVT, RegisterVT;
  441. unsigned NumIntermediates;
  442. unsigned NumRegs =
  443. TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
  444. RegisterVT);
  445. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  446. NumParts = NumRegs; // Silence a compiler warning.
  447. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  448. assert(RegisterVT == Parts[0].getValueType() &&
  449. "Part type doesn't match part!");
  450. // Assemble the parts into intermediate operands.
  451. SmallVector<SDValue, 8> Ops(NumIntermediates);
  452. if (NumIntermediates == NumParts) {
  453. // If the register was not expanded, truncate or copy the value,
  454. // as appropriate.
  455. for (unsigned i = 0; i != NumParts; ++i)
  456. Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
  457. PartVT, IntermediateVT);
  458. } else if (NumParts > 0) {
  459. // If the intermediate type was expanded, build the intermediate operands
  460. // from the parts.
  461. assert(NumParts % NumIntermediates == 0 &&
  462. "Must expand into a divisible number of parts!");
  463. unsigned Factor = NumParts / NumIntermediates;
  464. for (unsigned i = 0; i != NumIntermediates; ++i)
  465. Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
  466. PartVT, IntermediateVT);
  467. }
  468. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
  469. // operands.
  470. Val = DAG.getNode(IntermediateVT.isVector() ?
  471. ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
  472. ValueVT, &Ops[0], NumIntermediates);
  473. }
  474. }
  475. // There is now one part, held in Val. Correct it to match ValueVT.
  476. PartVT = Val.getValueType();
  477. if (PartVT == ValueVT)
  478. return Val;
  479. if (PartVT.isVector()) {
  480. assert(ValueVT.isVector() && "Unknown vector conversion!");
  481. return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
  482. }
  483. if (ValueVT.isVector()) {
  484. assert(ValueVT.getVectorElementType() == PartVT &&
  485. ValueVT.getVectorNumElements() == 1 &&
  486. "Only trivial scalar-to-vector conversions should get here!");
  487. return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
  488. }
  489. if (PartVT.isInteger() &&
  490. ValueVT.isInteger()) {
  491. if (ValueVT.bitsLT(PartVT)) {
  492. // For a truncate, see if we have any information to
  493. // indicate whether the truncated bits will always be
  494. // zero or sign-extension.
  495. if (AssertOp != ISD::DELETED_NODE)
  496. Val = DAG.getNode(AssertOp, dl, PartVT, Val,
  497. DAG.getValueType(ValueVT));
  498. return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
  499. } else {
  500. return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
  501. }
  502. }
  503. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  504. if (ValueVT.bitsLT(Val.getValueType()))
  505. // FP_ROUND's are always exact here.
  506. return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
  507. DAG.getIntPtrConstant(1));
  508. return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
  509. }
  510. if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
  511. return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
  512. assert(0 && "Unknown mismatch!");
  513. return SDValue();
  514. }
  515. /// getCopyToParts - Create a series of nodes that contain the specified value
  516. /// split into legal parts. If the parts contain more bits than Val, then, for
  517. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  518. static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
  519. SDValue *Parts, unsigned NumParts, MVT PartVT,
  520. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  521. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  522. MVT PtrVT = TLI.getPointerTy();
  523. MVT ValueVT = Val.getValueType();
  524. unsigned PartBits = PartVT.getSizeInBits();
  525. unsigned OrigNumParts = NumParts;
  526. assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
  527. if (!NumParts)
  528. return;
  529. if (!ValueVT.isVector()) {
  530. if (PartVT == ValueVT) {
  531. assert(NumParts == 1 && "No-op copy with multiple parts!");
  532. Parts[0] = Val;
  533. return;
  534. }
  535. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  536. // If the parts cover more bits than the value has, promote the value.
  537. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  538. assert(NumParts == 1 && "Do not know what to promote to!");
  539. Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
  540. } else if (PartVT.isInteger() && ValueVT.isInteger()) {
  541. ValueVT = MVT::getIntegerVT(NumParts * PartBits);
  542. Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
  543. } else {
  544. assert(0 && "Unknown mismatch!");
  545. }
  546. } else if (PartBits == ValueVT.getSizeInBits()) {
  547. // Different types of the same size.
  548. assert(NumParts == 1 && PartVT != ValueVT);
  549. Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
  550. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  551. // If the parts cover less bits than value has, truncate the value.
  552. if (PartVT.isInteger() && ValueVT.isInteger()) {
  553. ValueVT = MVT::getIntegerVT(NumParts * PartBits);
  554. Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
  555. } else {
  556. assert(0 && "Unknown mismatch!");
  557. }
  558. }
  559. // The value may have changed - recompute ValueVT.
  560. ValueVT = Val.getValueType();
  561. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  562. "Failed to tile the value with PartVT!");
  563. if (NumParts == 1) {
  564. assert(PartVT == ValueVT && "Type conversion failed!");
  565. Parts[0] = Val;
  566. return;
  567. }
  568. // Expand the value into multiple parts.
  569. if (NumParts & (NumParts - 1)) {
  570. // The number of parts is not a power of 2. Split off and copy the tail.
  571. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  572. "Do not know what to expand to!");
  573. unsigned RoundParts = 1 << Log2_32(NumParts);
  574. unsigned RoundBits = RoundParts * PartBits;
  575. unsigned OddParts = NumParts - RoundParts;
  576. SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
  577. DAG.getConstant(RoundBits,
  578. TLI.getPointerTy()));
  579. getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
  580. if (TLI.isBigEndian())
  581. // The odd parts were reversed by getCopyToParts - unreverse them.
  582. std::reverse(Parts + RoundParts, Parts + NumParts);
  583. NumParts = RoundParts;
  584. ValueVT = MVT::getIntegerVT(NumParts * PartBits);
  585. Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
  586. }
  587. // The number of parts is a power of 2. Repeatedly bisect the value using
  588. // EXTRACT_ELEMENT.
  589. Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
  590. MVT::getIntegerVT(ValueVT.getSizeInBits()),
  591. Val);
  592. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  593. for (unsigned i = 0; i < NumParts; i += StepSize) {
  594. unsigned ThisBits = StepSize * PartBits / 2;
  595. MVT ThisVT = MVT::getIntegerVT (ThisBits);
  596. SDValue &Part0 = Parts[i];
  597. SDValue &Part1 = Parts[i+StepSize/2];
  598. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
  599. ThisVT, Part0,
  600. DAG.getConstant(1, PtrVT));
  601. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
  602. ThisVT, Part0,
  603. DAG.getConstant(0, PtrVT));
  604. if (ThisBits == PartBits && ThisVT != PartVT) {
  605. Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
  606. PartVT, Part0);
  607. Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
  608. PartVT, Part1);
  609. }
  610. }
  611. }
  612. if (TLI.isBigEndian())
  613. std::reverse(Parts, Parts + OrigNumParts);
  614. return;
  615. }
  616. // Vector ValueVT.
  617. if (NumParts == 1) {
  618. if (PartVT != ValueVT) {
  619. if (PartVT.isVector()) {
  620. Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
  621. } else {
  622. assert(ValueVT.getVectorElementType() == PartVT &&
  623. ValueVT.getVectorNumElements() == 1 &&
  624. "Only trivial vector-to-scalar conversions should get here!");
  625. Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
  626. PartVT, Val,
  627. DAG.getConstant(0, PtrVT));
  628. }
  629. }
  630. Parts[0] = Val;
  631. return;
  632. }
  633. // Handle a multi-element vector.
  634. MVT IntermediateVT, RegisterVT;
  635. unsigned NumIntermediates;
  636. unsigned NumRegs = TLI
  637. .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
  638. RegisterVT);
  639. unsigned NumElements = ValueVT.getVectorNumElements();
  640. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  641. NumParts = NumRegs; // Silence a compiler warning.
  642. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  643. // Split the vector into intermediate operands.
  644. SmallVector<SDValue, 8> Ops(NumIntermediates);
  645. for (unsigned i = 0; i != NumIntermediates; ++i)
  646. if (IntermediateVT.isVector())
  647. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
  648. IntermediateVT, Val,
  649. DAG.getConstant(i * (NumElements / NumIntermediates),
  650. PtrVT));
  651. else
  652. Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
  653. IntermediateVT, Val,
  654. DAG.getConstant(i, PtrVT));
  655. // Split the intermediate operands into legal parts.
  656. if (NumParts == NumIntermediates) {
  657. // If the register was not expanded, promote or copy the value,
  658. // as appropriate.
  659. for (unsigned i = 0; i != NumParts; ++i)
  660. getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
  661. } else if (NumParts > 0) {
  662. // If the intermediate type was expanded, split each the value into
  663. // legal parts.
  664. assert(NumParts % NumIntermediates == 0 &&
  665. "Must expand into a divisible number of parts!");
  666. unsigned Factor = NumParts / NumIntermediates;
  667. for (unsigned i = 0; i != NumIntermediates; ++i)
  668. getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
  669. }
  670. }
  671. void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
  672. AA = &aa;
  673. GFI = gfi;
  674. TD = DAG.getTarget().getTargetData();
  675. }
  676. /// clear - Clear out the curret SelectionDAG and the associated
  677. /// state and prepare this SelectionDAGLowering object to be used
  678. /// for a new block. This doesn't clear out information about
  679. /// additional blocks that are needed to complete switch lowering
  680. /// or PHI node updating; that information is cleared out as it is
  681. /// consumed.
  682. void SelectionDAGLowering::clear() {
  683. NodeMap.clear();
  684. PendingLoads.clear();
  685. PendingExports.clear();
  686. DAG.clear();
  687. CurDebugLoc = DebugLoc::getUnknownLoc();
  688. }
  689. /// getRoot - Return the current virtual root of the Selection DAG,
  690. /// flushing any PendingLoad items. This must be done before emitting
  691. /// a store or any other node that may need to be ordered after any
  692. /// prior load instructions.
  693. ///
  694. SDValue SelectionDAGLowering::getRoot() {
  695. if (PendingLoads.empty())
  696. return DAG.getRoot();
  697. if (PendingLoads.size() == 1) {
  698. SDValue Root = PendingLoads[0];
  699. DAG.setRoot(Root);
  700. PendingLoads.clear();
  701. return Root;
  702. }
  703. // Otherwise, we have to make a token factor node.
  704. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
  705. &PendingLoads[0], PendingLoads.size());
  706. PendingLoads.clear();
  707. DAG.setRoot(Root);
  708. return Root;
  709. }
  710. /// getControlRoot - Similar to getRoot, but instead of flushing all the
  711. /// PendingLoad items, flush all the PendingExports items. It is necessary
  712. /// to do this before emitting a terminator instruction.
  713. ///
  714. SDValue SelectionDAGLowering::getControlRoot() {
  715. SDValue Root = DAG.getRoot();
  716. if (PendingExports.empty())
  717. return Root;
  718. // Turn all of the CopyToReg chains into one factored node.
  719. if (Root.getOpcode() != ISD::EntryToken) {
  720. unsigned i = 0, e = PendingExports.size();
  721. for (; i != e; ++i) {
  722. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  723. if (PendingExports[i].getNode()->getOperand(0) == Root)
  724. break; // Don't add the root if we already indirectly depend on it.
  725. }
  726. if (i == e)
  727. PendingExports.push_back(Root);
  728. }
  729. Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
  730. &PendingExports[0],
  731. PendingExports.size());
  732. PendingExports.clear();
  733. DAG.setRoot(Root);
  734. return Root;
  735. }
  736. void SelectionDAGLowering::visit(Instruction &I) {
  737. visit(I.getOpcode(), I);
  738. }
  739. void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
  740. // Note: this doesn't use InstVisitor, because it has to work with
  741. // ConstantExpr's in addition to instructions.
  742. switch (Opcode) {
  743. default: assert(0 && "Unknown instruction type encountered!");
  744. abort();
  745. // Build the switch statement using the Instruction.def file.
  746. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  747. case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
  748. #include "llvm/Instruction.def"
  749. }
  750. }
  751. void SelectionDAGLowering::visitAdd(User &I) {
  752. if (I.getType()->isFPOrFPVector())
  753. visitBinary(I, ISD::FADD);
  754. else
  755. visitBinary(I, ISD::ADD);
  756. }
  757. void SelectionDAGLowering::visitMul(User &I) {
  758. if (I.getType()->isFPOrFPVector())
  759. visitBinary(I, ISD::FMUL);
  760. else
  761. visitBinary(I, ISD::MUL);
  762. }
  763. SDValue SelectionDAGLowering::getValue(const Value *V) {
  764. SDValue &N = NodeMap[V];
  765. if (N.getNode()) return N;
  766. if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
  767. MVT VT = TLI.getValueType(V->getType(), true);
  768. if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
  769. return N = DAG.getConstant(*CI, VT);
  770. if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
  771. return N = DAG.getGlobalAddress(GV, VT);
  772. if (isa<ConstantPointerNull>(C))
  773. return N = DAG.getConstant(0, TLI.getPointerTy());
  774. if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  775. return N = DAG.getConstantFP(*CFP, VT);
  776. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  777. return N = DAG.getUNDEF(VT);
  778. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  779. visit(CE->getOpcode(), *CE);
  780. SDValue N1 = NodeMap[V];
  781. assert(N1.getNode() && "visit didn't populate the ValueMap!");
  782. return N1;
  783. }
  784. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  785. SmallVector<SDValue, 4> Constants;
  786. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  787. OI != OE; ++OI) {
  788. SDNode *Val = getValue(*OI).getNode();
  789. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  790. Constants.push_back(SDValue(Val, i));
  791. }
  792. return DAG.getMergeValues(&Constants[0], Constants.size(),
  793. getCurDebugLoc());
  794. }
  795. if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
  796. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  797. "Unknown struct or array constant!");
  798. SmallVector<MVT, 4> ValueVTs;
  799. ComputeValueVTs(TLI, C->getType(), ValueVTs);
  800. unsigned NumElts = ValueVTs.size();
  801. if (NumElts == 0)
  802. return SDValue(); // empty struct
  803. SmallVector<SDValue, 4> Constants(NumElts);
  804. for (unsigned i = 0; i != NumElts; ++i) {
  805. MVT EltVT = ValueVTs[i];
  806. if (isa<UndefValue>(C))
  807. Constants[i] = DAG.getUNDEF(EltVT);
  808. else if (EltVT.isFloatingPoint())
  809. Constants[i] = DAG.getConstantFP(0, EltVT);
  810. else
  811. Constants[i] = DAG.getConstant(0, EltVT);
  812. }
  813. return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
  814. }
  815. const VectorType *VecTy = cast<VectorType>(V->getType());
  816. unsigned NumElements = VecTy->getNumElements();
  817. // Now that we know the number and type of the elements, get that number of
  818. // elements into the Ops array based on what kind of constant it is.
  819. SmallVector<SDValue, 16> Ops;
  820. if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
  821. for (unsigned i = 0; i != NumElements; ++i)
  822. Ops.push_back(getValue(CP->getOperand(i)));
  823. } else {
  824. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  825. MVT EltVT = TLI.getValueType(VecTy->getElementType());
  826. SDValue Op;
  827. if (EltVT.isFloatingPoint())
  828. Op = DAG.getConstantFP(0, EltVT);
  829. else
  830. Op = DAG.getConstant(0, EltVT);
  831. Ops.assign(NumElements, Op);
  832. }
  833. // Create a BUILD_VECTOR node.
  834. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
  835. VT, &Ops[0], Ops.size());
  836. }
  837. // If this is a static alloca, generate it as the frameindex instead of
  838. // computation.
  839. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  840. DenseMap<const AllocaInst*, int>::iterator SI =
  841. FuncInfo.StaticAllocaMap.find(AI);
  842. if (SI != FuncInfo.StaticAllocaMap.end())
  843. return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
  844. }
  845. unsigned InReg = FuncInfo.ValueMap[V];
  846. assert(InReg && "Value not in map!");
  847. RegsForValue RFV(TLI, InReg, V->getType());
  848. SDValue Chain = DAG.getEntryNode();
  849. return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
  850. }
  851. void SelectionDAGLowering::visitRet(ReturnInst &I) {
  852. if (I.getNumOperands() == 0) {
  853. DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
  854. MVT::Other, getControlRoot()));
  855. return;
  856. }
  857. SmallVector<SDValue, 8> NewValues;
  858. NewValues.push_back(getControlRoot());
  859. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
  860. SmallVector<MVT, 4> ValueVTs;
  861. ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
  862. unsigned NumValues = ValueVTs.size();
  863. if (NumValues == 0) continue;
  864. SDValue RetOp = getValue(I.getOperand(i));
  865. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  866. MVT VT = ValueVTs[j];
  867. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  868. const Function *F = I.getParent()->getParent();
  869. if (F->paramHasAttr(0, Attribute::SExt))
  870. ExtendKind = ISD::SIGN_EXTEND;
  871. else if (F->paramHasAttr(0, Attribute::ZExt))
  872. ExtendKind = ISD::ZERO_EXTEND;
  873. // FIXME: C calling convention requires the return type to be promoted to
  874. // at least 32-bit. But this is not necessary for non-C calling
  875. // conventions. The frontend should mark functions whose return values
  876. // require promoting with signext or zeroext attributes.
  877. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
  878. MVT MinVT = TLI.getRegisterType(MVT::i32);
  879. if (VT.bitsLT(MinVT))
  880. VT = MinVT;
  881. }
  882. unsigned NumParts = TLI.getNumRegisters(VT);
  883. MVT PartVT = TLI.getRegisterType(VT);
  884. SmallVector<SDValue, 4> Parts(NumParts);
  885. getCopyToParts(DAG, getCurDebugLoc(),
  886. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  887. &Parts[0], NumParts, PartVT, ExtendKind);
  888. // 'inreg' on function refers to return value
  889. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  890. if (F->paramHasAttr(0, Attribute::InReg))
  891. Flags.setInReg();
  892. for (unsigned i = 0; i < NumParts; ++i) {
  893. NewValues.push_back(Parts[i]);
  894. NewValues.push_back(DAG.getArgFlags(Flags));
  895. }
  896. }
  897. }
  898. DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
  899. &NewValues[0], NewValues.size()));
  900. }
  901. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  902. /// created for it, emit nodes to copy the value into the virtual
  903. /// registers.
  904. void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
  905. if (!V->use_empty()) {
  906. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  907. if (VMI != FuncInfo.ValueMap.end())
  908. CopyValueToVirtualRegister(V, VMI->second);
  909. }
  910. }
  911. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  912. /// the current basic block, add it to ValueMap now so that we'll get a
  913. /// CopyTo/FromReg.
  914. void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
  915. // No need to export constants.
  916. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  917. // Already exported?
  918. if (FuncInfo.isExportedInst(V)) return;
  919. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  920. CopyValueToVirtualRegister(V, Reg);
  921. }
  922. bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
  923. const BasicBlock *FromBB) {
  924. // The operands of the setcc have to be in this block. We don't know
  925. // how to export them from some other block.
  926. if (Instruction *VI = dyn_cast<Instruction>(V)) {
  927. // Can export from current BB.
  928. if (VI->getParent() == FromBB)
  929. return true;
  930. // Is already exported, noop.
  931. return FuncInfo.isExportedInst(V);
  932. }
  933. // If this is an argument, we can export it if the BB is the entry block or
  934. // if it is already exported.
  935. if (isa<Argument>(V)) {
  936. if (FromBB == &FromBB->getParent()->getEntryBlock())
  937. return true;
  938. // Otherwise, can only export this if it is already exported.
  939. return FuncInfo.isExportedInst(V);
  940. }
  941. // Otherwise, constants can always be exported.
  942. return true;
  943. }
  944. static bool InBlock(const Value *V, const BasicBlock *BB) {
  945. if (const Instruction *I = dyn_cast<Instruction>(V))
  946. return I->getParent() == BB;
  947. return true;
  948. }
  949. /// getFCmpCondCode - Return the ISD condition code corresponding to
  950. /// the given LLVM IR floating-point condition code. This includes
  951. /// consideration of global floating-point math flags.
  952. ///
  953. static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
  954. ISD::CondCode FPC, FOC;
  955. switch (Pred) {
  956. case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
  957. case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
  958. case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
  959. case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
  960. case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
  961. case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
  962. case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
  963. case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
  964. case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
  965. case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
  966. case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
  967. case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
  968. case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
  969. case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
  970. case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
  971. case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
  972. default:
  973. assert(0 && "Invalid FCmp predicate opcode!");
  974. FOC = FPC = ISD::SETFALSE;
  975. break;
  976. }
  977. if (FiniteOnlyFPMath())
  978. return FOC;
  979. else
  980. return FPC;
  981. }
  982. /// getICmpCondCode - Return the ISD condition code corresponding to
  983. /// the given LLVM IR integer condition code.
  984. ///
  985. static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
  986. switch (Pred) {
  987. case ICmpInst::ICMP_EQ: return ISD::SETEQ;
  988. case ICmpInst::ICMP_NE: return ISD::SETNE;
  989. case ICmpInst::ICMP_SLE: return ISD::SETLE;
  990. case ICmpInst::ICMP_ULE: return ISD::SETULE;
  991. case ICmpInst::ICMP_SGE: return ISD::SETGE;
  992. case ICmpInst::ICMP_UGE: return ISD::SETUGE;
  993. case ICmpInst::ICMP_SLT: return ISD::SETLT;
  994. case ICmpInst::ICMP_ULT: return ISD::SETULT;
  995. case ICmpInst::ICMP_SGT: return ISD::SETGT;
  996. case ICmpInst::ICMP_UGT: return ISD::SETUGT;
  997. default:
  998. assert(0 && "Invalid ICmp predicate opcode!");
  999. return ISD::SETNE;
  1000. }
  1001. }
  1002. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1003. /// This function emits a branch and is used at the leaves of an OR or an
  1004. /// AND operator tree.
  1005. ///
  1006. void
  1007. SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
  1008. MachineBasicBlock *TBB,
  1009. MachineBasicBlock *FBB,
  1010. MachineBasicBlock *CurBB) {
  1011. const BasicBlock *BB = CurBB->getBasicBlock();
  1012. // If the leaf of the tree is a comparison, merge the condition into
  1013. // the caseblock.
  1014. if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1015. // The operands of the cmp have to be in this block. We don't know
  1016. // how to export them from some other block. If this is the first block
  1017. // of the sequence, no exporting is needed.
  1018. if (CurBB == CurMBB ||
  1019. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1020. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1021. ISD::CondCode Condition;
  1022. if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1023. Condition = getICmpCondCode(IC->getPredicate());
  1024. } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
  1025. Condition = getFCmpCondCode(FC->getPredicate());
  1026. } else {
  1027. Condition = ISD::SETEQ; // silence warning.
  1028. assert(0 && "Unknown compare instruction");
  1029. }
  1030. CaseBlock CB(Condition, BOp->getOperand(0),
  1031. BOp->getOperand(1), NULL, TBB, FBB, CurBB);
  1032. SwitchCases.push_back(CB);
  1033. return;
  1034. }
  1035. }
  1036. // Create a CaseBlock record representing this branch.
  1037. CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
  1038. NULL, TBB, FBB, CurBB);
  1039. SwitchCases.push_back(CB);
  1040. }
  1041. /// FindMergedConditions - If Cond is an expression like
  1042. void SelectionDAGLowering::FindMergedConditions(Value *Cond,
  1043. MachineBasicBlock *TBB,
  1044. MachineBasicBlock *FBB,
  1045. MachineBasicBlock *CurBB,
  1046. unsigned Opc) {
  1047. // If this node is not part of the or/and tree, emit it as a branch.
  1048. Instruction *BOp = dyn_cast<Instruction>(Cond);
  1049. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1050. (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
  1051. BOp->getParent() != CurBB->getBasicBlock() ||
  1052. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1053. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1054. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
  1055. return;
  1056. }
  1057. // Create TmpBB after CurBB.
  1058. MachineFunction::iterator BBI = CurBB;
  1059. MachineFunction &MF = DAG.getMachineFunction();
  1060. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1061. CurBB->getParent()->insert(++BBI, TmpBB);
  1062. if (Opc == Instruction::Or) {
  1063. // Codegen X | Y as:
  1064. // jmp_if_X TBB
  1065. // jmp TmpBB
  1066. // TmpBB:
  1067. // jmp_if_Y TBB
  1068. // jmp FBB
  1069. //
  1070. // Emit the LHS condition.
  1071. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
  1072. // Emit the RHS condition into TmpBB.
  1073. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
  1074. } else {
  1075. assert(Opc == Instruction::And && "Unknown merge op!");
  1076. // Codegen X & Y as:
  1077. // jmp_if_X TmpBB
  1078. // jmp FBB
  1079. // TmpBB:
  1080. // jmp_if_Y TBB
  1081. // jmp FBB
  1082. //
  1083. // This requires creation of TmpBB after CurBB.
  1084. // Emit the LHS condition.
  1085. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
  1086. // Emit the RHS condition into TmpBB.
  1087. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
  1088. }
  1089. }
  1090. /// If the set of cases should be emitted as a series of branches, return true.
  1091. /// If we should emit this as a bunch of and/or'd together conditions, return
  1092. /// false.
  1093. bool
  1094. SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
  1095. if (Cases.size() != 2) return true;
  1096. // If this is two comparisons of the same values or'd or and'd together, they
  1097. // will get folded into a single comparison, so don't emit two blocks.
  1098. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1099. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1100. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1101. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1102. return false;
  1103. }
  1104. return true;
  1105. }
  1106. void SelectionDAGLowering::visitBr(BranchInst &I) {
  1107. // Update machine-CFG edges.
  1108. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1109. // Figure out which block is immediately after the current one.
  1110. MachineBasicBlock *NextBlock = 0;
  1111. MachineFunction::iterator BBI = CurMBB;
  1112. if (++BBI != CurMBB->getParent()->end())
  1113. NextBlock = BBI;
  1114. if (I.isUnconditional()) {
  1115. // Update machine-CFG edges.
  1116. CurMBB->addSuccessor(Succ0MBB);
  1117. // If this is not a fall-through branch, emit the branch.
  1118. if (Succ0MBB != NextBlock)
  1119. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
  1120. MVT::Other, getControlRoot(),
  1121. DAG.getBasicBlock(Succ0MBB)));
  1122. return;
  1123. }
  1124. // If this condition is one of the special cases we handle, do special stuff
  1125. // now.
  1126. Value *CondVal = I.getCondition();
  1127. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1128. // If this is a series of conditions that are or'd or and'd together, emit
  1129. // this as a sequence of branches instead of setcc's with and/or operations.
  1130. // For example, instead of something like:
  1131. // cmp A, B
  1132. // C = seteq
  1133. // cmp D, E
  1134. // F = setle
  1135. // or C, F
  1136. // jnz foo
  1137. // Emit:
  1138. // cmp A, B
  1139. // je foo
  1140. // cmp D, E
  1141. // jle foo
  1142. //
  1143. if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1144. if (BOp->hasOneUse() &&
  1145. (BOp->getOpcode() == Instruction::And ||
  1146. BOp->getOpcode() == Instruction::Or)) {
  1147. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
  1148. // If the compares in later blocks need to use values not currently
  1149. // exported from this block, export them now. This block should always
  1150. // be the first entry.
  1151. assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
  1152. // Allow some cases to be rejected.
  1153. if (ShouldEmitAsBranches(SwitchCases)) {
  1154. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1155. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1156. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1157. }
  1158. // Emit the branch for this block.
  1159. visitSwitchCase(SwitchCases[0]);
  1160. SwitchCases.erase(SwitchCases.begin());
  1161. return;
  1162. }
  1163. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1164. // SwitchCases.
  1165. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1166. CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
  1167. SwitchCases.clear();
  1168. }
  1169. }
  1170. // Create a CaseBlock record representing this branch.
  1171. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
  1172. NULL, Succ0MBB, Succ1MBB, CurMBB);
  1173. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1174. // cond branch.
  1175. visitSwitchCase(CB);
  1176. }
  1177. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1178. /// the binary search tree resulting from lowering a switch instruction.
  1179. void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
  1180. SDValue Cond;
  1181. SDValue CondLHS = getValue(CB.CmpLHS);
  1182. DebugLoc dl = getCurDebugLoc();
  1183. // Build the setcc now.
  1184. if (CB.CmpMHS == NULL) {
  1185. // Fold "(X == true)" to X and "(X == false)" to !X to
  1186. // handle common cases produced by branch lowering.
  1187. if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
  1188. Cond = CondLHS;
  1189. else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
  1190. SDValue True = DAG.getConstant(1, CondLHS.getValueType());
  1191. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1192. } else
  1193. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1194. } else {
  1195. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1196. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1197. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1198. SDValue CmpOp = getValue(CB.CmpMHS);
  1199. MVT VT = CmpOp.getValueType();
  1200. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1201. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
  1202. ISD::SETLE);
  1203. } else {
  1204. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1205. VT, CmpOp, DAG.getConstant(Low, VT));
  1206. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1207. DAG.getConstant(High-Low, VT), ISD::SETULE);
  1208. }
  1209. }
  1210. // Update successor info
  1211. CurMBB->addSuccessor(CB.TrueBB);
  1212. CurMBB->addSuccessor(CB.FalseBB);
  1213. // Set NextBlock to be the MBB immediately after the current one, if any.
  1214. // This is used to avoid emitting unnecessary branches to the next block.
  1215. MachineBasicBlock *NextBlock = 0;
  1216. MachineFunction::iterator BBI = CurMBB;
  1217. if (++BBI != CurMBB->getParent()->end())
  1218. NextBlock = BBI;
  1219. // If the lhs block is the next block, invert the condition so that we can
  1220. // fall through to the lhs instead of the rhs block.
  1221. if (CB.TrueBB == NextBlock) {
  1222. std::swap(CB.TrueBB, CB.FalseBB);
  1223. SDValue True = DAG.getConstant(1, Cond.getValueType());
  1224. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1225. }
  1226. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1227. MVT::Other, getControlRoot(), Cond,
  1228. DAG.getBasicBlock(CB.TrueBB));
  1229. // If the branch was constant folded, fix up the CFG.
  1230. if (BrCond.getOpcode() == ISD::BR) {
  1231. CurMBB->removeSuccessor(CB.FalseBB);
  1232. DAG.setRoot(BrCond);
  1233. } else {
  1234. // Otherwise, go ahead and insert the false branch.
  1235. if (BrCond == getControlRoot())
  1236. CurMBB->removeSuccessor(CB.TrueBB);
  1237. if (CB.FalseBB == NextBlock)
  1238. DAG.setRoot(BrCond);
  1239. else
  1240. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1241. DAG.getBasicBlock(CB.FalseBB)));
  1242. }
  1243. }
  1244. /// visitJumpTable - Emit JumpTable node in the current MBB
  1245. void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
  1246. // Emit the code for the jump table
  1247. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1248. MVT PTy = TLI.getPointerTy();
  1249. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
  1250. JT.Reg, PTy);
  1251. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1252. DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
  1253. MVT::Other, Index.getValue(1),
  1254. Table, Index));
  1255. }
  1256. /// visitJumpTableHeader - This function emits necessary code to produce index
  1257. /// in the JumpTable from switch case.
  1258. void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
  1259. JumpTableHeader &JTH) {
  1260. // Subtract the lowest switch case value from the value being switched on and
  1261. // conditional branch to default mbb if the result is greater than the
  1262. // difference between smallest and largest cases.
  1263. SDValue SwitchOp = getValue(JTH.SValue);
  1264. MVT VT = SwitchOp.getValueType();
  1265. SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
  1266. DAG.getConstant(JTH.First, VT));
  1267. // The SDNode we just created, which holds the value being switched on minus
  1268. // the the smallest case value, needs to be copied to a virtual register so it
  1269. // can be used as an index into the jump table in a subsequent basic block.
  1270. // This value may be smaller or larger than the target's pointer type, and
  1271. // therefore require extension or truncating.
  1272. if (VT.bitsGT(TLI.getPointerTy()))
  1273. SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  1274. TLI.getPointerTy(), SUB);
  1275. else
  1276. SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  1277. TLI.getPointerTy(), SUB);
  1278. unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
  1279. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
  1280. JumpTableReg, SwitchOp);
  1281. JT.Reg = JumpTableReg;
  1282. // Emit the range check for the jump table, and branch to the default block
  1283. // for the switch statement if the value being switched on exceeds the largest
  1284. // case in the switch.
  1285. SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
  1286. TLI.getSetCCResultType(SUB.getValueType()), SUB,
  1287. DAG.getConstant(JTH.Last-JTH.First,VT),
  1288. ISD::SETUGT);
  1289. // Set NextBlock to be the MBB immediately after the current one, if any.
  1290. // This is used to avoid emitting unnecessary branches to the next block.
  1291. MachineBasicBlock *NextBlock = 0;
  1292. MachineFunction::iterator BBI = CurMBB;
  1293. if (++BBI != CurMBB->getParent()->end())
  1294. NextBlock = BBI;
  1295. SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
  1296. MVT::Other, CopyTo, CMP,
  1297. DAG.getBasicBlock(JT.Default));
  1298. if (JT.MBB == NextBlock)
  1299. DAG.setRoot(BrCond);
  1300. else
  1301. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
  1302. DAG.getBasicBlock(JT.MBB)));
  1303. }
  1304. /// visitBitTestHeader - This function emits necessary code to produce value
  1305. /// suitable for "bit tests"
  1306. void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
  1307. // Subtract the minimum value
  1308. SDValue SwitchOp = getValue(B.SValue);
  1309. MVT VT = SwitchOp.getValueType();
  1310. SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
  1311. DAG.getConstant(B.First, VT));
  1312. // Check range
  1313. SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
  1314. TLI.getSetCCResultType(SUB.getValueType()),
  1315. SUB, DAG.getConstant(B.Range, VT),
  1316. ISD::SETUGT);
  1317. SDValue ShiftOp;
  1318. if (VT.bitsGT(TLI.getPointerTy()))
  1319. ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  1320. TLI.getPointerTy(), SUB);
  1321. else
  1322. ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  1323. TLI.getPointerTy(), SUB);
  1324. B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
  1325. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
  1326. B.Reg, ShiftOp);
  1327. // Set NextBlock to be the MBB immediately after the current one, if any.
  1328. // This is used to avoid emitting unnecessary branches to the next block.
  1329. MachineBasicBlock *NextBlock = 0;
  1330. MachineFunction::iterator BBI = CurMBB;
  1331. if (++BBI != CurMBB->getParent()->end())
  1332. NextBlock = BBI;
  1333. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1334. CurMBB->addSuccessor(B.Default);
  1335. CurMBB->addSuccessor(MBB);
  1336. SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
  1337. MVT::Other, CopyTo, RangeCmp,
  1338. DAG.getBasicBlock(B.Default));
  1339. if (MBB == NextBlock)
  1340. DAG.setRoot(BrRange);
  1341. else
  1342. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
  1343. DAG.getBasicBlock(MBB)));
  1344. }
  1345. /// visitBitTestCase - this function produces one "bit test"
  1346. void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
  1347. unsigned Reg,
  1348. BitTestCase &B) {
  1349. // Make desired shift
  1350. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
  1351. TLI.getPointerTy());
  1352. SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
  1353. TLI.getPointerTy(),
  1354. DAG.getConstant(1, TLI.getPointerTy()),
  1355. ShiftOp);
  1356. // Emit bit tests and jumps
  1357. SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
  1358. TLI.getPointerTy(), SwitchVal,
  1359. DAG.getConstant(B.Mask, TLI.getPointerTy()));
  1360. SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
  1361. TLI.getSetCCResultType(AndOp.getValueType()),
  1362. AndOp, DAG.getConstant(0, TLI.getPointerTy()),
  1363. ISD::SETNE);
  1364. CurMBB->addSuccessor(B.TargetBB);
  1365. CurMBB->addSuccessor(NextMBB);
  1366. SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
  1367. MVT::Other, getControlRoot(),
  1368. AndCmp, DAG.getBasicBlock(B.TargetBB));
  1369. // Set NextBlock to be the MBB immediately after the current one, if any.
  1370. // This is used to avoid emitting unnecessary branches to the next block.
  1371. MachineBasicBlock *NextBlock = 0;
  1372. MachineFunction::iterator BBI = CurMBB;
  1373. if (++BBI != CurMBB->getParent()->end())
  1374. NextBlock = BBI;
  1375. if (NextMBB == NextBlock)
  1376. DAG.setRoot(BrAnd);
  1377. else
  1378. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
  1379. DAG.getBasicBlock(NextMBB)));
  1380. }
  1381. void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
  1382. // Retrieve successors.
  1383. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  1384. MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
  1385. const Value *Callee(I.getCalledValue());
  1386. if (isa<InlineAsm>(Callee))
  1387. visitInlineAsm(&I);
  1388. else
  1389. LowerCallTo(&I, getValue(Callee), false, LandingPad);
  1390. // If the value of the invoke is used outside of its defining block, make it
  1391. // available as a virtual register.
  1392. CopyToExportRegsIfNeeded(&I);
  1393. // Update successor info
  1394. CurMBB->addSuccessor(Return);
  1395. CurMBB->addSuccessor(LandingPad);
  1396. // Drop into normal successor.
  1397. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
  1398. MVT::Other, getControlRoot(),
  1399. DAG.getBasicBlock(Return)));
  1400. }
  1401. void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
  1402. }
  1403. /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
  1404. /// small case ranges).
  1405. bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
  1406. CaseRecVector& WorkList,
  1407. Value* SV,
  1408. MachineBasicBlock* Default) {
  1409. Case& BackCase = *(CR.Range.second-1);
  1410. // Size is the number of Cases represented by this range.
  1411. size_t Size = CR.Range.second - CR.Range.first;
  1412. if (Size > 3)
  1413. return false;
  1414. // Get the MachineFunction which holds the current MBB. This is used when
  1415. // inserting any additional MBBs necessary to represent the switch.
  1416. MachineFunction *CurMF = CurMBB->getParent();
  1417. // Figure out which block is immediately after the current one.
  1418. MachineBasicBlock *NextBlock = 0;
  1419. MachineFunction::iterator BBI = CR.CaseBB;
  1420. if (++BBI != CurMBB->getParent()->end())
  1421. NextBlock = BBI;
  1422. // TODO: If any two of the cases has the same destination, and if one value
  1423. // is the same as the other, but has one bit unset that the other has set,
  1424. // use bit manipulation to do two compares at once. For example:
  1425. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  1426. // Rearrange the case blocks so that the last one falls through if possible.
  1427. if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
  1428. // The last case block won't fall through into 'NextBlock' if we emit the
  1429. // branches in this order. See if rearranging a case value would help.
  1430. for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
  1431. if (I->BB == NextBlock) {
  1432. std::swap(*I, BackCase);
  1433. break;
  1434. }
  1435. }
  1436. }
  1437. // Create a CaseBlock record representing a conditional branch to
  1438. // the Case's target mbb if the value being switched on SV is equal
  1439. // to C.
  1440. MachineBasicBlock *CurBlock = CR.CaseBB;
  1441. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  1442. MachineBasicBlock *FallThrough;
  1443. if (I != E-1) {
  1444. FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
  1445. CurMF->insert(BBI, FallThrough);
  1446. // Put SV in a virtual register to make it available from the new blocks.
  1447. ExportFromCurrentBlock(SV);
  1448. } else {
  1449. // If the last case doesn't match, go to the default block.
  1450. FallThrough = Default;
  1451. }
  1452. Value *RHS, *LHS, *MHS;
  1453. ISD::CondCode CC;
  1454. if (I->High == I->Low) {
  1455. // This is just small small case range :) containing exactly 1 case
  1456. CC = ISD::SETEQ;
  1457. LHS = SV; RHS = I->High; MHS = NULL;
  1458. } else {
  1459. CC = ISD::SETLE;
  1460. LHS = I->Low; MHS = SV; RHS = I->High;
  1461. }
  1462. CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
  1463. // If emitting the first comparison, just call visitSwitchCase to emit the
  1464. // code into the current block. Otherwise, push the CaseBlock onto the
  1465. // vector to be later processed by SDISel, and insert the node's MBB
  1466. // before the next MBB.
  1467. if (CurBlock == CurMBB)
  1468. visitSwitchCase(CB);
  1469. else
  1470. SwitchCases.push_back(CB);
  1471. CurBlock = FallThrough;
  1472. }
  1473. return true;
  1474. }
  1475. static inline bool areJTsAllowed(const TargetLowering &TLI) {
  1476. return !DisableJumpTables &&
  1477. (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  1478. TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
  1479. }
  1480. static APInt ComputeRange(const APInt &First, const APInt &Last) {
  1481. APInt LastExt(Last), FirstExt(First);
  1482. uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
  1483. LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
  1484. return (LastExt - FirstExt + 1ULL);
  1485. }
  1486. /// handleJTSwitchCase - Emit jumptable for current switch case range
  1487. bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
  1488. CaseRecVector& WorkList,
  1489. Value* SV,
  1490. MachineBasicBlock* Default) {
  1491. Case& FrontCase = *CR.Range.first;
  1492. Case& BackCase = *(CR.Range.second-1);
  1493. const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
  1494. const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
  1495. size_t TSize = 0;
  1496. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  1497. I!=E; ++I)
  1498. TSize += I->size();
  1499. if (!areJTsAllowed(TLI) || TSize <= 3)
  1500. return false;
  1501. APInt Range = ComputeRange(First, Last);
  1502. double Density = (double)TSize / Range.roundToDouble();
  1503. if (Density < 0.4)
  1504. return false;
  1505. DEBUG(errs() << "Lowering jump table\n"
  1506. << "First entry: " << First << ". Last entry: " << Last << '\n'
  1507. << "Range: " << Range
  1508. << "Size: " << TSize << ". Density: " << Density << "\n\n");
  1509. // Get the MachineFunction which holds the current MBB. This is used when
  1510. // inserting any additional MBBs necessary to represent the switch.
  1511. MachineFunction *CurMF = CurMBB->getParent();
  1512. // Figure out which block is immediately after the current one.
  1513. MachineBasicBlock *NextBlock = 0;
  1514. MachineFunction::iterator BBI = CR.CaseBB;
  1515. if (++BBI != CurMBB->getParent()->end())
  1516. NextBlock = BBI;
  1517. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1518. // Create a new basic block to hold the code for loading the address
  1519. // of the jump table, and jumping to it. Update successor information;
  1520. // we will either branch to the default case for the switch, or the jump
  1521. // table.
  1522. MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1523. CurMF->insert(BBI, JumpTableBB);
  1524. CR.CaseBB->addSuccessor(Default);
  1525. CR.CaseBB->addSuccessor(JumpTableBB);
  1526. // Build a vector of destination BBs, corresponding to each target
  1527. // of the jump table. If the value of the jump table slot corresponds to
  1528. // a case statement, push the case's BB onto the vector, otherwise, push
  1529. // the default BB.
  1530. std::vector<MachineBasicBlock*> DestBBs;
  1531. APInt TEI = First;
  1532. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
  1533. const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
  1534. const APInt& High = cast<ConstantInt>(I->High)->getValue();
  1535. if (Low.sle(TEI) && TEI.sle(High)) {
  1536. DestBBs.push_back(I->BB);
  1537. if (TEI==High)
  1538. ++I;
  1539. } else {
  1540. DestBBs.push_back(Default);
  1541. }
  1542. }
  1543. // Update successor info. Add one edge to each unique successor.
  1544. BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
  1545. for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
  1546. E = DestBBs.end(); I != E; ++I) {
  1547. if (!SuccsHandled[(*I)->getNumber()]) {
  1548. SuccsHandled[(*I)->getNumber()] = true;
  1549. JumpTableBB->addSuccessor(*I);
  1550. }
  1551. }
  1552. // Create a jump table index for this jump table, or return an existing
  1553. // one.
  1554. unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
  1555. // Set the jump table information so that we can codegen it as a second
  1556. // MachineBasicBlock
  1557. JumpTable JT(-1U, JTI, JumpTableBB, Default);
  1558. JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
  1559. if (CR.CaseBB == CurMBB)
  1560. visitJumpTableHeader(JT, JTH);
  1561. JTCases.push_back(JumpTableBlock(JTH, JT));
  1562. return true;
  1563. }
  1564. /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
  1565. /// 2 subtrees.
  1566. bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
  1567. CaseRecVector& WorkList,
  1568. Value* SV,
  1569. MachineBasicBlock* Default) {
  1570. // Get the MachineFunction which holds the current MBB. This is used when
  1571. // inserting any additional MBBs necessary to represent the switch.
  1572. MachineFunction *CurMF = CurMBB->getParent();
  1573. // Figure out which block is immediately after the current one.
  1574. MachineBasicBlock *NextBlock = 0;
  1575. MachineFunction::iterator BBI = CR.CaseBB;
  1576. if (++BBI != CurMBB->getParent()->end())
  1577. NextBlock = BBI;
  1578. Case& FrontCase = *CR.Range.first;
  1579. Case& BackCase = *(CR.Range.second-1);
  1580. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1581. // Size is the number of Cases represented by this range.
  1582. unsigned Size = CR.Range.second - CR.Range.first;
  1583. const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
  1584. const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
  1585. double FMetric = 0;
  1586. CaseItr Pivot = CR.Range.first + Size/2;
  1587. // Select optimal pivot, maximizing sum density of LHS and RHS. This will
  1588. // (heuristically) allow us to emit JumpTable's later.
  1589. size_t TSize = 0;
  1590. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  1591. I!=E; ++I)
  1592. TSize += I->size();
  1593. size_t LSize = FrontCase.size();
  1594. size_t RSize = TSize-LSize;
  1595. DEBUG(errs() << "Selecting best pivot: \n"
  1596. << "First: " << First << ", Last: " << Last <<'\n'
  1597. << "LSize: " << LSize << ", RSize: " << RSize << '\n');
  1598. for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
  1599. J!=E; ++I, ++J) {
  1600. const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
  1601. const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
  1602. APInt Range = ComputeRange(LEnd, RBegin);
  1603. assert((Range - 2ULL).isNonNegative() &&
  1604. "Invalid case distance");
  1605. double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
  1606. double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
  1607. double Metric = Range.logBase2()*(LDensity+RDensity);
  1608. // Should always split in some non-trivial place
  1609. DEBUG(errs() <<"=>Step\n"
  1610. << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
  1611. << "LDensity: " << LDensity
  1612. << ", RDensity: " << RDensity << '\n'
  1613. << "Metric: " << Metric << '\n');
  1614. if (FMetric < Metric) {
  1615. Pivot = J;
  1616. FMetric = Metric;
  1617. DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
  1618. }
  1619. LSize += J->size();
  1620. RSize -= J->size();
  1621. }
  1622. if (areJTsAllowed(TLI)) {
  1623. // If our case is dense we *really* should handle it earlier!
  1624. assert((FMetric > 0) && "Should handle dense range earlier!");
  1625. } else {
  1626. Pivot = CR.Range.first + Size/2;
  1627. }
  1628. CaseRange LHSR(CR.Range.first, Pivot);
  1629. CaseRange RHSR(Pivot, CR.Range.second);
  1630. Constant *C = Pivot->Low;
  1631. MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
  1632. // We know that we branch to the LHS if the Value being switched on is
  1633. // less than the Pivot value, C. We use this to optimize our binary
  1634. // tree a bit, by recognizing that if SV is greater than or equal to the
  1635. // LHS's Case Value, and that Case Value is exactly one less than the
  1636. // Pivot's Value, then we can branch directly to the LHS's Target,
  1637. // rather than creating a leaf node for it.
  1638. if ((LHSR.second - LHSR.first) == 1 &&
  1639. LHSR.first->High == CR.GE &&
  1640. cast<ConstantInt>(C)->getValue() ==
  1641. (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
  1642. TrueBB = LHSR.first->BB;
  1643. } else {
  1644. TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1645. CurMF->insert(BBI, TrueBB);
  1646. WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
  1647. // Put SV in a virtual register to make it available from the new blocks.
  1648. ExportFromCurrentBlock(SV);
  1649. }
  1650. // Similar to the optimization above, if the Value being switched on is
  1651. // known to be less than the Constant CR.LT, and the current Case Value
  1652. // is CR.LT - 1, then we can branch directly to the target block for
  1653. // the current Case Value, rather than emitting a RHS leaf node for it.
  1654. if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
  1655. cast<ConstantInt>(RHSR.first->Low)->getValue() ==
  1656. (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
  1657. FalseBB = RHSR.first->BB;
  1658. } else {
  1659. FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1660. CurMF->insert(BBI, FalseBB);
  1661. WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
  1662. // Put SV in a virtual register to make it available from the new blocks.
  1663. ExportFromCurrentBlock(SV);
  1664. }
  1665. // Create a CaseBlock record representing a conditional branch to
  1666. // the LHS node if the value being switched on SV is less than C.
  1667. // Otherwise, branch to LHS.
  1668. CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
  1669. if (CR.CaseBB == CurMBB)
  1670. visitSwitchCase(CB);
  1671. else
  1672. SwitchCases.push_back(CB);
  1673. return true;
  1674. }
  1675. /// handleBitTestsSwitchCase - if current case range has few destination and
  1676. /// range span less, than machine word bitwidth, encode case range into series
  1677. /// of masks and emit bit tests with these masks.
  1678. bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
  1679. CaseRecVector& WorkList,
  1680. Value* SV,
  1681. MachineBasicBlock* Default){
  1682. unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
  1683. Case& FrontCase = *CR.Range.first;
  1684. Case& BackCase = *(CR.Range.second-1);
  1685. // Get the MachineFunction which holds the current MBB. This is used when
  1686. // inserting any additional MBBs necessary to represent the switch.
  1687. MachineFunction *CurMF = CurMBB->getParent();
  1688. size_t numCmps = 0;
  1689. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  1690. I!=E; ++I) {
  1691. // Single case counts one, case range - two.
  1692. numCmps += (I->Low == I->High ? 1 : 2);
  1693. }
  1694. // Count unique destinations
  1695. SmallSet<MachineBasicBlock*, 4> Dests;
  1696. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  1697. Dests.insert(I->BB);
  1698. if (Dests.size() > 3)
  1699. // Don't bother the code below, if there are too much unique destinations
  1700. return false;
  1701. }
  1702. DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
  1703. << "Total number of comparisons: " << numCmps << '\n');
  1704. // Compute span of values.
  1705. const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
  1706. const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
  1707. APInt cmpRange = maxValue - minValue;
  1708. DEBUG(errs() << "Compare range: " << cmpRange << '\n'
  1709. << "Low bound: " << minValue << '\n'
  1710. << "High bound: " << maxValue << '\n');
  1711. if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
  1712. (!(Dests.size() == 1 && numCmps >= 3) &&
  1713. !(Dests.size() == 2 && numCmps >= 5) &&
  1714. !(Dests.size() >= 3 && numCmps >= 6)))
  1715. return false;
  1716. DEBUG(errs() << "Emitting bit tests\n");
  1717. APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
  1718. // Optimize the case where all the case values fit in a
  1719. // word without having to subtract minValue. In this case,
  1720. // we can optimize away the subtraction.
  1721. if (minValue.isNonNegative() &&
  1722. maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
  1723. cmpRange = maxValue;
  1724. } else {
  1725. lowBound = minValue;
  1726. }
  1727. CaseBitsVector CasesBits;
  1728. unsigned i, count = 0;
  1729. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  1730. MachineBasicBlock* Dest = I->BB;
  1731. for (i = 0; i < count; ++i)
  1732. if (Dest == CasesBits[i].BB)
  1733. break;
  1734. if (i == count) {
  1735. assert((count < 3) && "Too much destinations to test!");
  1736. CasesBits.push_back(CaseBits(0, Dest, 0));
  1737. count++;
  1738. }
  1739. const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
  1740. const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
  1741. uint64_t lo = (lowValue - lowBound).getZExtValue();
  1742. uint64_t hi = (highValue - lowBound).getZExtValue();
  1743. for (uint64_t j = lo; j <= hi; j++) {
  1744. CasesBits[i].Mask |= 1ULL << j;
  1745. CasesBits[i].Bits++;
  1746. }
  1747. }
  1748. std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
  1749. BitTestInfo BTC;
  1750. // Figure out which block is immediately after the current one.
  1751. MachineFunction::iterator BBI = CR.CaseBB;
  1752. ++BBI;
  1753. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1754. DEBUG(errs() << "Cases:\n");
  1755. for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
  1756. DEBUG(errs() << "Mask: " << CasesBits[i].Mask
  1757. << ", Bits: " << CasesBits[i].Bits
  1758. << ", BB: " << CasesBits[i].BB << '\n');
  1759. MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1760. CurMF->insert(BBI, CaseBB);
  1761. BTC.push_back(BitTestCase(CasesBits[i].Mask,
  1762. CaseBB,
  1763. CasesBits[i].BB));
  1764. // Put SV in a virtual register to make it available from the new blocks.
  1765. ExportFromCurrentBlock(SV);
  1766. }
  1767. BitTestBlock BTB(lowBound, cmpRange, SV,
  1768. -1U, (CR.CaseBB == CurMBB),
  1769. CR.CaseBB, Default, BTC);
  1770. if (CR.CaseBB == CurMBB)
  1771. visitBitTestHeader(BTB);
  1772. BitTestCases.push_back(BTB);
  1773. return true;
  1774. }
  1775. /// Clusterify - Transform simple list of Cases into list of CaseRange's
  1776. size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
  1777. const SwitchInst& SI) {
  1778. size_t numCmps = 0;
  1779. // Start with "simple" cases
  1780. for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
  1781. MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
  1782. Cases.push_back(Case(SI.getSuccessorValue(i),
  1783. SI.getSuccessorValue(i),
  1784. SMBB));
  1785. }
  1786. std::sort(Cases.begin(), Cases.end(), CaseCmp());
  1787. // Merge case into clusters
  1788. if (Cases.size() >= 2)
  1789. // Must recompute end() each iteration because it may be
  1790. // invalidated by erase if we hold on to it
  1791. for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
  1792. const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
  1793. const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
  1794. MachineBasicBlock* nextBB = J->BB;
  1795. MachineBasicBlock* currentBB = I->BB;
  1796. // If the two neighboring cases go to the same destination, merge them
  1797. // into a single case.
  1798. if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
  1799. I->High = J->High;
  1800. J = Cases.erase(J);
  1801. } else {
  1802. I = J++;
  1803. }
  1804. }
  1805. for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
  1806. if (I->Low != I->High)
  1807. // A range counts double, since it requires two compares.
  1808. ++numCmps;
  1809. }
  1810. return numCmps;
  1811. }
  1812. void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
  1813. // Figure out which block is immediately after the current one.
  1814. MachineBasicBlock *NextBlock = 0;
  1815. MachineFunction::iterator BBI = CurMBB;
  1816. MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
  1817. // If there is only the default destination, branch to it if it is not the
  1818. // next basic block. Otherwise, just fall through.
  1819. if (SI.getNumOperands() == 2) {
  1820. // Update machine-CFG edges.
  1821. // If this is not a fall-through branch, emit the branch.
  1822. CurMBB->addSuccessor(Default);
  1823. if (Default != NextBlock)
  1824. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
  1825. MVT::Other, getControlRoot(),
  1826. DAG.getBasicBlock(Default)));
  1827. return;
  1828. }
  1829. // If there are any non-default case statements, create a vector of Cases
  1830. // representing each one, and sort the vector so that we can efficiently
  1831. // create a binary search tree from them.
  1832. CaseVector Cases;
  1833. size_t numCmps = Clusterify(Cases, SI);
  1834. DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
  1835. << ". Total compares: " << numCmps << '\n');
  1836. numCmps = 0;
  1837. // Get the Value to be switched on and default basic blocks, which will be
  1838. // inserted into CaseBlock records, representing basic blocks in the binary
  1839. // search tree.
  1840. Value *SV = SI.getOperand(0);
  1841. // Push the initial CaseRec onto the worklist
  1842. CaseRecVector WorkList;
  1843. WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
  1844. while (!WorkList.empty()) {
  1845. // Grab a record representing a case range to process off the worklist
  1846. CaseRec CR = WorkList.back();
  1847. WorkList.pop_back();
  1848. if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
  1849. continue;
  1850. // If the range has few cases (two or less) emit a series of specific
  1851. // tests.
  1852. if (handleSmallSwitchRange(CR, WorkList, SV, Default))
  1853. continue;
  1854. // If the switch has more than 5 blocks, and at least 40% dense, and the
  1855. // target supports indirect branches, then emit a jump table rather than
  1856. // lowering the switch to a binary tree of conditional branches.
  1857. if (handleJTSwitchCase(CR, WorkList, SV, Default))
  1858. continue;
  1859. // Emit binary tree. We need to pick a pivot, and push left and right ranges
  1860. // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
  1861. handleBTSplitSwitchCase(CR, WorkList, SV, Default);
  1862. }
  1863. }
  1864. void SelectionDAGLowering::visitSub(User &I) {
  1865. // -0.0 - X --> fneg
  1866. const Type *Ty = I.getType();
  1867. if (isa<VectorType>(Ty)) {
  1868. if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
  1869. const VectorType *DestTy = cast<VectorType>(I.getType());
  1870. const Type *ElTy = DestTy->getElementType();
  1871. if (ElTy->isFloatingPoint()) {
  1872. unsigned VL = DestTy->getNumElements();
  1873. std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
  1874. Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
  1875. if (CV == CNZ) {
  1876. SDValue Op2 = getValue(I.getOperand(1));
  1877. setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
  1878. Op2.getValueType(), Op2));
  1879. return;
  1880. }
  1881. }
  1882. }
  1883. }
  1884. if (Ty->isFloatingPoint()) {
  1885. if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
  1886. if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
  1887. SDValue Op2 = getValue(I.getOperand(1));
  1888. setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
  1889. Op2.getValueType(), Op2));
  1890. return;
  1891. }
  1892. }
  1893. visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
  1894. }
  1895. void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
  1896. SDValue Op1 = getValue(I.getOperand(0));
  1897. SDValue Op2 = getValue(I.getOperand(1));
  1898. setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
  1899. Op1.getValueType(), Op1, Op2));
  1900. }
  1901. void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
  1902. SDValue Op1 = getValue(I.getOperand(0));
  1903. SDValue Op2 = getValue(I.getOperand(1));
  1904. if (!isa<VectorType>(I.getType()) &&
  1905. Op2.getValueType() != TLI.getShiftAmountTy()) {
  1906. // If the operand is smaller than the shift count type, promote it.
  1907. if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
  1908. Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
  1909. TLI.getShiftAmountTy(), Op2);
  1910. // If the operand is larger than the shift count type but the shift
  1911. // count type has enough bits to represent any shift value, truncate
  1912. // it now. This is a common case and it exposes the truncate to
  1913. // optimization early.
  1914. else if (TLI.getShiftAmountTy().getSizeInBits() >=
  1915. Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
  1916. Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  1917. TLI.getShiftAmountTy(), Op2);
  1918. // Otherwise we'll need to temporarily settle for some other
  1919. // convenient type; type legalization will make adjustments as
  1920. // needed.
  1921. else if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
  1922. Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  1923. TLI.getPointerTy(), Op2);
  1924. else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
  1925. Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
  1926. TLI.getPointerTy(), Op2);
  1927. }
  1928. setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
  1929. Op1.getValueType(), Op1, Op2));
  1930. }
  1931. void SelectionDAGLowering::visitICmp(User &I) {
  1932. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  1933. if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  1934. predicate = IC->getPredicate();
  1935. else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  1936. predicate = ICmpInst::Predicate(IC->getPredicate());
  1937. SDValue Op1 = getValue(I.getOperand(0));
  1938. SDValue Op2 = getValue(I.getOperand(1));
  1939. ISD::CondCode Opcode = getICmpCondCode(predicate);
  1940. setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
  1941. }
  1942. void SelectionDAGLowering::visitFCmp(User &I) {
  1943. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  1944. if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  1945. predicate = FC->getPredicate();
  1946. else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  1947. predicate = FCmpInst::Predicate(FC->getPredicate());
  1948. SDValue Op1 = getValue(I.getOperand(0));
  1949. SDValue Op2 = getValue(I.getOperand(1));
  1950. ISD::CondCode Condition = getFCmpCondCode(predicate);
  1951. setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
  1952. }
  1953. void SelectionDAGLowering::visitVICmp(User &I) {
  1954. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  1955. if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
  1956. predicate = IC->getPredicate();
  1957. else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  1958. predicate = ICmpInst::Predicate(IC->getPredicate());
  1959. SDValue Op1 = getValue(I.getOperand(0));
  1960. SDValue Op2 = getValue(I.getOperand(1));
  1961. ISD::CondCode Opcode = getICmpCondCode(predicate);
  1962. setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
  1963. Op1, Op2, Opcode));
  1964. }
  1965. void SelectionDAGLowering::visitVFCmp(User &I) {
  1966. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  1967. if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
  1968. predicate = FC->getPredicate();
  1969. else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  1970. predicate = FCmpInst::Predicate(FC->getPredicate());
  1971. SDValue Op1 = getValue(I.getOperand(0));
  1972. SDValue Op2 = getValue(I.getOperand(1));
  1973. ISD::CondCode Condition = getFCmpCondCode(predicate);
  1974. MVT DestVT = TLI.getValueType(I.getType());
  1975. setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
  1976. }
  1977. void SelectionDAGLowering::visitSelect(User &I) {
  1978. SmallVector<MVT, 4> ValueVTs;
  1979. ComputeValueVTs(TLI, I.getType(), ValueVTs);
  1980. unsigned NumValues = ValueVTs.size();
  1981. if (NumValues != 0) {
  1982. SmallVector<SDValue, 4> Values(NumValues);
  1983. SDValue Cond = getValue(I.getOperand(0));
  1984. SDValue TrueVal = getValue(I.getOperand(1));
  1985. SDValue FalseVal = getValue(I.getOperand(2));
  1986. for (unsigned i = 0; i != NumValues; ++i)
  1987. Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
  1988. TrueVal.getValueType(), Cond,
  1989. SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
  1990. SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
  1991. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  1992. DAG.getVTList(&ValueVTs[0], NumValues),
  1993. &Values[0], NumValues));
  1994. }
  1995. }
  1996. void SelectionDAGLowering::visitTrunc(User &I) {
  1997. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  1998. SDValue N = getValue(I.getOperand(0));
  1999. MVT DestVT = TLI.getValueType(I.getType());
  2000. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
  2001. }
  2002. void SelectionDAGLowering::visitZExt(User &I) {
  2003. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2004. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2005. SDValue N = getValue(I.getOperand(0));
  2006. MVT DestVT = TLI.getValueType(I.getType());
  2007. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
  2008. }
  2009. void SelectionDAGLowering::visitSExt(User &I) {
  2010. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2011. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2012. SDValue N = getValue(I.getOperand(0));
  2013. MVT DestVT = TLI.getValueType(I.getType());
  2014. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
  2015. }
  2016. void SelectionDAGLowering::visitFPTrunc(User &I) {
  2017. // FPTrunc is never a no-op cast, no need to check
  2018. SDValue N = getValue(I.getOperand(0));
  2019. MVT DestVT = TLI.getValueType(I.getType());
  2020. setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
  2021. DestVT, N, DAG.getIntPtrConstant(0)));
  2022. }
  2023. void SelectionDAGLowering::visitFPExt(User &I){
  2024. // FPTrunc is never a no-op cast, no need to check
  2025. SDValue N = getValue(I.getOperand(0));
  2026. MVT DestVT = TLI.getValueType(I.getType());
  2027. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
  2028. }
  2029. void SelectionDAGLowering::visitFPToUI(User &I) {
  2030. // FPToUI is never a no-op cast, no need to check
  2031. SDValue N = getValue(I.getOperand(0));
  2032. MVT DestVT = TLI.getValueType(I.getType());
  2033. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
  2034. }
  2035. void SelectionDAGLowering::visitFPToSI(User &I) {
  2036. // FPToSI is never a no-op cast, no need to check
  2037. SDValue N = getValue(I.getOperand(0));
  2038. MVT DestVT = TLI.getValueType(I.getType());
  2039. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
  2040. }
  2041. void SelectionDAGLowering::visitUIToFP(User &I) {
  2042. // UIToFP is never a no-op cast, no need to check
  2043. SDValue N = getValue(I.getOperand(0));
  2044. MVT DestVT = TLI.getValueType(I.getType());
  2045. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
  2046. }
  2047. void SelectionDAGLowering::visitSIToFP(User &I){
  2048. // SIToFP is never a no-op cast, no need to check
  2049. SDValue N = getValue(I.getOperand(0));
  2050. MVT DestVT = TLI.getValueType(I.getType());
  2051. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
  2052. }
  2053. void SelectionDAGLowering::visitPtrToInt(User &I) {
  2054. // What to do depends on the size of the integer and the size of the pointer.
  2055. // We can either truncate, zero extend, or no-op, accordingly.
  2056. SDValue N = getValue(I.getOperand(0));
  2057. MVT SrcVT = N.getValueType();
  2058. MVT DestVT = TLI.getValueType(I.getType());
  2059. SDValue Result;
  2060. if (DestVT.bitsLT(SrcVT))
  2061. Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
  2062. else
  2063. // Note: ZERO_EXTEND can handle cases where the sizes are equal too
  2064. Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
  2065. setValue(&I, Result);
  2066. }
  2067. void SelectionDAGLowering::visitIntToPtr(User &I) {
  2068. // What to do depends on the size of the integer and the size of the pointer.
  2069. // We can either truncate, zero extend, or no-op, accordingly.
  2070. SDValue N = getValue(I.getOperand(0));
  2071. MVT SrcVT = N.getValueType();
  2072. MVT DestVT = TLI.getValueType(I.getType());
  2073. if (DestVT.bitsLT(SrcVT))
  2074. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
  2075. else
  2076. // Note: ZERO_EXTEND can handle cases where the sizes are equal too
  2077. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  2078. DestVT, N));
  2079. }
  2080. void SelectionDAGLowering::visitBitCast(User &I) {
  2081. SDValue N = getValue(I.getOperand(0));
  2082. MVT DestVT = TLI.getValueType(I.getType());
  2083. // BitCast assures us that source and destination are the same size so this
  2084. // is either a BIT_CONVERT or a no-op.
  2085. if (DestVT != N.getValueType())
  2086. setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
  2087. DestVT, N)); // convert types
  2088. else
  2089. setValue(&I, N); // noop cast.
  2090. }
  2091. void SelectionDAGLowering::visitInsertElement(User &I) {
  2092. SDValue InVec = getValue(I.getOperand(0));
  2093. SDValue InVal = getValue(I.getOperand(1));
  2094. SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  2095. TLI.getPointerTy(),
  2096. getValue(I.getOperand(2)));
  2097. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
  2098. TLI.getValueType(I.getType()),
  2099. InVec, InVal, InIdx));
  2100. }
  2101. void SelectionDAGLowering::visitExtractElement(User &I) {
  2102. SDValue InVec = getValue(I.getOperand(0));
  2103. SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  2104. TLI.getPointerTy(),
  2105. getValue(I.getOperand(1)));
  2106. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
  2107. TLI.getValueType(I.getType()), InVec, InIdx));
  2108. }
  2109. // Utility for visitShuffleVector - Returns true if the mask is mask starting
  2110. // from SIndx and increasing to the element length (undefs are allowed).
  2111. static bool SequentialMask(SmallVectorImpl<int> &Mask, int SIndx) {
  2112. int MaskNumElts = Mask.size();
  2113. for (int i = 0; i != MaskNumElts; ++i)
  2114. if ((Mask[i] >= 0) && (Mask[i] != i + SIndx))
  2115. return false;
  2116. return true;
  2117. }
  2118. void SelectionDAGLowering::visitShuffleVector(User &I) {
  2119. SmallVector<int, 8> Mask;
  2120. SDValue Src1 = getValue(I.getOperand(0));
  2121. SDValue Src2 = getValue(I.getOperand(1));
  2122. // Convert the ConstantVector mask operand into an array of ints, with -1
  2123. // representing undef values.
  2124. SmallVector<Constant*, 8> MaskElts;
  2125. cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
  2126. int MaskNumElts = MaskElts.size();
  2127. for (int i = 0; i != MaskNumElts; ++i) {
  2128. if (isa<UndefValue>(MaskElts[i]))
  2129. Mask.push_back(-1);
  2130. else
  2131. Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
  2132. }
  2133. MVT VT = TLI.getValueType(I.getType());
  2134. MVT SrcVT = Src1.getValueType();
  2135. int SrcNumElts = SrcVT.getVectorNumElements();
  2136. if (SrcNumElts == MaskNumElts) {
  2137. setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
  2138. &Mask[0]));
  2139. return;
  2140. }
  2141. // Normalize the shuffle vector since mask and vector length don't match.
  2142. if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
  2143. // Mask is longer than the source vectors and is a multiple of the source
  2144. // vectors. We can use concatenate vector to make the mask and vectors
  2145. // lengths match.
  2146. if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
  2147. // The shuffle is concatenating two vectors together.
  2148. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
  2149. VT, Src1, Src2));
  2150. return;
  2151. }
  2152. // Pad both vectors with undefs to make them the same length as the mask.
  2153. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2154. bool Src1U = Src1.getOpcode() == ISD::UNDEF;
  2155. bool Src2U = Src2.getOpcode() == ISD::UNDEF;
  2156. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2157. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2158. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2159. MOps1[0] = Src1;
  2160. MOps2[0] = Src2;
  2161. Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2162. getCurDebugLoc(), VT,
  2163. &MOps1[0], NumConcat);
  2164. Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2165. getCurDebugLoc(), VT,
  2166. &MOps2[0], NumConcat);
  2167. // Readjust mask for new input vector length.
  2168. SmallVector<int, 8> MappedOps;
  2169. for (int i = 0; i != MaskNumElts; ++i) {
  2170. int Idx = Mask[i];
  2171. if (Idx < SrcNumElts)
  2172. MappedOps.push_back(Idx);
  2173. else
  2174. MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
  2175. }
  2176. setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
  2177. &MappedOps[0]));
  2178. return;
  2179. }
  2180. if (SrcNumElts > MaskNumElts) {
  2181. // Resulting vector is shorter than the incoming vector.
  2182. if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
  2183. // Shuffle extracts 1st vector.
  2184. setValue(&I, Src1);
  2185. return;
  2186. }
  2187. if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
  2188. // Shuffle extracts 2nd vector.
  2189. setValue(&I, Src2);
  2190. return;
  2191. }
  2192. // Analyze the access pattern of the vector to see if we can extract
  2193. // two subvectors and do the shuffle. The analysis is done by calculating
  2194. // the range of elements the mask access on both vectors.
  2195. int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
  2196. int MaxRange[2] = {-1, -1};
  2197. for (int i = 0; i != MaskNumElts; ++i) {
  2198. int Idx = Mask[i];
  2199. int Input = 0;
  2200. if (Idx < 0)
  2201. continue;
  2202. if (Idx >= SrcNumElts) {
  2203. Input = 1;
  2204. Idx -= SrcNumElts;
  2205. }
  2206. if (Idx > MaxRange[Input])
  2207. MaxRange[Input] = Idx;
  2208. if (Idx < MinRange[Input])
  2209. MinRange[Input] = Idx;
  2210. }
  2211. // Check if the access is smaller than the vector size and can we find
  2212. // a reasonable extract index.
  2213. int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
  2214. int StartIdx[2]; // StartIdx to extract from
  2215. for (int Input=0; Input < 2; ++Input) {
  2216. if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
  2217. RangeUse[Input] = 0; // Unused
  2218. StartIdx[Input] = 0;
  2219. } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
  2220. // Fits within range but we should see if we can find a good
  2221. // start index that is a multiple of the mask length.
  2222. if (MaxRange[Input] < MaskNumElts) {
  2223. RangeUse[Input] = 1; // Extract from beginning of the vector
  2224. StartIdx[Input] = 0;
  2225. } else {
  2226. StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
  2227. if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
  2228. StartIdx[Input] + MaskNumElts < SrcNumElts)
  2229. RangeUse[Input] = 1; // Extract from a multiple of the mask length.
  2230. }
  2231. }
  2232. }
  2233. if (RangeUse[0] == 0 && RangeUse[0] == 0) {
  2234. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2235. return;
  2236. }
  2237. else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
  2238. // Extract appropriate subvector and generate a vector shuffle
  2239. for (int Input=0; Input < 2; ++Input) {
  2240. SDValue& Src = Input == 0 ? Src1 : Src2;
  2241. if (RangeUse[Input] == 0) {
  2242. Src = DAG.getUNDEF(VT);
  2243. } else {
  2244. Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
  2245. Src, DAG.getIntPtrConstant(StartIdx[Input]));
  2246. }
  2247. }
  2248. // Calculate new mask.
  2249. SmallVector<int, 8> MappedOps;
  2250. for (int i = 0; i != MaskNumElts; ++i) {
  2251. int Idx = Mask[i];
  2252. if (Idx < 0)
  2253. MappedOps.push_back(Idx);
  2254. else if (Idx < SrcNumElts)
  2255. MappedOps.push_back(Idx - StartIdx[0]);
  2256. else
  2257. MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
  2258. }
  2259. setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
  2260. &MappedOps[0]));
  2261. return;
  2262. }
  2263. }
  2264. // We can't use either concat vectors or extract subvectors so fall back to
  2265. // replacing the shuffle with extract and build vector.
  2266. // to insert and build vector.
  2267. MVT EltVT = VT.getVectorElementType();
  2268. MVT PtrVT = TLI.getPointerTy();
  2269. SmallVector<SDValue,8> Ops;
  2270. for (int i = 0; i != MaskNumElts; ++i) {
  2271. if (Mask[i] < 0) {
  2272. Ops.push_back(DAG.getUNDEF(EltVT));
  2273. } else {
  2274. int Idx = Mask[i];
  2275. if (Idx < SrcNumElts)
  2276. Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
  2277. EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
  2278. else
  2279. Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
  2280. EltVT, Src2,
  2281. DAG.getConstant(Idx - SrcNumElts, PtrVT)));
  2282. }
  2283. }
  2284. setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
  2285. VT, &Ops[0], Ops.size()));
  2286. }
  2287. void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
  2288. const Value *Op0 = I.getOperand(0);
  2289. const Value *Op1 = I.getOperand(1);
  2290. const Type *AggTy = I.getType();
  2291. const Type *ValTy = Op1->getType();
  2292. bool IntoUndef = isa<UndefValue>(Op0);
  2293. bool FromUndef = isa<UndefValue>(Op1);
  2294. unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
  2295. I.idx_begin(), I.idx_end());
  2296. SmallVector<MVT, 4> AggValueVTs;
  2297. ComputeValueVTs(TLI, AggTy, AggValueVTs);
  2298. SmallVector<MVT, 4> ValValueVTs;
  2299. ComputeValueVTs(TLI, ValTy, ValValueVTs);
  2300. unsigned NumAggValues = AggValueVTs.size();
  2301. unsigned NumValValues = ValValueVTs.size();
  2302. SmallVector<SDValue, 4> Values(NumAggValues);
  2303. SDValue Agg = getValue(Op0);
  2304. SDValue Val = getValue(Op1);
  2305. unsigned i = 0;
  2306. // Copy the beginning value(s) from the original aggregate.
  2307. for (; i != LinearIndex; ++i)
  2308. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2309. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2310. // Copy values from the inserted value(s).
  2311. for (; i != LinearIndex + NumValValues; ++i)
  2312. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2313. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2314. // Copy remaining value(s) from the original aggregate.
  2315. for (; i != NumAggValues; ++i)
  2316. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2317. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2318. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2319. DAG.getVTList(&AggValueVTs[0], NumAggValues),
  2320. &Values[0], NumAggValues));
  2321. }
  2322. void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
  2323. const Value *Op0 = I.getOperand(0);
  2324. const Type *AggTy = Op0->getType();
  2325. const Type *ValTy = I.getType();
  2326. bool OutOfUndef = isa<UndefValue>(Op0);
  2327. unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
  2328. I.idx_begin(), I.idx_end());
  2329. SmallVector<MVT, 4> ValValueVTs;
  2330. ComputeValueVTs(TLI, ValTy, ValValueVTs);
  2331. unsigned NumValValues = ValValueVTs.size();
  2332. SmallVector<SDValue, 4> Values(NumValValues);
  2333. SDValue Agg = getValue(Op0);
  2334. // Copy out the selected value(s).
  2335. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2336. Values[i - LinearIndex] =
  2337. OutOfUndef ?
  2338. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2339. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2340. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2341. DAG.getVTList(&ValValueVTs[0], NumValValues),
  2342. &Values[0], NumValValues));
  2343. }
  2344. void SelectionDAGLowering::visitGetElementPtr(User &I) {
  2345. SDValue N = getValue(I.getOperand(0));
  2346. const Type *Ty = I.getOperand(0)->getType();
  2347. for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
  2348. OI != E; ++OI) {
  2349. Value *Idx = *OI;
  2350. if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
  2351. unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
  2352. if (Field) {
  2353. // N = N + Offset
  2354. uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
  2355. N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
  2356. DAG.getIntPtrConstant(Offset));
  2357. }
  2358. Ty = StTy->getElementType(Field);
  2359. } else {
  2360. Ty = cast<SequentialType>(Ty)->getElementType();
  2361. // If this is a constant subscript, handle it quickly.
  2362. if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
  2363. if (CI->getZExtValue() == 0) continue;
  2364. uint64_t Offs =
  2365. TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
  2366. SDValue OffsVal;
  2367. unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
  2368. if (PtrBits < 64) {
  2369. OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  2370. TLI.getPointerTy(),
  2371. DAG.getConstant(Offs, MVT::i64));
  2372. } else
  2373. OffsVal = DAG.getIntPtrConstant(Offs);
  2374. N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
  2375. OffsVal);
  2376. continue;
  2377. }
  2378. // N = N + Idx * ElementSize;
  2379. uint64_t ElementSize = TD->getTypePaddedSize(Ty);
  2380. SDValue IdxN = getValue(Idx);
  2381. // If the index is smaller or larger than intptr_t, truncate or extend
  2382. // it.
  2383. if (IdxN.getValueType().bitsLT(N.getValueType()))
  2384. IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
  2385. N.getValueType(), IdxN);
  2386. else if (IdxN.getValueType().bitsGT(N.getValueType()))
  2387. IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  2388. N.getValueType(), IdxN);
  2389. // If this is a multiply by a power of two, turn it into a shl
  2390. // immediately. This is a very common case.
  2391. if (ElementSize != 1) {
  2392. if (isPowerOf2_64(ElementSize)) {
  2393. unsigned Amt = Log2_64(ElementSize);
  2394. IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
  2395. N.getValueType(), IdxN,
  2396. DAG.getConstant(Amt, TLI.getPointerTy()));
  2397. } else {
  2398. SDValue Scale = DAG.getIntPtrConstant(ElementSize);
  2399. IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
  2400. N.getValueType(), IdxN, Scale);
  2401. }
  2402. }
  2403. N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2404. N.getValueType(), N, IdxN);
  2405. }
  2406. }
  2407. setValue(&I, N);
  2408. }
  2409. void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
  2410. // If this is a fixed sized alloca in the entry block of the function,
  2411. // allocate it statically on the stack.
  2412. if (FuncInfo.StaticAllocaMap.count(&I))
  2413. return; // getValue will auto-populate this.
  2414. const Type *Ty = I.getAllocatedType();
  2415. uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
  2416. unsigned Align =
  2417. std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
  2418. I.getAlignment());
  2419. SDValue AllocSize = getValue(I.getArraySize());
  2420. AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
  2421. AllocSize,
  2422. DAG.getConstant(TySize, AllocSize.getValueType()));
  2423. MVT IntPtr = TLI.getPointerTy();
  2424. if (IntPtr.bitsLT(AllocSize.getValueType()))
  2425. AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  2426. IntPtr, AllocSize);
  2427. else if (IntPtr.bitsGT(AllocSize.getValueType()))
  2428. AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  2429. IntPtr, AllocSize);
  2430. // Handle alignment. If the requested alignment is less than or equal to
  2431. // the stack alignment, ignore it. If the size is greater than or equal to
  2432. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  2433. unsigned StackAlign =
  2434. TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
  2435. if (Align <= StackAlign)
  2436. Align = 0;
  2437. // Round the size of the allocation up to the stack alignment size
  2438. // by add SA-1 to the size.
  2439. AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2440. AllocSize.getValueType(), AllocSize,
  2441. DAG.getIntPtrConstant(StackAlign-1));
  2442. // Mask out the low bits for alignment purposes.
  2443. AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
  2444. AllocSize.getValueType(), AllocSize,
  2445. DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
  2446. SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
  2447. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  2448. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
  2449. VTs, Ops, 3);
  2450. setValue(&I, DSA);
  2451. DAG.setRoot(DSA.getValue(1));
  2452. // Inform the Frame Information that we have just allocated a variable-sized
  2453. // object.
  2454. CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
  2455. }
  2456. void SelectionDAGLowering::visitLoad(LoadInst &I) {
  2457. const Value *SV = I.getOperand(0);
  2458. SDValue Ptr = getValue(SV);
  2459. const Type *Ty = I.getType();
  2460. bool isVolatile = I.isVolatile();
  2461. unsigned Alignment = I.getAlignment();
  2462. SmallVector<MVT, 4> ValueVTs;
  2463. SmallVector<uint64_t, 4> Offsets;
  2464. ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
  2465. unsigned NumValues = ValueVTs.size();
  2466. if (NumValues == 0)
  2467. return;
  2468. SDValue Root;
  2469. bool ConstantMemory = false;
  2470. if (I.isVolatile())
  2471. // Serialize volatile loads with other side effects.
  2472. Root = getRoot();
  2473. else if (AA->pointsToConstantMemory(SV)) {
  2474. // Do not serialize (non-volatile) loads of constant memory with anything.
  2475. Root = DAG.getEntryNode();
  2476. ConstantMemory = true;
  2477. } else {
  2478. // Do not serialize non-volatile loads against each other.
  2479. Root = DAG.getRoot();
  2480. }
  2481. SmallVector<SDValue, 4> Values(NumValues);
  2482. SmallVector<SDValue, 4> Chains(NumValues);
  2483. MVT PtrVT = Ptr.getValueType();
  2484. for (unsigned i = 0; i != NumValues; ++i) {
  2485. SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
  2486. DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2487. PtrVT, Ptr,
  2488. DAG.getConstant(Offsets[i], PtrVT)),
  2489. SV, Offsets[i],
  2490. isVolatile, Alignment);
  2491. Values[i] = L;
  2492. Chains[i] = L.getValue(1);
  2493. }
  2494. if (!ConstantMemory) {
  2495. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  2496. MVT::Other,
  2497. &Chains[0], NumValues);
  2498. if (isVolatile)
  2499. DAG.setRoot(Chain);
  2500. else
  2501. PendingLoads.push_back(Chain);
  2502. }
  2503. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2504. DAG.getVTList(&ValueVTs[0], NumValues),
  2505. &Values[0], NumValues));
  2506. }
  2507. void SelectionDAGLowering::visitStore(StoreInst &I) {
  2508. Value *SrcV = I.getOperand(0);
  2509. Value *PtrV = I.getOperand(1);
  2510. SmallVector<MVT, 4> ValueVTs;
  2511. SmallVector<uint64_t, 4> Offsets;
  2512. ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
  2513. unsigned NumValues = ValueVTs.size();
  2514. if (NumValues == 0)
  2515. return;
  2516. // Get the lowered operands. Note that we do this after
  2517. // checking if NumResults is zero, because with zero results
  2518. // the operands won't have values in the map.
  2519. SDValue Src = getValue(SrcV);
  2520. SDValue Ptr = getValue(PtrV);
  2521. SDValue Root = getRoot();
  2522. SmallVector<SDValue, 4> Chains(NumValues);
  2523. MVT PtrVT = Ptr.getValueType();
  2524. bool isVolatile = I.isVolatile();
  2525. unsigned Alignment = I.getAlignment();
  2526. for (unsigned i = 0; i != NumValues; ++i)
  2527. Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
  2528. SDValue(Src.getNode(), Src.getResNo() + i),
  2529. DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2530. PtrVT, Ptr,
  2531. DAG.getConstant(Offsets[i], PtrVT)),
  2532. PtrV, Offsets[i],
  2533. isVolatile, Alignment);
  2534. DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  2535. MVT::Other, &Chains[0], NumValues));
  2536. }
  2537. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  2538. /// node.
  2539. void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
  2540. unsigned Intrinsic) {
  2541. bool HasChain = !I.doesNotAccessMemory();
  2542. bool OnlyLoad = HasChain && I.onlyReadsMemory();
  2543. // Build the operand list.
  2544. SmallVector<SDValue, 8> Ops;
  2545. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  2546. if (OnlyLoad) {
  2547. // We don't need to serialize loads against other loads.
  2548. Ops.push_back(DAG.getRoot());
  2549. } else {
  2550. Ops.push_back(getRoot());
  2551. }
  2552. }
  2553. // Info is set by getTgtMemInstrinsic
  2554. TargetLowering::IntrinsicInfo Info;
  2555. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
  2556. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  2557. if (!IsTgtIntrinsic)
  2558. Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
  2559. // Add all operands of the call to the operand list.
  2560. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
  2561. SDValue Op = getValue(I.getOperand(i));
  2562. assert(TLI.isTypeLegal(Op.getValueType()) &&
  2563. "Intrinsic uses a non-legal type?");
  2564. Ops.push_back(Op);
  2565. }
  2566. std::vector<MVT> VTArray;
  2567. if (I.getType() != Type::VoidTy) {
  2568. MVT VT = TLI.getValueType(I.getType());
  2569. if (VT.isVector()) {
  2570. const VectorType *DestTy = cast<VectorType>(I.getType());
  2571. MVT EltVT = TLI.getValueType(DestTy->getElementType());
  2572. VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
  2573. assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
  2574. }
  2575. assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
  2576. VTArray.push_back(VT);
  2577. }
  2578. if (HasChain)
  2579. VTArray.push_back(MVT::Other);
  2580. SDVTList VTs = DAG.getVTList(&VTArray[0], VTArray.size());
  2581. // Create the node.
  2582. SDValue Result;
  2583. if (IsTgtIntrinsic) {
  2584. // This is target intrinsic that touches memory
  2585. Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
  2586. VTs, &Ops[0], Ops.size(),
  2587. Info.memVT, Info.ptrVal, Info.offset,
  2588. Info.align, Info.vol,
  2589. Info.readMem, Info.writeMem);
  2590. }
  2591. else if (!HasChain)
  2592. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
  2593. VTs, &Ops[0], Ops.size());
  2594. else if (I.getType() != Type::VoidTy)
  2595. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
  2596. VTs, &Ops[0], Ops.size());
  2597. else
  2598. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
  2599. VTs, &Ops[0], Ops.size());
  2600. if (HasChain) {
  2601. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  2602. if (OnlyLoad)
  2603. PendingLoads.push_back(Chain);
  2604. else
  2605. DAG.setRoot(Chain);
  2606. }
  2607. if (I.getType() != Type::VoidTy) {
  2608. if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  2609. MVT VT = TLI.getValueType(PTy);
  2610. Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
  2611. }
  2612. setValue(&I, Result);
  2613. }
  2614. }
  2615. /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
  2616. static GlobalVariable *ExtractTypeInfo(Value *V) {
  2617. V = V->stripPointerCasts();
  2618. GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
  2619. assert ((GV || isa<ConstantPointerNull>(V)) &&
  2620. "TypeInfo must be a global variable or NULL");
  2621. return GV;
  2622. }
  2623. namespace llvm {
  2624. /// AddCatchInfo - Extract the personality and type infos from an eh.selector
  2625. /// call, and add them to the specified machine basic block.
  2626. void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
  2627. MachineBasicBlock *MBB) {
  2628. // Inform the MachineModuleInfo of the personality for this landing pad.
  2629. ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
  2630. assert(CE->getOpcode() == Instruction::BitCast &&
  2631. isa<Function>(CE->getOperand(0)) &&
  2632. "Personality should be a function");
  2633. MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
  2634. // Gather all the type infos for this landing pad and pass them along to
  2635. // MachineModuleInfo.
  2636. std::vector<GlobalVariable *> TyInfo;
  2637. unsigned N = I.getNumOperands();
  2638. for (unsigned i = N - 1; i > 2; --i) {
  2639. if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
  2640. unsigned FilterLength = CI->getZExtValue();
  2641. unsigned FirstCatch = i + FilterLength + !FilterLength;
  2642. assert (FirstCatch <= N && "Invalid filter length");
  2643. if (FirstCatch < N) {
  2644. TyInfo.reserve(N - FirstCatch);
  2645. for (unsigned j = FirstCatch; j < N; ++j)
  2646. TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
  2647. MMI->addCatchTypeInfo(MBB, TyInfo);
  2648. TyInfo.clear();
  2649. }
  2650. if (!FilterLength) {
  2651. // Cleanup.
  2652. MMI->addCleanup(MBB);
  2653. } else {
  2654. // Filter.
  2655. TyInfo.reserve(FilterLength - 1);
  2656. for (unsigned j = i + 1; j < FirstCatch; ++j)
  2657. TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
  2658. MMI->addFilterTypeInfo(MBB, TyInfo);
  2659. TyInfo.clear();
  2660. }
  2661. N = i;
  2662. }
  2663. }
  2664. if (N > 3) {
  2665. TyInfo.reserve(N - 3);
  2666. for (unsigned j = 3; j < N; ++j)
  2667. TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
  2668. MMI->addCatchTypeInfo(MBB, TyInfo);
  2669. }
  2670. }
  2671. }
  2672. /// GetSignificand - Get the significand and build it into a floating-point
  2673. /// number with exponent of 1:
  2674. ///
  2675. /// Op = (Op & 0x007fffff) | 0x3f800000;
  2676. ///
  2677. /// where Op is the hexidecimal representation of floating point value.
  2678. static SDValue
  2679. GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
  2680. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  2681. DAG.getConstant(0x007fffff, MVT::i32));
  2682. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  2683. DAG.getConstant(0x3f800000, MVT::i32));
  2684. return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
  2685. }
  2686. /// GetExponent - Get the exponent:
  2687. ///
  2688. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  2689. ///
  2690. /// where Op is the hexidecimal representation of floating point value.
  2691. static SDValue
  2692. GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
  2693. DebugLoc dl) {
  2694. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  2695. DAG.getConstant(0x7f800000, MVT::i32));
  2696. SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
  2697. DAG.getConstant(23, TLI.getPointerTy()));
  2698. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  2699. DAG.getConstant(127, MVT::i32));
  2700. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  2701. }
  2702. /// getF32Constant - Get 32-bit floating point constant.
  2703. static SDValue
  2704. getF32Constant(SelectionDAG &DAG, unsigned Flt) {
  2705. return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
  2706. }
  2707. /// Inlined utility function to implement binary input atomic intrinsics for
  2708. /// visitIntrinsicCall: I is a call instruction
  2709. /// Op is the associated NodeType for I
  2710. const char *
  2711. SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
  2712. SDValue Root = getRoot();
  2713. SDValue L =
  2714. DAG.getAtomic(Op, getCurDebugLoc(),
  2715. getValue(I.getOperand(2)).getValueType().getSimpleVT(),
  2716. Root,
  2717. getValue(I.getOperand(1)),
  2718. getValue(I.getOperand(2)),
  2719. I.getOperand(1));
  2720. setValue(&I, L);
  2721. DAG.setRoot(L.getValue(1));
  2722. return 0;
  2723. }
  2724. // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
  2725. const char *
  2726. SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
  2727. SDValue Op1 = getValue(I.getOperand(1));
  2728. SDValue Op2 = getValue(I.getOperand(2));
  2729. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  2730. SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
  2731. setValue(&I, Result);
  2732. return 0;
  2733. }
  2734. /// visitExp - Lower an exp intrinsic. Handles the special sequences for
  2735. /// limited-precision mode.
  2736. void
  2737. SelectionDAGLowering::visitExp(CallInst &I) {
  2738. SDValue result;
  2739. DebugLoc dl = getCurDebugLoc();
  2740. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  2741. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2742. SDValue Op = getValue(I.getOperand(1));
  2743. // Put the exponent in the right bit position for later addition to the
  2744. // final result:
  2745. //
  2746. // #define LOG2OFe 1.4426950f
  2747. // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
  2748. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  2749. getF32Constant(DAG, 0x3fb8aa3b));
  2750. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  2751. // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
  2752. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  2753. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  2754. // IntegerPartOfX <<= 23;
  2755. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  2756. DAG.getConstant(23, TLI.getPointerTy()));
  2757. if (LimitFloatPrecision <= 6) {
  2758. // For floating-point precision of 6:
  2759. //
  2760. // TwoToFractionalPartOfX =
  2761. // 0.997535578f +
  2762. // (0.735607626f + 0.252464424f * x) * x;
  2763. //
  2764. // error 0.0144103317, which is 6 bits
  2765. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2766. getF32Constant(DAG, 0x3e814304));
  2767. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2768. getF32Constant(DAG, 0x3f3c50c8));
  2769. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2770. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2771. getF32Constant(DAG, 0x3f7f5e7e));
  2772. SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
  2773. // Add the exponent into the result in integer domain.
  2774. SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  2775. TwoToFracPartOfX, IntegerPartOfX);
  2776. result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
  2777. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2778. // For floating-point precision of 12:
  2779. //
  2780. // TwoToFractionalPartOfX =
  2781. // 0.999892986f +
  2782. // (0.696457318f +
  2783. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  2784. //
  2785. // 0.000107046256 error, which is 13 to 14 bits
  2786. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2787. getF32Constant(DAG, 0x3da235e3));
  2788. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2789. getF32Constant(DAG, 0x3e65b8f3));
  2790. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2791. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2792. getF32Constant(DAG, 0x3f324b07));
  2793. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2794. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  2795. getF32Constant(DAG, 0x3f7ff8fd));
  2796. SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
  2797. // Add the exponent into the result in integer domain.
  2798. SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  2799. TwoToFracPartOfX, IntegerPartOfX);
  2800. result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
  2801. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  2802. // For floating-point precision of 18:
  2803. //
  2804. // TwoToFractionalPartOfX =
  2805. // 0.999999982f +
  2806. // (0.693148872f +
  2807. // (0.240227044f +
  2808. // (0.554906021e-1f +
  2809. // (0.961591928e-2f +
  2810. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  2811. //
  2812. // error 2.47208000*10^(-7), which is better than 18 bits
  2813. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2814. getF32Constant(DAG, 0x3924b03e));
  2815. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2816. getF32Constant(DAG, 0x3ab24b87));
  2817. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2818. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2819. getF32Constant(DAG, 0x3c1d8c17));
  2820. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2821. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  2822. getF32Constant(DAG, 0x3d634a1d));
  2823. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  2824. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  2825. getF32Constant(DAG, 0x3e75fe14));
  2826. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  2827. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  2828. getF32Constant(DAG, 0x3f317234));
  2829. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  2830. SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  2831. getF32Constant(DAG, 0x3f800000));
  2832. SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
  2833. MVT::i32, t13);
  2834. // Add the exponent into the result in integer domain.
  2835. SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  2836. TwoToFracPartOfX, IntegerPartOfX);
  2837. result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
  2838. }
  2839. } else {
  2840. // No special expansion.
  2841. result = DAG.getNode(ISD::FEXP, dl,
  2842. getValue(I.getOperand(1)).getValueType(),
  2843. getValue(I.getOperand(1)));
  2844. }
  2845. setValue(&I, result);
  2846. }
  2847. /// visitLog - Lower a log intrinsic. Handles the special sequences for
  2848. /// limited-precision mode.
  2849. void
  2850. SelectionDAGLowering::visitLog(CallInst &I) {
  2851. SDValue result;
  2852. DebugLoc dl = getCurDebugLoc();
  2853. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  2854. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2855. SDValue Op = getValue(I.getOperand(1));
  2856. SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
  2857. // Scale the exponent by log(2) [0.69314718f].
  2858. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  2859. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  2860. getF32Constant(DAG, 0x3f317218));
  2861. // Get the significand and build it into a floating-point number with
  2862. // exponent of 1.
  2863. SDValue X = GetSignificand(DAG, Op1, dl);
  2864. if (LimitFloatPrecision <= 6) {
  2865. // For floating-point precision of 6:
  2866. //
  2867. // LogofMantissa =
  2868. // -1.1609546f +
  2869. // (1.4034025f - 0.23903021f * x) * x;
  2870. //
  2871. // error 0.0034276066, which is better than 8 bits
  2872. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2873. getF32Constant(DAG, 0xbe74c456));
  2874. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2875. getF32Constant(DAG, 0x3fb3a2b1));
  2876. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2877. SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2878. getF32Constant(DAG, 0x3f949a29));
  2879. result = DAG.getNode(ISD::FADD, dl,
  2880. MVT::f32, LogOfExponent, LogOfMantissa);
  2881. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2882. // For floating-point precision of 12:
  2883. //
  2884. // LogOfMantissa =
  2885. // -1.7417939f +
  2886. // (2.8212026f +
  2887. // (-1.4699568f +
  2888. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  2889. //
  2890. // error 0.000061011436, which is 14 bits
  2891. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2892. getF32Constant(DAG, 0xbd67b6d6));
  2893. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2894. getF32Constant(DAG, 0x3ee4f4b8));
  2895. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2896. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2897. getF32Constant(DAG, 0x3fbc278b));
  2898. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2899. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2900. getF32Constant(DAG, 0x40348e95));
  2901. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2902. SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  2903. getF32Constant(DAG, 0x3fdef31a));
  2904. result = DAG.getNode(ISD::FADD, dl,
  2905. MVT::f32, LogOfExponent, LogOfMantissa);
  2906. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  2907. // For floating-point precision of 18:
  2908. //
  2909. // LogOfMantissa =
  2910. // -2.1072184f +
  2911. // (4.2372794f +
  2912. // (-3.7029485f +
  2913. // (2.2781945f +
  2914. // (-0.87823314f +
  2915. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  2916. //
  2917. // error 0.0000023660568, which is better than 18 bits
  2918. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2919. getF32Constant(DAG, 0xbc91e5ac));
  2920. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2921. getF32Constant(DAG, 0x3e4350aa));
  2922. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2923. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2924. getF32Constant(DAG, 0x3f60d3e3));
  2925. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2926. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2927. getF32Constant(DAG, 0x4011cdf0));
  2928. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2929. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  2930. getF32Constant(DAG, 0x406cfd1c));
  2931. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  2932. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  2933. getF32Constant(DAG, 0x408797cb));
  2934. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  2935. SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  2936. getF32Constant(DAG, 0x4006dcab));
  2937. result = DAG.getNode(ISD::FADD, dl,
  2938. MVT::f32, LogOfExponent, LogOfMantissa);
  2939. }
  2940. } else {
  2941. // No special expansion.
  2942. result = DAG.getNode(ISD::FLOG, dl,
  2943. getValue(I.getOperand(1)).getValueType(),
  2944. getValue(I.getOperand(1)));
  2945. }
  2946. setValue(&I, result);
  2947. }
  2948. /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
  2949. /// limited-precision mode.
  2950. void
  2951. SelectionDAGLowering::visitLog2(CallInst &I) {
  2952. SDValue result;
  2953. DebugLoc dl = getCurDebugLoc();
  2954. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  2955. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2956. SDValue Op = getValue(I.getOperand(1));
  2957. SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
  2958. // Get the exponent.
  2959. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  2960. // Get the significand and build it into a floating-point number with
  2961. // exponent of 1.
  2962. SDValue X = GetSignificand(DAG, Op1, dl);
  2963. // Different possible minimax approximations of significand in
  2964. // floating-point for various degrees of accuracy over [1,2].
  2965. if (LimitFloatPrecision <= 6) {
  2966. // For floating-point precision of 6:
  2967. //
  2968. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  2969. //
  2970. // error 0.0049451742, which is more than 7 bits
  2971. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2972. getF32Constant(DAG, 0xbeb08fe0));
  2973. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2974. getF32Constant(DAG, 0x40019463));
  2975. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2976. SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2977. getF32Constant(DAG, 0x3fd6633d));
  2978. result = DAG.getNode(ISD::FADD, dl,
  2979. MVT::f32, LogOfExponent, Log2ofMantissa);
  2980. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2981. // For floating-point precision of 12:
  2982. //
  2983. // Log2ofMantissa =
  2984. // -2.51285454f +
  2985. // (4.07009056f +
  2986. // (-2.12067489f +
  2987. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  2988. //
  2989. // error 0.0000876136000, which is better than 13 bits
  2990. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2991. getF32Constant(DAG, 0xbda7262e));
  2992. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2993. getF32Constant(DAG, 0x3f25280b));
  2994. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2995. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2996. getF32Constant(DAG, 0x4007b923));
  2997. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2998. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2999. getF32Constant(DAG, 0x40823e2f));
  3000. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3001. SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3002. getF32Constant(DAG, 0x4020d29c));
  3003. result = DAG.getNode(ISD::FADD, dl,
  3004. MVT::f32, LogOfExponent, Log2ofMantissa);
  3005. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3006. // For floating-point precision of 18:
  3007. //
  3008. // Log2ofMantissa =
  3009. // -3.0400495f +
  3010. // (6.1129976f +
  3011. // (-5.3420409f +
  3012. // (3.2865683f +
  3013. // (-1.2669343f +
  3014. // (0.27515199f -
  3015. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  3016. //
  3017. // error 0.0000018516, which is better than 18 bits
  3018. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3019. getF32Constant(DAG, 0xbcd2769e));
  3020. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3021. getF32Constant(DAG, 0x3e8ce0b9));
  3022. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3023. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3024. getF32Constant(DAG, 0x3fa22ae7));
  3025. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3026. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3027. getF32Constant(DAG, 0x40525723));
  3028. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3029. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3030. getF32Constant(DAG, 0x40aaf200));
  3031. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3032. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3033. getF32Constant(DAG, 0x40c39dad));
  3034. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3035. SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3036. getF32Constant(DAG, 0x4042902c));
  3037. result = DAG.getNode(ISD::FADD, dl,
  3038. MVT::f32, LogOfExponent, Log2ofMantissa);
  3039. }
  3040. } else {
  3041. // No special expansion.
  3042. result = DAG.getNode(ISD::FLOG2, dl,
  3043. getValue(I.getOperand(1)).getValueType(),
  3044. getValue(I.getOperand(1)));
  3045. }
  3046. setValue(&I, result);
  3047. }
  3048. /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
  3049. /// limited-precision mode.
  3050. void
  3051. SelectionDAGLowering::visitLog10(CallInst &I) {
  3052. SDValue result;
  3053. DebugLoc dl = getCurDebugLoc();
  3054. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  3055. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3056. SDValue Op = getValue(I.getOperand(1));
  3057. SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
  3058. // Scale the exponent by log10(2) [0.30102999f].
  3059. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3060. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3061. getF32Constant(DAG, 0x3e9a209a));
  3062. // Get the significand and build it into a floating-point number with
  3063. // exponent of 1.
  3064. SDValue X = GetSignificand(DAG, Op1, dl);
  3065. if (LimitFloatPrecision <= 6) {
  3066. // For floating-point precision of 6:
  3067. //
  3068. // Log10ofMantissa =
  3069. // -0.50419619f +
  3070. // (0.60948995f - 0.10380950f * x) * x;
  3071. //
  3072. // error 0.0014886165, which is 6 bits
  3073. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3074. getF32Constant(DAG, 0xbdd49a13));
  3075. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3076. getF32Constant(DAG, 0x3f1c0789));
  3077. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3078. SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3079. getF32Constant(DAG, 0x3f011300));
  3080. result = DAG.getNode(ISD::FADD, dl,
  3081. MVT::f32, LogOfExponent, Log10ofMantissa);
  3082. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  3083. // For floating-point precision of 12:
  3084. //
  3085. // Log10ofMantissa =
  3086. // -0.64831180f +
  3087. // (0.91751397f +
  3088. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  3089. //
  3090. // error 0.00019228036, which is better than 12 bits
  3091. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3092. getF32Constant(DAG, 0x3d431f31));
  3093. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3094. getF32Constant(DAG, 0x3ea21fb2));
  3095. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3096. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3097. getF32Constant(DAG, 0x3f6ae232));
  3098. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3099. SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3100. getF32Constant(DAG, 0x3f25f7c3));
  3101. result = DAG.getNode(ISD::FADD, dl,
  3102. MVT::f32, LogOfExponent, Log10ofMantissa);
  3103. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3104. // For floating-point precision of 18:
  3105. //
  3106. // Log10ofMantissa =
  3107. // -0.84299375f +
  3108. // (1.5327582f +
  3109. // (-1.0688956f +
  3110. // (0.49102474f +
  3111. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  3112. //
  3113. // error 0.0000037995730, which is better than 18 bits
  3114. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3115. getF32Constant(DAG, 0x3c5d51ce));
  3116. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3117. getF32Constant(DAG, 0x3e00685a));
  3118. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3119. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3120. getF32Constant(DAG, 0x3efb6798));
  3121. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3122. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3123. getF32Constant(DAG, 0x3f88d192));
  3124. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3125. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3126. getF32Constant(DAG, 0x3fc4316c));
  3127. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3128. SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  3129. getF32Constant(DAG, 0x3f57ce70));
  3130. result = DAG.getNode(ISD::FADD, dl,
  3131. MVT::f32, LogOfExponent, Log10ofMantissa);
  3132. }
  3133. } else {
  3134. // No special expansion.
  3135. result = DAG.getNode(ISD::FLOG10, dl,
  3136. getValue(I.getOperand(1)).getValueType(),
  3137. getValue(I.getOperand(1)));
  3138. }
  3139. setValue(&I, result);
  3140. }
  3141. /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  3142. /// limited-precision mode.
  3143. void
  3144. SelectionDAGLowering::visitExp2(CallInst &I) {
  3145. SDValue result;
  3146. DebugLoc dl = getCurDebugLoc();
  3147. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  3148. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3149. SDValue Op = getValue(I.getOperand(1));
  3150. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
  3151. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3152. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3153. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
  3154. // IntegerPartOfX <<= 23;
  3155. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3156. DAG.getConstant(23, TLI.getPointerTy()));
  3157. if (LimitFloatPrecision <= 6) {
  3158. // For floating-point precision of 6:
  3159. //
  3160. // TwoToFractionalPartOfX =
  3161. // 0.997535578f +
  3162. // (0.735607626f + 0.252464424f * x) * x;
  3163. //
  3164. // error 0.0144103317, which is 6 bits
  3165. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3166. getF32Constant(DAG, 0x3e814304));
  3167. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3168. getF32Constant(DAG, 0x3f3c50c8));
  3169. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3170. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3171. getF32Constant(DAG, 0x3f7f5e7e));
  3172. SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
  3173. SDValue TwoToFractionalPartOfX =
  3174. DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
  3175. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3176. MVT::f32, TwoToFractionalPartOfX);
  3177. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  3178. // For floating-point precision of 12:
  3179. //
  3180. // TwoToFractionalPartOfX =
  3181. // 0.999892986f +
  3182. // (0.696457318f +
  3183. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3184. //
  3185. // error 0.000107046256, which is 13 to 14 bits
  3186. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3187. getF32Constant(DAG, 0x3da235e3));
  3188. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3189. getF32Constant(DAG, 0x3e65b8f3));
  3190. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3191. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3192. getF32Constant(DAG, 0x3f324b07));
  3193. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3194. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3195. getF32Constant(DAG, 0x3f7ff8fd));
  3196. SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
  3197. SDValue TwoToFractionalPartOfX =
  3198. DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
  3199. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3200. MVT::f32, TwoToFractionalPartOfX);
  3201. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3202. // For floating-point precision of 18:
  3203. //
  3204. // TwoToFractionalPartOfX =
  3205. // 0.999999982f +
  3206. // (0.693148872f +
  3207. // (0.240227044f +
  3208. // (0.554906021e-1f +
  3209. // (0.961591928e-2f +
  3210. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3211. // error 2.47208000*10^(-7), which is better than 18 bits
  3212. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3213. getF32Constant(DAG, 0x3924b03e));
  3214. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3215. getF32Constant(DAG, 0x3ab24b87));
  3216. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3217. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3218. getF32Constant(DAG, 0x3c1d8c17));
  3219. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3220. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3221. getF32Constant(DAG, 0x3d634a1d));
  3222. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3223. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3224. getF32Constant(DAG, 0x3e75fe14));
  3225. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3226. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3227. getF32Constant(DAG, 0x3f317234));
  3228. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3229. SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3230. getF32Constant(DAG, 0x3f800000));
  3231. SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
  3232. SDValue TwoToFractionalPartOfX =
  3233. DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
  3234. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3235. MVT::f32, TwoToFractionalPartOfX);
  3236. }
  3237. } else {
  3238. // No special expansion.
  3239. result = DAG.getNode(ISD::FEXP2, dl,
  3240. getValue(I.getOperand(1)).getValueType(),
  3241. getValue(I.getOperand(1)));
  3242. }
  3243. setValue(&I, result);
  3244. }
  3245. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  3246. /// limited-precision mode with x == 10.0f.
  3247. void
  3248. SelectionDAGLowering::visitPow(CallInst &I) {
  3249. SDValue result;
  3250. Value *Val = I.getOperand(1);
  3251. DebugLoc dl = getCurDebugLoc();
  3252. bool IsExp10 = false;
  3253. if (getValue(Val).getValueType() == MVT::f32 &&
  3254. getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
  3255. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3256. if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
  3257. if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  3258. APFloat Ten(10.0f);
  3259. IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
  3260. }
  3261. }
  3262. }
  3263. if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3264. SDValue Op = getValue(I.getOperand(2));
  3265. // Put the exponent in the right bit position for later addition to the
  3266. // final result:
  3267. //
  3268. // #define LOG2OF10 3.3219281f
  3269. // IntegerPartOfX = (int32_t)(x * LOG2OF10);
  3270. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3271. getF32Constant(DAG, 0x40549a78));
  3272. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3273. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3274. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3275. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3276. // IntegerPartOfX <<= 23;
  3277. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3278. DAG.getConstant(23, TLI.getPointerTy()));
  3279. if (LimitFloatPrecision <= 6) {
  3280. // For floating-point precision of 6:
  3281. //
  3282. // twoToFractionalPartOfX =
  3283. // 0.997535578f +
  3284. // (0.735607626f + 0.252464424f * x) * x;
  3285. //
  3286. // error 0.0144103317, which is 6 bits
  3287. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3288. getF32Constant(DAG, 0x3e814304));
  3289. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3290. getF32Constant(DAG, 0x3f3c50c8));
  3291. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3292. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3293. getF32Constant(DAG, 0x3f7f5e7e));
  3294. SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
  3295. SDValue TwoToFractionalPartOfX =
  3296. DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
  3297. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3298. MVT::f32, TwoToFractionalPartOfX);
  3299. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  3300. // For floating-point precision of 12:
  3301. //
  3302. // TwoToFractionalPartOfX =
  3303. // 0.999892986f +
  3304. // (0.696457318f +
  3305. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3306. //
  3307. // error 0.000107046256, which is 13 to 14 bits
  3308. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3309. getF32Constant(DAG, 0x3da235e3));
  3310. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3311. getF32Constant(DAG, 0x3e65b8f3));
  3312. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3313. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3314. getF32Constant(DAG, 0x3f324b07));
  3315. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3316. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3317. getF32Constant(DAG, 0x3f7ff8fd));
  3318. SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
  3319. SDValue TwoToFractionalPartOfX =
  3320. DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
  3321. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3322. MVT::f32, TwoToFractionalPartOfX);
  3323. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3324. // For floating-point precision of 18:
  3325. //
  3326. // TwoToFractionalPartOfX =
  3327. // 0.999999982f +
  3328. // (0.693148872f +
  3329. // (0.240227044f +
  3330. // (0.554906021e-1f +
  3331. // (0.961591928e-2f +
  3332. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3333. // error 2.47208000*10^(-7), which is better than 18 bits
  3334. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3335. getF32Constant(DAG, 0x3924b03e));
  3336. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3337. getF32Constant(DAG, 0x3ab24b87));
  3338. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3339. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3340. getF32Constant(DAG, 0x3c1d8c17));
  3341. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3342. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3343. getF32Constant(DAG, 0x3d634a1d));
  3344. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3345. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3346. getF32Constant(DAG, 0x3e75fe14));
  3347. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3348. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3349. getF32Constant(DAG, 0x3f317234));
  3350. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3351. SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3352. getF32Constant(DAG, 0x3f800000));
  3353. SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
  3354. SDValue TwoToFractionalPartOfX =
  3355. DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
  3356. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3357. MVT::f32, TwoToFractionalPartOfX);
  3358. }
  3359. } else {
  3360. // No special expansion.
  3361. result = DAG.getNode(ISD::FPOW, dl,
  3362. getValue(I.getOperand(1)).getValueType(),
  3363. getValue(I.getOperand(1)),
  3364. getValue(I.getOperand(2)));
  3365. }
  3366. setValue(&I, result);
  3367. }
  3368. /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
  3369. /// we want to emit this as a call to a named external function, return the name
  3370. /// otherwise lower it and return null.
  3371. const char *
  3372. SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
  3373. DebugLoc dl = getCurDebugLoc();
  3374. switch (Intrinsic) {
  3375. default:
  3376. // By default, turn this into a target intrinsic node.
  3377. visitTargetIntrinsic(I, Intrinsic);
  3378. return 0;
  3379. case Intrinsic::vastart: visitVAStart(I); return 0;
  3380. case Intrinsic::vaend: visitVAEnd(I); return 0;
  3381. case Intrinsic::vacopy: visitVACopy(I); return 0;
  3382. case Intrinsic::returnaddress:
  3383. setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
  3384. getValue(I.getOperand(1))));
  3385. return 0;
  3386. case Intrinsic::frameaddress:
  3387. setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
  3388. getValue(I.getOperand(1))));
  3389. return 0;
  3390. case Intrinsic::setjmp:
  3391. return "_setjmp"+!TLI.usesUnderscoreSetJmp();
  3392. break;
  3393. case Intrinsic::longjmp:
  3394. return "_longjmp"+!TLI.usesUnderscoreLongJmp();
  3395. break;
  3396. case Intrinsic::memcpy: {
  3397. SDValue Op1 = getValue(I.getOperand(1));
  3398. SDValue Op2 = getValue(I.getOperand(2));
  3399. SDValue Op3 = getValue(I.getOperand(3));
  3400. unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
  3401. DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
  3402. I.getOperand(1), 0, I.getOperand(2), 0));
  3403. return 0;
  3404. }
  3405. case Intrinsic::memset: {
  3406. SDValue Op1 = getValue(I.getOperand(1));
  3407. SDValue Op2 = getValue(I.getOperand(2));
  3408. SDValue Op3 = getValue(I.getOperand(3));
  3409. unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
  3410. DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
  3411. I.getOperand(1), 0));
  3412. return 0;
  3413. }
  3414. case Intrinsic::memmove: {
  3415. SDValue Op1 = getValue(I.getOperand(1));
  3416. SDValue Op2 = getValue(I.getOperand(2));
  3417. SDValue Op3 = getValue(I.getOperand(3));
  3418. unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
  3419. // If the source and destination are known to not be aliases, we can
  3420. // lower memmove as memcpy.
  3421. uint64_t Size = -1ULL;
  3422. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
  3423. Size = C->getZExtValue();
  3424. if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
  3425. AliasAnalysis::NoAlias) {
  3426. DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
  3427. I.getOperand(1), 0, I.getOperand(2), 0));
  3428. return 0;
  3429. }
  3430. DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
  3431. I.getOperand(1), 0, I.getOperand(2), 0));
  3432. return 0;
  3433. }
  3434. case Intrinsic::dbg_stoppoint: {
  3435. DwarfWriter *DW = DAG.getDwarfWriter();
  3436. DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
  3437. if (DW && DW->ValidDebugInfo(SPI.getContext(), Fast)) {
  3438. MachineFunction &MF = DAG.getMachineFunction();
  3439. if (Fast)
  3440. DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
  3441. SPI.getLine(),
  3442. SPI.getColumn(),
  3443. SPI.getContext()));
  3444. DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
  3445. std::string Dir, FN;
  3446. unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
  3447. CU.getFilename(FN));
  3448. unsigned idx = MF.getOrCreateDebugLocID(SrcFile,
  3449. SPI.getLine(), SPI.getColumn());
  3450. setCurDebugLoc(DebugLoc::get(idx));
  3451. }
  3452. return 0;
  3453. }
  3454. case Intrinsic::dbg_region_start: {
  3455. DwarfWriter *DW = DAG.getDwarfWriter();
  3456. DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
  3457. if (DW && DW->ValidDebugInfo(RSI.getContext(), Fast)) {
  3458. unsigned LabelID =
  3459. DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
  3460. DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
  3461. getRoot(), LabelID));
  3462. }
  3463. return 0;
  3464. }
  3465. case Intrinsic::dbg_region_end: {
  3466. DwarfWriter *DW = DAG.getDwarfWriter();
  3467. DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
  3468. if (DW && DW->ValidDebugInfo(REI.getContext(), Fast)) {
  3469. MachineFunction &MF = DAG.getMachineFunction();
  3470. DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
  3471. std::string SPName;
  3472. Subprogram.getLinkageName(SPName);
  3473. if (!SPName.empty()
  3474. && strcmp(SPName.c_str(), MF.getFunction()->getNameStart())) {
  3475. // This is end of inlined function. Debugging information for
  3476. // inlined function is not handled yet (only supported by FastISel).
  3477. if (Fast) {
  3478. unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
  3479. if (ID != 0)
  3480. // Returned ID is 0 if this is unbalanced "end of inlined
  3481. // scope". This could happen if optimizer eats dbg intrinsics
  3482. // or "beginning of inlined scope" is not recoginized due to
  3483. // missing location info. In such cases, do ignore this region.end.
  3484. DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
  3485. getRoot(), ID));
  3486. }
  3487. return 0;
  3488. }
  3489. unsigned LabelID =
  3490. DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
  3491. DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
  3492. getRoot(), LabelID));
  3493. }
  3494. return 0;
  3495. }
  3496. case Intrinsic::dbg_func_start: {
  3497. DwarfWriter *DW = DAG.getDwarfWriter();
  3498. if (!DW) return 0;
  3499. DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
  3500. Value *SP = FSI.getSubprogram();
  3501. if (SP && DW->ValidDebugInfo(SP, Fast)) {
  3502. MachineFunction &MF = DAG.getMachineFunction();
  3503. if (Fast) {
  3504. // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is what
  3505. // (most?) gdb expects.
  3506. DebugLoc PrevLoc = CurDebugLoc;
  3507. DISubprogram Subprogram(cast<GlobalVariable>(SP));
  3508. DICompileUnit CompileUnit = Subprogram.getCompileUnit();
  3509. std::string Dir, FN;
  3510. unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
  3511. CompileUnit.getFilename(FN));
  3512. if (!Subprogram.describes(MF.getFunction())) {
  3513. // This is a beginning of an inlined function.
  3514. // If llvm.dbg.func.start is seen in a new block before any
  3515. // llvm.dbg.stoppoint intrinsic then the location info is unknown.
  3516. // FIXME : Why DebugLoc is reset at the beginning of each block ?
  3517. if (PrevLoc.isUnknown())
  3518. return 0;
  3519. // Record the source line.
  3520. unsigned Line = Subprogram.getLineNumber();
  3521. unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
  3522. setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
  3523. DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
  3524. getRoot(), LabelID));
  3525. DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
  3526. DW->RecordInlinedFnStart(&FSI, Subprogram, LabelID,
  3527. PrevLocTpl.Src,
  3528. PrevLocTpl.Line,
  3529. PrevLocTpl.Col);
  3530. } else {
  3531. // Record the source line.
  3532. unsigned Line = Subprogram.getLineNumber();
  3533. setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
  3534. DW->RecordSourceLine(Line, 0, SrcFile);
  3535. // llvm.dbg.func_start also defines beginning of function scope.
  3536. DW->RecordRegionStart(cast<GlobalVariable>(FSI.getSubprogram()));
  3537. }
  3538. } else {
  3539. DISubprogram Subprogram(cast<GlobalVariable>(SP));
  3540. std::string SPName;
  3541. Subprogram.getLinkageName(SPName);
  3542. if (!SPName.empty()
  3543. && strcmp(SPName.c_str(), MF.getFunction()->getNameStart())) {
  3544. // This is beginning of inlined function. Debugging information for
  3545. // inlined function is not handled yet (only supported by FastISel).
  3546. return 0;
  3547. }
  3548. // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
  3549. // what (most?) gdb expects.
  3550. DICompileUnit CompileUnit = Subprogram.getCompileUnit();
  3551. std::string Dir, FN;
  3552. unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
  3553. CompileUnit.getFilename(FN));
  3554. // Record the source line but does not create a label for the normal
  3555. // function start. It will be emitted at asm emission time. However,
  3556. // create a label if this is a beginning of inlined function.
  3557. unsigned Line = Subprogram.getLineNumber();
  3558. setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
  3559. // FIXME - Start new region because llvm.dbg.func_start also defines
  3560. // beginning of function scope.
  3561. }
  3562. }
  3563. return 0;
  3564. }
  3565. case Intrinsic::dbg_declare: {
  3566. if (Fast) {
  3567. DwarfWriter *DW = DAG.getDwarfWriter();
  3568. DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
  3569. Value *Variable = DI.getVariable();
  3570. if (DW && DW->ValidDebugInfo(Variable, Fast))
  3571. DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
  3572. getValue(DI.getAddress()), getValue(Variable)));
  3573. } else {
  3574. // FIXME: Do something sensible here when we support debug declare.
  3575. }
  3576. return 0;
  3577. }
  3578. case Intrinsic::eh_exception: {
  3579. if (!CurMBB->isLandingPad()) {
  3580. // FIXME: Mark exception register as live in. Hack for PR1508.
  3581. unsigned Reg = TLI.getExceptionAddressRegister();
  3582. if (Reg) CurMBB->addLiveIn(Reg);
  3583. }
  3584. // Insert the EXCEPTIONADDR instruction.
  3585. SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
  3586. SDValue Ops[1];
  3587. Ops[0] = DAG.getRoot();
  3588. SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
  3589. setValue(&I, Op);
  3590. DAG.setRoot(Op.getValue(1));
  3591. return 0;
  3592. }
  3593. case Intrinsic::eh_selector_i32:
  3594. case Intrinsic::eh_selector_i64: {
  3595. MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
  3596. MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
  3597. MVT::i32 : MVT::i64);
  3598. if (MMI) {
  3599. if (CurMBB->isLandingPad())
  3600. AddCatchInfo(I, MMI, CurMBB);
  3601. else {
  3602. #ifndef NDEBUG
  3603. FuncInfo.CatchInfoLost.insert(&I);
  3604. #endif
  3605. // FIXME: Mark exception selector register as live in. Hack for PR1508.
  3606. unsigned Reg = TLI.getExceptionSelectorRegister();
  3607. if (Reg) CurMBB->addLiveIn(Reg);
  3608. }
  3609. // Insert the EHSELECTION instruction.
  3610. SDVTList VTs = DAG.getVTList(VT, MVT::Other);
  3611. SDValue Ops[2];
  3612. Ops[0] = getValue(I.getOperand(1));
  3613. Ops[1] = getRoot();
  3614. SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
  3615. setValue(&I, Op);
  3616. DAG.setRoot(Op.getValue(1));
  3617. } else {
  3618. setValue(&I, DAG.getConstant(0, VT));
  3619. }
  3620. return 0;
  3621. }
  3622. case Intrinsic::eh_typeid_for_i32:
  3623. case Intrinsic::eh_typeid_for_i64: {
  3624. MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
  3625. MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
  3626. MVT::i32 : MVT::i64);
  3627. if (MMI) {
  3628. // Find the type id for the given typeinfo.
  3629. GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
  3630. unsigned TypeID = MMI->getTypeIDFor(GV);
  3631. setValue(&I, DAG.getConstant(TypeID, VT));
  3632. } else {
  3633. // Return something different to eh_selector.
  3634. setValue(&I, DAG.getConstant(1, VT));
  3635. }
  3636. return 0;
  3637. }
  3638. case Intrinsic::eh_return_i32:
  3639. case Intrinsic::eh_return_i64:
  3640. if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
  3641. MMI->setCallsEHReturn(true);
  3642. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
  3643. MVT::Other,
  3644. getControlRoot(),
  3645. getValue(I.getOperand(1)),
  3646. getValue(I.getOperand(2))));
  3647. } else {
  3648. setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
  3649. }
  3650. return 0;
  3651. case Intrinsic::eh_unwind_init:
  3652. if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
  3653. MMI->setCallsUnwindInit(true);
  3654. }
  3655. return 0;
  3656. case Intrinsic::eh_dwarf_cfa: {
  3657. MVT VT = getValue(I.getOperand(1)).getValueType();
  3658. SDValue CfaArg;
  3659. if (VT.bitsGT(TLI.getPointerTy()))
  3660. CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
  3661. TLI.getPointerTy(), getValue(I.getOperand(1)));
  3662. else
  3663. CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
  3664. TLI.getPointerTy(), getValue(I.getOperand(1)));
  3665. SDValue Offset = DAG.getNode(ISD::ADD, dl,
  3666. TLI.getPointerTy(),
  3667. DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
  3668. TLI.getPointerTy()),
  3669. CfaArg);
  3670. setValue(&I, DAG.getNode(ISD::ADD, dl,
  3671. TLI.getPointerTy(),
  3672. DAG.getNode(ISD::FRAMEADDR, dl,
  3673. TLI.getPointerTy(),
  3674. DAG.getConstant(0,
  3675. TLI.getPointerTy())),
  3676. Offset));
  3677. return 0;
  3678. }
  3679. case Intrinsic::convertff:
  3680. case Intrinsic::convertfsi:
  3681. case Intrinsic::convertfui:
  3682. case Intrinsic::convertsif:
  3683. case Intrinsic::convertuif:
  3684. case Intrinsic::convertss:
  3685. case Intrinsic::convertsu:
  3686. case Intrinsic::convertus:
  3687. case Intrinsic::convertuu: {
  3688. ISD::CvtCode Code = ISD::CVT_INVALID;
  3689. switch (Intrinsic) {
  3690. case Intrinsic::convertff: Code = ISD::CVT_FF; break;
  3691. case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
  3692. case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
  3693. case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
  3694. case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
  3695. case Intrinsic::convertss: Code = ISD::CVT_SS; break;
  3696. case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
  3697. case Intrinsic::convertus: Code = ISD::CVT_US; break;
  3698. case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
  3699. }
  3700. MVT DestVT = TLI.getValueType(I.getType());
  3701. Value* Op1 = I.getOperand(1);
  3702. setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
  3703. DAG.getValueType(DestVT),
  3704. DAG.getValueType(getValue(Op1).getValueType()),
  3705. getValue(I.getOperand(2)),
  3706. getValue(I.getOperand(3)),
  3707. Code));
  3708. return 0;
  3709. }
  3710. case Intrinsic::sqrt:
  3711. setValue(&I, DAG.getNode(ISD::FSQRT, dl,
  3712. getValue(I.getOperand(1)).getValueType(),
  3713. getValue(I.getOperand(1))));
  3714. return 0;
  3715. case Intrinsic::powi:
  3716. setValue(&I, DAG.getNode(ISD::FPOWI, dl,
  3717. getValue(I.getOperand(1)).getValueType(),
  3718. getValue(I.getOperand(1)),
  3719. getValue(I.getOperand(2))));
  3720. return 0;
  3721. case Intrinsic::sin:
  3722. setValue(&I, DAG.getNode(ISD::FSIN, dl,
  3723. getValue(I.getOperand(1)).getValueType(),
  3724. getValue(I.getOperand(1))));
  3725. return 0;
  3726. case Intrinsic::cos:
  3727. setValue(&I, DAG.getNode(ISD::FCOS, dl,
  3728. getValue(I.getOperand(1)).getValueType(),
  3729. getValue(I.getOperand(1))));
  3730. return 0;
  3731. case Intrinsic::log:
  3732. visitLog(I);
  3733. return 0;
  3734. case Intrinsic::log2:
  3735. visitLog2(I);
  3736. return 0;
  3737. case Intrinsic::log10:
  3738. visitLog10(I);
  3739. return 0;
  3740. case Intrinsic::exp:
  3741. visitExp(I);
  3742. return 0;
  3743. case Intrinsic::exp2:
  3744. visitExp2(I);
  3745. return 0;
  3746. case Intrinsic::pow:
  3747. visitPow(I);
  3748. return 0;
  3749. case Intrinsic::pcmarker: {
  3750. SDValue Tmp = getValue(I.getOperand(1));
  3751. DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
  3752. return 0;
  3753. }
  3754. case Intrinsic::readcyclecounter: {
  3755. SDValue Op = getRoot();
  3756. SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
  3757. DAG.getVTList(MVT::i64, MVT::Other),
  3758. &Op, 1);
  3759. setValue(&I, Tmp);
  3760. DAG.setRoot(Tmp.getValue(1));
  3761. return 0;
  3762. }
  3763. case Intrinsic::part_select: {
  3764. // Currently not implemented: just abort
  3765. assert(0 && "part_select intrinsic not implemented");
  3766. abort();
  3767. }
  3768. case Intrinsic::part_set: {
  3769. // Currently not implemented: just abort
  3770. assert(0 && "part_set intrinsic not implemented");
  3771. abort();
  3772. }
  3773. case Intrinsic::bswap:
  3774. setValue(&I, DAG.getNode(ISD::BSWAP, dl,
  3775. getValue(I.getOperand(1)).getValueType(),
  3776. getValue(I.getOperand(1))));
  3777. return 0;
  3778. case Intrinsic::cttz: {
  3779. SDValue Arg = getValue(I.getOperand(1));
  3780. MVT Ty = Arg.getValueType();
  3781. SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
  3782. setValue(&I, result);
  3783. return 0;
  3784. }
  3785. case Intrinsic::ctlz: {
  3786. SDValue Arg = getValue(I.getOperand(1));
  3787. MVT Ty = Arg.getValueType();
  3788. SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
  3789. setValue(&I, result);
  3790. return 0;
  3791. }
  3792. case Intrinsic::ctpop: {
  3793. SDValue Arg = getValue(I.getOperand(1));
  3794. MVT Ty = Arg.getValueType();
  3795. SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
  3796. setValue(&I, result);
  3797. return 0;
  3798. }
  3799. case Intrinsic::stacksave: {
  3800. SDValue Op = getRoot();
  3801. SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
  3802. DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
  3803. setValue(&I, Tmp);
  3804. DAG.setRoot(Tmp.getValue(1));
  3805. return 0;
  3806. }
  3807. case Intrinsic::stackrestore: {
  3808. SDValue Tmp = getValue(I.getOperand(1));
  3809. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
  3810. return 0;
  3811. }
  3812. case Intrinsic::stackprotector: {
  3813. // Emit code into the DAG to store the stack guard onto the stack.
  3814. MachineFunction &MF = DAG.getMachineFunction();
  3815. MachineFrameInfo *MFI = MF.getFrameInfo();
  3816. MVT PtrTy = TLI.getPointerTy();
  3817. SDValue Src = getValue(I.getOperand(1)); // The guard's value.
  3818. AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
  3819. int FI = FuncInfo.StaticAllocaMap[Slot];
  3820. MFI->setStackProtectorIndex(FI);
  3821. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  3822. // Store the stack protector onto the stack.
  3823. SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
  3824. PseudoSourceValue::getFixedStack(FI),
  3825. 0, true);
  3826. setValue(&I, Result);
  3827. DAG.setRoot(Result);
  3828. return 0;
  3829. }
  3830. case Intrinsic::var_annotation:
  3831. // Discard annotate attributes
  3832. return 0;
  3833. case Intrinsic::init_trampoline: {
  3834. const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
  3835. SDValue Ops[6];
  3836. Ops[0] = getRoot();
  3837. Ops[1] = getValue(I.getOperand(1));
  3838. Ops[2] = getValue(I.getOperand(2));
  3839. Ops[3] = getValue(I.getOperand(3));
  3840. Ops[4] = DAG.getSrcValue(I.getOperand(1));
  3841. Ops[5] = DAG.getSrcValue(F);
  3842. SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
  3843. DAG.getVTList(TLI.getPointerTy(), MVT::Other),
  3844. Ops, 6);
  3845. setValue(&I, Tmp);
  3846. DAG.setRoot(Tmp.getValue(1));
  3847. return 0;
  3848. }
  3849. case Intrinsic::gcroot:
  3850. if (GFI) {
  3851. Value *Alloca = I.getOperand(1);
  3852. Constant *TypeMap = cast<Constant>(I.getOperand(2));
  3853. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  3854. GFI->addStackRoot(FI->getIndex(), TypeMap);
  3855. }
  3856. return 0;
  3857. case Intrinsic::gcread:
  3858. case Intrinsic::gcwrite:
  3859. assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
  3860. return 0;
  3861. case Intrinsic::flt_rounds: {
  3862. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
  3863. return 0;
  3864. }
  3865. case Intrinsic::trap: {
  3866. DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
  3867. return 0;
  3868. }
  3869. case Intrinsic::uadd_with_overflow:
  3870. return implVisitAluOverflow(I, ISD::UADDO);
  3871. case Intrinsic::sadd_with_overflow:
  3872. return implVisitAluOverflow(I, ISD::SADDO);
  3873. case Intrinsic::usub_with_overflow:
  3874. return implVisitAluOverflow(I, ISD::USUBO);
  3875. case Intrinsic::ssub_with_overflow:
  3876. return implVisitAluOverflow(I, ISD::SSUBO);
  3877. case Intrinsic::umul_with_overflow:
  3878. return implVisitAluOverflow(I, ISD::UMULO);
  3879. case Intrinsic::smul_with_overflow:
  3880. return implVisitAluOverflow(I, ISD::SMULO);
  3881. case Intrinsic::prefetch: {
  3882. SDValue Ops[4];
  3883. Ops[0] = getRoot();
  3884. Ops[1] = getValue(I.getOperand(1));
  3885. Ops[2] = getValue(I.getOperand(2));
  3886. Ops[3] = getValue(I.getOperand(3));
  3887. DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
  3888. return 0;
  3889. }
  3890. case Intrinsic::memory_barrier: {
  3891. SDValue Ops[6];
  3892. Ops[0] = getRoot();
  3893. for (int x = 1; x < 6; ++x)
  3894. Ops[x] = getValue(I.getOperand(x));
  3895. DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
  3896. return 0;
  3897. }
  3898. case Intrinsic::atomic_cmp_swap: {
  3899. SDValue Root = getRoot();
  3900. SDValue L =
  3901. DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
  3902. getValue(I.getOperand(2)).getValueType().getSimpleVT(),
  3903. Root,
  3904. getValue(I.getOperand(1)),
  3905. getValue(I.getOperand(2)),
  3906. getValue(I.getOperand(3)),
  3907. I.getOperand(1));
  3908. setValue(&I, L);
  3909. DAG.setRoot(L.getValue(1));
  3910. return 0;
  3911. }
  3912. case Intrinsic::atomic_load_add:
  3913. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
  3914. case Intrinsic::atomic_load_sub:
  3915. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
  3916. case Intrinsic::atomic_load_or:
  3917. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
  3918. case Intrinsic::atomic_load_xor:
  3919. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
  3920. case Intrinsic::atomic_load_and:
  3921. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
  3922. case Intrinsic::atomic_load_nand:
  3923. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
  3924. case Intrinsic::atomic_load_max:
  3925. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
  3926. case Intrinsic::atomic_load_min:
  3927. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
  3928. case Intrinsic::atomic_load_umin:
  3929. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
  3930. case Intrinsic::atomic_load_umax:
  3931. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
  3932. case Intrinsic::atomic_swap:
  3933. return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
  3934. }
  3935. }
  3936. void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
  3937. bool IsTailCall,
  3938. MachineBasicBlock *LandingPad) {
  3939. const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
  3940. const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
  3941. MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
  3942. unsigned BeginLabel = 0, EndLabel = 0;
  3943. TargetLowering::ArgListTy Args;
  3944. TargetLowering::ArgListEntry Entry;
  3945. Args.reserve(CS.arg_size());
  3946. for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  3947. i != e; ++i) {
  3948. SDValue ArgNode = getValue(*i);
  3949. Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
  3950. unsigned attrInd = i - CS.arg_begin() + 1;
  3951. Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
  3952. Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
  3953. Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
  3954. Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
  3955. Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
  3956. Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
  3957. Entry.Alignment = CS.getParamAlignment(attrInd);
  3958. Args.push_back(Entry);
  3959. }
  3960. if (LandingPad && MMI) {
  3961. // Insert a label before the invoke call to mark the try range. This can be
  3962. // used to detect deletion of the invoke via the MachineModuleInfo.
  3963. BeginLabel = MMI->NextLabelID();
  3964. // Both PendingLoads and PendingExports must be flushed here;
  3965. // this call might not return.
  3966. (void)getRoot();
  3967. DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
  3968. getControlRoot(), BeginLabel));
  3969. }
  3970. std::pair<SDValue,SDValue> Result =
  3971. TLI.LowerCallTo(getRoot(), CS.getType(),
  3972. CS.paramHasAttr(0, Attribute::SExt),
  3973. CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
  3974. CS.paramHasAttr(0, Attribute::InReg),
  3975. CS.getCallingConv(),
  3976. IsTailCall && PerformTailCallOpt,
  3977. Callee, Args, DAG, getCurDebugLoc());
  3978. if (CS.getType() != Type::VoidTy)
  3979. setValue(CS.getInstruction(), Result.first);
  3980. DAG.setRoot(Result.second);
  3981. if (LandingPad && MMI) {
  3982. // Insert a label at the end of the invoke call to mark the try range. This
  3983. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  3984. EndLabel = MMI->NextLabelID();
  3985. DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
  3986. getRoot(), EndLabel));
  3987. // Inform MachineModuleInfo of range.
  3988. MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
  3989. }
  3990. }
  3991. void SelectionDAGLowering::visitCall(CallInst &I) {
  3992. const char *RenameFn = 0;
  3993. if (Function *F = I.getCalledFunction()) {
  3994. if (F->isDeclaration()) {
  3995. const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
  3996. if (II) {
  3997. if (unsigned IID = II->getIntrinsicID(F)) {
  3998. RenameFn = visitIntrinsicCall(I, IID);
  3999. if (!RenameFn)
  4000. return;
  4001. }
  4002. }
  4003. if (unsigned IID = F->getIntrinsicID()) {
  4004. RenameFn = visitIntrinsicCall(I, IID);
  4005. if (!RenameFn)
  4006. return;
  4007. }
  4008. }
  4009. // Check for well-known libc/libm calls. If the function is internal, it
  4010. // can't be a library call.
  4011. unsigned NameLen = F->getNameLen();
  4012. if (!F->hasLocalLinkage() && NameLen) {
  4013. const char *NameStr = F->getNameStart();
  4014. if (NameStr[0] == 'c' &&
  4015. ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
  4016. (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
  4017. if (I.getNumOperands() == 3 && // Basic sanity checks.
  4018. I.getOperand(1)->getType()->isFloatingPoint() &&
  4019. I.getType() == I.getOperand(1)->getType() &&
  4020. I.getType() == I.getOperand(2)->getType()) {
  4021. SDValue LHS = getValue(I.getOperand(1));
  4022. SDValue RHS = getValue(I.getOperand(2));
  4023. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
  4024. LHS.getValueType(), LHS, RHS));
  4025. return;
  4026. }
  4027. } else if (NameStr[0] == 'f' &&
  4028. ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
  4029. (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
  4030. (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
  4031. if (I.getNumOperands() == 2 && // Basic sanity checks.
  4032. I.getOperand(1)->getType()->isFloatingPoint() &&
  4033. I.getType() == I.getOperand(1)->getType()) {
  4034. SDValue Tmp = getValue(I.getOperand(1));
  4035. setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
  4036. Tmp.getValueType(), Tmp));
  4037. return;
  4038. }
  4039. } else if (NameStr[0] == 's' &&
  4040. ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
  4041. (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
  4042. (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
  4043. if (I.getNumOperands() == 2 && // Basic sanity checks.
  4044. I.getOperand(1)->getType()->isFloatingPoint() &&
  4045. I.getType() == I.getOperand(1)->getType()) {
  4046. SDValue Tmp = getValue(I.getOperand(1));
  4047. setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
  4048. Tmp.getValueType(), Tmp));
  4049. return;
  4050. }
  4051. } else if (NameStr[0] == 'c' &&
  4052. ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
  4053. (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
  4054. (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
  4055. if (I.getNumOperands() == 2 && // Basic sanity checks.
  4056. I.getOperand(1)->getType()->isFloatingPoint() &&
  4057. I.getType() == I.getOperand(1)->getType()) {
  4058. SDValue Tmp = getValue(I.getOperand(1));
  4059. setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
  4060. Tmp.getValueType(), Tmp));
  4061. return;
  4062. }
  4063. }
  4064. }
  4065. } else if (isa<InlineAsm>(I.getOperand(0))) {
  4066. visitInlineAsm(&I);
  4067. return;
  4068. }
  4069. SDValue Callee;
  4070. if (!RenameFn)
  4071. Callee = getValue(I.getOperand(0));
  4072. else
  4073. Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
  4074. LowerCallTo(&I, Callee, I.isTailCall());
  4075. }
  4076. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  4077. /// this value and returns the result as a ValueVT value. This uses
  4078. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  4079. /// If the Flag pointer is NULL, no flag is used.
  4080. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
  4081. SDValue &Chain,
  4082. SDValue *Flag) const {
  4083. // Assemble the legal parts into the final values.
  4084. SmallVector<SDValue, 4> Values(ValueVTs.size());
  4085. SmallVector<SDValue, 8> Parts;
  4086. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  4087. // Copy the legal parts from the registers.
  4088. MVT ValueVT = ValueVTs[Value];
  4089. unsigned NumRegs = TLI->getNumRegisters(ValueVT);
  4090. MVT RegisterVT = RegVTs[Value];
  4091. Parts.resize(NumRegs);
  4092. for (unsigned i = 0; i != NumRegs; ++i) {
  4093. SDValue P;
  4094. if (Flag == 0)
  4095. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  4096. else {
  4097. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  4098. *Flag = P.getValue(2);
  4099. }
  4100. Chain = P.getValue(1);
  4101. // If the source register was virtual and if we know something about it,
  4102. // add an assert node.
  4103. if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
  4104. RegisterVT.isInteger() && !RegisterVT.isVector()) {
  4105. unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
  4106. FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
  4107. if (FLI.LiveOutRegInfo.size() > SlotNo) {
  4108. FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
  4109. unsigned RegSize = RegisterVT.getSizeInBits();
  4110. unsigned NumSignBits = LOI.NumSignBits;
  4111. unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
  4112. // FIXME: We capture more information than the dag can represent. For
  4113. // now, just use the tightest assertzext/assertsext possible.
  4114. bool isSExt = true;
  4115. MVT FromVT(MVT::Other);
  4116. if (NumSignBits == RegSize)
  4117. isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
  4118. else if (NumZeroBits >= RegSize-1)
  4119. isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
  4120. else if (NumSignBits > RegSize-8)
  4121. isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
  4122. else if (NumZeroBits >= RegSize-8)
  4123. isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
  4124. else if (NumSignBits > RegSize-16)
  4125. isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
  4126. else if (NumZeroBits >= RegSize-16)
  4127. isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
  4128. else if (NumSignBits > RegSize-32)
  4129. isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
  4130. else if (NumZeroBits >= RegSize-32)
  4131. isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
  4132. if (FromVT != MVT::Other) {
  4133. P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  4134. RegisterVT, P, DAG.getValueType(FromVT));
  4135. }
  4136. }
  4137. }
  4138. Parts[i] = P;
  4139. }
  4140. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  4141. NumRegs, RegisterVT, ValueVT);
  4142. Part += NumRegs;
  4143. Parts.clear();
  4144. }
  4145. return DAG.getNode(ISD::MERGE_VALUES, dl,
  4146. DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
  4147. &Values[0], ValueVTs.size());
  4148. }
  4149. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  4150. /// specified value into the registers specified by this object. This uses
  4151. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  4152. /// If the Flag pointer is NULL, no flag is used.
  4153. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
  4154. SDValue &Chain, SDValue *Flag) const {
  4155. // Get the list of the values's legal parts.
  4156. unsigned NumRegs = Regs.size();
  4157. SmallVector<SDValue, 8> Parts(NumRegs);
  4158. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  4159. MVT ValueVT = ValueVTs[Value];
  4160. unsigned NumParts = TLI->getNumRegisters(ValueVT);
  4161. MVT RegisterVT = RegVTs[Value];
  4162. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  4163. &Parts[Part], NumParts, RegisterVT);
  4164. Part += NumParts;
  4165. }
  4166. // Copy the parts into the registers.
  4167. SmallVector<SDValue, 8> Chains(NumRegs);
  4168. for (unsigned i = 0; i != NumRegs; ++i) {
  4169. SDValue Part;
  4170. if (Flag == 0)
  4171. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  4172. else {
  4173. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  4174. *Flag = Part.getValue(1);
  4175. }
  4176. Chains[i] = Part.getValue(0);
  4177. }
  4178. if (NumRegs == 1 || Flag)
  4179. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  4180. // flagged to it. That is the CopyToReg nodes and the user are considered
  4181. // a single scheduling unit. If we create a TokenFactor and return it as
  4182. // chain, then the TokenFactor is both a predecessor (operand) of the
  4183. // user as well as a successor (the TF operands are flagged to the user).
  4184. // c1, f1 = CopyToReg
  4185. // c2, f2 = CopyToReg
  4186. // c3 = TokenFactor c1, c2
  4187. // ...
  4188. // = op c3, ..., f2
  4189. Chain = Chains[NumRegs-1];
  4190. else
  4191. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
  4192. }
  4193. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  4194. /// operand list. This adds the code marker and includes the number of
  4195. /// values added into it.
  4196. void RegsForValue::AddInlineAsmOperands(unsigned Code,
  4197. bool HasMatching,unsigned MatchingIdx,
  4198. SelectionDAG &DAG,
  4199. std::vector<SDValue> &Ops) const {
  4200. MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
  4201. assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
  4202. unsigned Flag = Code | (Regs.size() << 3);
  4203. if (HasMatching)
  4204. Flag |= 0x80000000 | (MatchingIdx << 16);
  4205. Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
  4206. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  4207. unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
  4208. MVT RegisterVT = RegVTs[Value];
  4209. for (unsigned i = 0; i != NumRegs; ++i) {
  4210. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  4211. Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
  4212. }
  4213. }
  4214. }
  4215. /// isAllocatableRegister - If the specified register is safe to allocate,
  4216. /// i.e. it isn't a stack pointer or some other special register, return the
  4217. /// register class for the register. Otherwise, return null.
  4218. static const TargetRegisterClass *
  4219. isAllocatableRegister(unsigned Reg, MachineFunction &MF,
  4220. const TargetLowering &TLI,
  4221. const TargetRegisterInfo *TRI) {
  4222. MVT FoundVT = MVT::Other;
  4223. const TargetRegisterClass *FoundRC = 0;
  4224. for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
  4225. E = TRI->regclass_end(); RCI != E; ++RCI) {
  4226. MVT ThisVT = MVT::Other;
  4227. const TargetRegisterClass *RC = *RCI;
  4228. // If none of the the value types for this register class are valid, we
  4229. // can't use it. For example, 64-bit reg classes on 32-bit targets.
  4230. for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
  4231. I != E; ++I) {
  4232. if (TLI.isTypeLegal(*I)) {
  4233. // If we have already found this register in a different register class,
  4234. // choose the one with the largest VT specified. For example, on
  4235. // PowerPC, we favor f64 register classes over f32.
  4236. if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
  4237. ThisVT = *I;
  4238. break;
  4239. }
  4240. }
  4241. }
  4242. if (ThisVT == MVT::Other) continue;
  4243. // NOTE: This isn't ideal. In particular, this might allocate the
  4244. // frame pointer in functions that need it (due to them not being taken
  4245. // out of allocation, because a variable sized allocation hasn't been seen
  4246. // yet). This is a slight code pessimization, but should still work.
  4247. for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
  4248. E = RC->allocation_order_end(MF); I != E; ++I)
  4249. if (*I == Reg) {
  4250. // We found a matching register class. Keep looking at others in case
  4251. // we find one with larger registers that this physreg is also in.
  4252. FoundRC = RC;
  4253. FoundVT = ThisVT;
  4254. break;
  4255. }
  4256. }
  4257. return FoundRC;
  4258. }
  4259. namespace llvm {
  4260. /// AsmOperandInfo - This contains information for each constraint that we are
  4261. /// lowering.
  4262. class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
  4263. public TargetLowering::AsmOperandInfo {
  4264. public:
  4265. /// CallOperand - If this is the result output operand or a clobber
  4266. /// this is null, otherwise it is the incoming operand to the CallInst.
  4267. /// This gets modified as the asm is processed.
  4268. SDValue CallOperand;
  4269. /// AssignedRegs - If this is a register or register class operand, this
  4270. /// contains the set of register corresponding to the operand.
  4271. RegsForValue AssignedRegs;
  4272. explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
  4273. : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
  4274. }
  4275. /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
  4276. /// busy in OutputRegs/InputRegs.
  4277. void MarkAllocatedRegs(bool isOutReg, bool isInReg,
  4278. std::set<unsigned> &OutputRegs,
  4279. std::set<unsigned> &InputRegs,
  4280. const TargetRegisterInfo &TRI) const {
  4281. if (isOutReg) {
  4282. for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
  4283. MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
  4284. }
  4285. if (isInReg) {
  4286. for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
  4287. MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
  4288. }
  4289. }
  4290. /// getCallOperandValMVT - Return the MVT of the Value* that this operand
  4291. /// corresponds to. If there is no Value* for this operand, it returns
  4292. /// MVT::Other.
  4293. MVT getCallOperandValMVT(const TargetLowering &TLI,
  4294. const TargetData *TD) const {
  4295. if (CallOperandVal == 0) return MVT::Other;
  4296. if (isa<BasicBlock>(CallOperandVal))
  4297. return TLI.getPointerTy();
  4298. const llvm::Type *OpTy = CallOperandVal->getType();
  4299. // If this is an indirect operand, the operand is a pointer to the
  4300. // accessed type.
  4301. if (isIndirect)
  4302. OpTy = cast<PointerType>(OpTy)->getElementType();
  4303. // If OpTy is not a single value, it may be a struct/union that we
  4304. // can tile with integers.
  4305. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  4306. unsigned BitSize = TD->getTypeSizeInBits(OpTy);
  4307. switch (BitSize) {
  4308. default: break;
  4309. case 1:
  4310. case 8:
  4311. case 16:
  4312. case 32:
  4313. case 64:
  4314. case 128:
  4315. OpTy = IntegerType::get(BitSize);
  4316. break;
  4317. }
  4318. }
  4319. return TLI.getValueType(OpTy, true);
  4320. }
  4321. private:
  4322. /// MarkRegAndAliases - Mark the specified register and all aliases in the
  4323. /// specified set.
  4324. static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
  4325. const TargetRegisterInfo &TRI) {
  4326. assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
  4327. Regs.insert(Reg);
  4328. if (const unsigned *Aliases = TRI.getAliasSet(Reg))
  4329. for (; *Aliases; ++Aliases)
  4330. Regs.insert(*Aliases);
  4331. }
  4332. };
  4333. } // end llvm namespace.
  4334. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  4335. /// specified operand. We prefer to assign virtual registers, to allow the
  4336. /// register allocator handle the assignment process. However, if the asm uses
  4337. /// features that we can't model on machineinstrs, we have SDISel do the
  4338. /// allocation. This produces generally horrible, but correct, code.
  4339. ///
  4340. /// OpInfo describes the operand.
  4341. /// Input and OutputRegs are the set of already allocated physical registers.
  4342. ///
  4343. void SelectionDAGLowering::
  4344. GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
  4345. std::set<unsigned> &OutputRegs,
  4346. std::set<unsigned> &InputRegs) {
  4347. // Compute whether this value requires an input register, an output register,
  4348. // or both.
  4349. bool isOutReg = false;
  4350. bool isInReg = false;
  4351. switch (OpInfo.Type) {
  4352. case InlineAsm::isOutput:
  4353. isOutReg = true;
  4354. // If there is an input constraint that matches this, we need to reserve
  4355. // the input register so no other inputs allocate to it.
  4356. isInReg = OpInfo.hasMatchingInput();
  4357. break;
  4358. case InlineAsm::isInput:
  4359. isInReg = true;
  4360. isOutReg = false;
  4361. break;
  4362. case InlineAsm::isClobber:
  4363. isOutReg = true;
  4364. isInReg = true;
  4365. break;
  4366. }
  4367. MachineFunction &MF = DAG.getMachineFunction();
  4368. SmallVector<unsigned, 4> Regs;
  4369. // If this is a constraint for a single physreg, or a constraint for a
  4370. // register class, find it.
  4371. std::pair<unsigned, const TargetRegisterClass*> PhysReg =
  4372. TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
  4373. OpInfo.ConstraintVT);
  4374. unsigned NumRegs = 1;
  4375. if (OpInfo.ConstraintVT != MVT::Other) {
  4376. // If this is a FP input in an integer register (or visa versa) insert a bit
  4377. // cast of the input value. More generally, handle any case where the input
  4378. // value disagrees with the register class we plan to stick this in.
  4379. if (OpInfo.Type == InlineAsm::isInput &&
  4380. PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
  4381. // Try to convert to the first MVT that the reg class contains. If the
  4382. // types are identical size, use a bitcast to convert (e.g. two differing
  4383. // vector types).
  4384. MVT RegVT = *PhysReg.second->vt_begin();
  4385. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  4386. OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
  4387. RegVT, OpInfo.CallOperand);
  4388. OpInfo.ConstraintVT = RegVT;
  4389. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  4390. // If the input is a FP value and we want it in FP registers, do a
  4391. // bitcast to the corresponding integer type. This turns an f64 value
  4392. // into i64, which can be passed with two i32 values on a 32-bit
  4393. // machine.
  4394. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  4395. OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
  4396. RegVT, OpInfo.CallOperand);
  4397. OpInfo.ConstraintVT = RegVT;
  4398. }
  4399. }
  4400. NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
  4401. }
  4402. MVT RegVT;
  4403. MVT ValueVT = OpInfo.ConstraintVT;
  4404. // If this is a constraint for a specific physical register, like {r17},
  4405. // assign it now.
  4406. if (unsigned AssignedReg = PhysReg.first) {
  4407. const TargetRegisterClass *RC = PhysReg.second;
  4408. if (OpInfo.ConstraintVT == MVT::Other)
  4409. ValueVT = *RC->vt_begin();
  4410. // Get the actual register value type. This is important, because the user
  4411. // may have asked for (e.g.) the AX register in i32 type. We need to
  4412. // remember that AX is actually i16 to get the right extension.
  4413. RegVT = *RC->vt_begin();
  4414. // This is a explicit reference to a physical register.
  4415. Regs.push_back(AssignedReg);
  4416. // If this is an expanded reference, add the rest of the regs to Regs.
  4417. if (NumRegs != 1) {
  4418. TargetRegisterClass::iterator I = RC->begin();
  4419. for (; *I != AssignedReg; ++I)
  4420. assert(I != RC->end() && "Didn't find reg!");
  4421. // Already added the first reg.
  4422. --NumRegs; ++I;
  4423. for (; NumRegs; --NumRegs, ++I) {
  4424. assert(I != RC->end() && "Ran out of registers to allocate!");
  4425. Regs.push_back(*I);
  4426. }
  4427. }
  4428. OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
  4429. const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
  4430. OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
  4431. return;
  4432. }
  4433. // Otherwise, if this was a reference to an LLVM register class, create vregs
  4434. // for this reference.
  4435. if (const TargetRegisterClass *RC = PhysReg.second) {
  4436. RegVT = *RC->vt_begin();
  4437. if (OpInfo.ConstraintVT == MVT::Other)
  4438. ValueVT = RegVT;
  4439. // Create the appropriate number of virtual registers.
  4440. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4441. for (; NumRegs; --NumRegs)
  4442. Regs.push_back(RegInfo.createVirtualRegister(RC));
  4443. OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
  4444. return;
  4445. }
  4446. // This is a reference to a register class that doesn't directly correspond
  4447. // to an LLVM register class. Allocate NumRegs consecutive, available,
  4448. // registers from the class.
  4449. std::vector<unsigned> RegClassRegs
  4450. = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
  4451. OpInfo.ConstraintVT);
  4452. const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
  4453. unsigned NumAllocated = 0;
  4454. for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
  4455. unsigned Reg = RegClassRegs[i];
  4456. // See if this register is available.
  4457. if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
  4458. (isInReg && InputRegs.count(Reg))) { // Already used.
  4459. // Make sure we find consecutive registers.
  4460. NumAllocated = 0;
  4461. continue;
  4462. }
  4463. // Check to see if this register is allocatable (i.e. don't give out the
  4464. // stack pointer).
  4465. const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
  4466. if (!RC) { // Couldn't allocate this register.
  4467. // Reset NumAllocated to make sure we return consecutive registers.
  4468. NumAllocated = 0;
  4469. continue;
  4470. }
  4471. // Okay, this register is good, we can use it.
  4472. ++NumAllocated;
  4473. // If we allocated enough consecutive registers, succeed.
  4474. if (NumAllocated == NumRegs) {
  4475. unsigned RegStart = (i-NumAllocated)+1;
  4476. unsigned RegEnd = i+1;
  4477. // Mark all of the allocated registers used.
  4478. for (unsigned i = RegStart; i != RegEnd; ++i)
  4479. Regs.push_back(RegClassRegs[i]);
  4480. OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
  4481. OpInfo.ConstraintVT);
  4482. OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
  4483. return;
  4484. }
  4485. }
  4486. // Otherwise, we couldn't allocate enough registers for this.
  4487. }
  4488. /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
  4489. /// processed uses a memory 'm' constraint.
  4490. static bool
  4491. hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
  4492. const TargetLowering &TLI) {
  4493. for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
  4494. InlineAsm::ConstraintInfo &CI = CInfos[i];
  4495. for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
  4496. TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
  4497. if (CType == TargetLowering::C_Memory)
  4498. return true;
  4499. }
  4500. }
  4501. return false;
  4502. }
  4503. /// visitInlineAsm - Handle a call to an InlineAsm object.
  4504. ///
  4505. void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
  4506. InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  4507. /// ConstraintOperands - Information about all of the constraints.
  4508. std::vector<SDISelAsmOperandInfo> ConstraintOperands;
  4509. // We won't need to flush pending loads if this asm doesn't touch
  4510. // memory and is nonvolatile.
  4511. SDValue Chain = IA->hasSideEffects() ? getRoot() : DAG.getRoot();
  4512. SDValue Flag;
  4513. std::set<unsigned> OutputRegs, InputRegs;
  4514. // Do a prepass over the constraints, canonicalizing them, and building up the
  4515. // ConstraintOperands list.
  4516. std::vector<InlineAsm::ConstraintInfo>
  4517. ConstraintInfos = IA->ParseConstraints();
  4518. bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
  4519. // Flush pending loads if this touches memory (includes clobbering it).
  4520. // It's possible this is overly conservative.
  4521. if (hasMemory)
  4522. Chain = getRoot();
  4523. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  4524. unsigned ResNo = 0; // ResNo - The result number of the next output.
  4525. for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
  4526. ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
  4527. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  4528. MVT OpVT = MVT::Other;
  4529. // Compute the value type for each operand.
  4530. switch (OpInfo.Type) {
  4531. case InlineAsm::isOutput:
  4532. // Indirect outputs just consume an argument.
  4533. if (OpInfo.isIndirect) {
  4534. OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
  4535. break;
  4536. }
  4537. // The return value of the call is this value. As such, there is no
  4538. // corresponding argument.
  4539. assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
  4540. if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
  4541. OpVT = TLI.getValueType(STy->getElementType(ResNo));
  4542. } else {
  4543. assert(ResNo == 0 && "Asm only has one result!");
  4544. OpVT = TLI.getValueType(CS.getType());
  4545. }
  4546. ++ResNo;
  4547. break;
  4548. case InlineAsm::isInput:
  4549. OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
  4550. break;
  4551. case InlineAsm::isClobber:
  4552. // Nothing to do.
  4553. break;
  4554. }
  4555. // If this is an input or an indirect output, process the call argument.
  4556. // BasicBlocks are labels, currently appearing only in asm's.
  4557. if (OpInfo.CallOperandVal) {
  4558. if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  4559. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  4560. } else {
  4561. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  4562. }
  4563. OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
  4564. }
  4565. OpInfo.ConstraintVT = OpVT;
  4566. }
  4567. // Second pass over the constraints: compute which constraint option to use
  4568. // and assign registers to constraints that want a specific physreg.
  4569. for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
  4570. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  4571. // If this is an output operand with a matching input operand, look up the
  4572. // matching input. If their types mismatch, e.g. one is an integer, the
  4573. // other is floating point, or their sizes are different, flag it as an
  4574. // error.
  4575. if (OpInfo.hasMatchingInput()) {
  4576. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  4577. if (OpInfo.ConstraintVT != Input.ConstraintVT) {
  4578. if ((OpInfo.ConstraintVT.isInteger() !=
  4579. Input.ConstraintVT.isInteger()) ||
  4580. (OpInfo.ConstraintVT.getSizeInBits() !=
  4581. Input.ConstraintVT.getSizeInBits())) {
  4582. cerr << "llvm: error: Unsupported asm: input constraint with a "
  4583. << "matching output constraint of incompatible type!\n";
  4584. exit(1);
  4585. }
  4586. Input.ConstraintVT = OpInfo.ConstraintVT;
  4587. }
  4588. }
  4589. // Compute the constraint code and ConstraintType to use.
  4590. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
  4591. // If this is a memory input, and if the operand is not indirect, do what we
  4592. // need to to provide an address for the memory input.
  4593. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  4594. !OpInfo.isIndirect) {
  4595. assert(OpInfo.Type == InlineAsm::isInput &&
  4596. "Can only indirectify direct input operands!");
  4597. // Memory operands really want the address of the value. If we don't have
  4598. // an indirect input, put it in the constpool if we can, otherwise spill
  4599. // it to a stack slot.
  4600. // If the operand is a float, integer, or vector constant, spill to a
  4601. // constant pool entry to get its address.
  4602. Value *OpVal = OpInfo.CallOperandVal;
  4603. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  4604. isa<ConstantVector>(OpVal)) {
  4605. OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
  4606. TLI.getPointerTy());
  4607. } else {
  4608. // Otherwise, create a stack slot and emit a store to it before the
  4609. // asm.
  4610. const Type *Ty = OpVal->getType();
  4611. uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
  4612. unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
  4613. MachineFunction &MF = DAG.getMachineFunction();
  4614. int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
  4615. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
  4616. Chain = DAG.getStore(Chain, getCurDebugLoc(),
  4617. OpInfo.CallOperand, StackSlot, NULL, 0);
  4618. OpInfo.CallOperand = StackSlot;
  4619. }
  4620. // There is no longer a Value* corresponding to this operand.
  4621. OpInfo.CallOperandVal = 0;
  4622. // It is now an indirect operand.
  4623. OpInfo.isIndirect = true;
  4624. }
  4625. // If this constraint is for a specific register, allocate it before
  4626. // anything else.
  4627. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  4628. GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
  4629. }
  4630. ConstraintInfos.clear();
  4631. // Second pass - Loop over all of the operands, assigning virtual or physregs
  4632. // to register class operands.
  4633. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  4634. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  4635. // C_Register operands have already been allocated, Other/Memory don't need
  4636. // to be.
  4637. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  4638. GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
  4639. }
  4640. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  4641. std::vector<SDValue> AsmNodeOperands;
  4642. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  4643. AsmNodeOperands.push_back(
  4644. DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
  4645. // Loop over all of the inputs, copying the operand values into the
  4646. // appropriate registers and processing the output regs.
  4647. RegsForValue RetValRegs;
  4648. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  4649. std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
  4650. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  4651. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  4652. switch (OpInfo.Type) {
  4653. case InlineAsm::isOutput: {
  4654. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  4655. OpInfo.ConstraintType != TargetLowering::C_Register) {
  4656. // Memory output, or 'other' output (e.g. 'X' constraint).
  4657. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  4658. // Add information to the INLINEASM node to know about this output.
  4659. unsigned ResOpType = 4/*MEM*/ | (1<<3);
  4660. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  4661. TLI.getPointerTy()));
  4662. AsmNodeOperands.push_back(OpInfo.CallOperand);
  4663. break;
  4664. }
  4665. // Otherwise, this is a register or register class output.
  4666. // Copy the output from the appropriate register. Find a register that
  4667. // we can use.
  4668. if (OpInfo.AssignedRegs.Regs.empty()) {
  4669. cerr << "llvm: error: Couldn't allocate output reg for constraint '"
  4670. << OpInfo.ConstraintCode << "'!\n";
  4671. exit(1);
  4672. }
  4673. // If this is an indirect operand, store through the pointer after the
  4674. // asm.
  4675. if (OpInfo.isIndirect) {
  4676. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  4677. OpInfo.CallOperandVal));
  4678. } else {
  4679. // This is the result value of the call.
  4680. assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
  4681. // Concatenate this output onto the outputs list.
  4682. RetValRegs.append(OpInfo.AssignedRegs);
  4683. }
  4684. // Add information to the INLINEASM node to know that this register is
  4685. // set.
  4686. OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
  4687. 6 /* EARLYCLOBBER REGDEF */ :
  4688. 2 /* REGDEF */ ,
  4689. false,
  4690. 0,
  4691. DAG, AsmNodeOperands);
  4692. break;
  4693. }
  4694. case InlineAsm::isInput: {
  4695. SDValue InOperandVal = OpInfo.CallOperand;
  4696. if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
  4697. // If this is required to match an output register we have already set,
  4698. // just use its register.
  4699. unsigned OperandNo = OpInfo.getMatchedOperand();
  4700. // Scan until we find the definition we already emitted of this operand.
  4701. // When we find it, create a RegsForValue operand.
  4702. unsigned CurOp = 2; // The first operand.
  4703. for (; OperandNo; --OperandNo) {
  4704. // Advance to the next operand.
  4705. unsigned OpFlag =
  4706. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  4707. assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
  4708. (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
  4709. (OpFlag & 7) == 4 /*MEM*/) &&
  4710. "Skipped past definitions?");
  4711. CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
  4712. }
  4713. unsigned OpFlag =
  4714. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  4715. if ((OpFlag & 7) == 2 /*REGDEF*/
  4716. || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
  4717. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  4718. RegsForValue MatchedRegs;
  4719. MatchedRegs.TLI = &TLI;
  4720. MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
  4721. MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
  4722. MatchedRegs.RegVTs.push_back(RegVT);
  4723. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  4724. for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
  4725. i != e; ++i)
  4726. MatchedRegs.Regs.
  4727. push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
  4728. // Use the produced MatchedRegs object to
  4729. MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
  4730. Chain, &Flag);
  4731. MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
  4732. true, OpInfo.getMatchedOperand(),
  4733. DAG, AsmNodeOperands);
  4734. break;
  4735. } else {
  4736. assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
  4737. assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
  4738. "Unexpected number of operands");
  4739. // Add information to the INLINEASM node to know about this input.
  4740. // See InlineAsm.h isUseOperandTiedToDef.
  4741. OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
  4742. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
  4743. TLI.getPointerTy()));
  4744. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  4745. break;
  4746. }
  4747. }
  4748. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  4749. assert(!OpInfo.isIndirect &&
  4750. "Don't know how to handle indirect other inputs yet!");
  4751. std::vector<SDValue> Ops;
  4752. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
  4753. hasMemory, Ops, DAG);
  4754. if (Ops.empty()) {
  4755. cerr << "llvm: error: Invalid operand for inline asm constraint '"
  4756. << OpInfo.ConstraintCode << "'!\n";
  4757. exit(1);
  4758. }
  4759. // Add information to the INLINEASM node to know about this input.
  4760. unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
  4761. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  4762. TLI.getPointerTy()));
  4763. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  4764. break;
  4765. } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  4766. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  4767. assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
  4768. "Memory operands expect pointer values");
  4769. // Add information to the INLINEASM node to know about this input.
  4770. unsigned ResOpType = 4/*MEM*/ | (1<<3);
  4771. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  4772. TLI.getPointerTy()));
  4773. AsmNodeOperands.push_back(InOperandVal);
  4774. break;
  4775. }
  4776. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  4777. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  4778. "Unknown constraint type!");
  4779. assert(!OpInfo.isIndirect &&
  4780. "Don't know how to handle indirect register inputs yet!");
  4781. // Copy the input into the appropriate registers.
  4782. if (OpInfo.AssignedRegs.Regs.empty()) {
  4783. cerr << "llvm: error: Couldn't allocate output reg for constraint '"
  4784. << OpInfo.ConstraintCode << "'!\n";
  4785. exit(1);
  4786. }
  4787. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
  4788. Chain, &Flag);
  4789. OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
  4790. DAG, AsmNodeOperands);
  4791. break;
  4792. }
  4793. case InlineAsm::isClobber: {
  4794. // Add the clobbered value to the operand list, so that the register
  4795. // allocator is aware that the physreg got clobbered.
  4796. if (!OpInfo.AssignedRegs.Regs.empty())
  4797. OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
  4798. false, 0, DAG,AsmNodeOperands);
  4799. break;
  4800. }
  4801. }
  4802. }
  4803. // Finish up input operands.
  4804. AsmNodeOperands[0] = Chain;
  4805. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  4806. Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
  4807. DAG.getVTList(MVT::Other, MVT::Flag),
  4808. &AsmNodeOperands[0], AsmNodeOperands.size());
  4809. Flag = Chain.getValue(1);
  4810. // If this asm returns a register value, copy the result from that register
  4811. // and set it as the value of the call.
  4812. if (!RetValRegs.Regs.empty()) {
  4813. SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
  4814. Chain, &Flag);
  4815. // FIXME: Why don't we do this for inline asms with MRVs?
  4816. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  4817. MVT ResultType = TLI.getValueType(CS.getType());
  4818. // If any of the results of the inline asm is a vector, it may have the
  4819. // wrong width/num elts. This can happen for register classes that can
  4820. // contain multiple different value types. The preg or vreg allocated may
  4821. // not have the same VT as was expected. Convert it to the right type
  4822. // with bit_convert.
  4823. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  4824. Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
  4825. ResultType, Val);
  4826. } else if (ResultType != Val.getValueType() &&
  4827. ResultType.isInteger() && Val.getValueType().isInteger()) {
  4828. // If a result value was tied to an input value, the computed result may
  4829. // have a wider width than the expected result. Extract the relevant
  4830. // portion.
  4831. Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
  4832. }
  4833. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  4834. }
  4835. setValue(CS.getInstruction(), Val);
  4836. // Don't need to use this as a chain in this case.
  4837. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  4838. return;
  4839. }
  4840. std::vector<std::pair<SDValue, Value*> > StoresToEmit;
  4841. // Process indirect outputs, first output all of the flagged copies out of
  4842. // physregs.
  4843. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  4844. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  4845. Value *Ptr = IndirectStoresToEmit[i].second;
  4846. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
  4847. Chain, &Flag);
  4848. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  4849. }
  4850. // Emit the non-flagged stores from the physregs.
  4851. SmallVector<SDValue, 8> OutChains;
  4852. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
  4853. OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
  4854. StoresToEmit[i].first,
  4855. getValue(StoresToEmit[i].second),
  4856. StoresToEmit[i].second, 0));
  4857. if (!OutChains.empty())
  4858. Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
  4859. &OutChains[0], OutChains.size());
  4860. DAG.setRoot(Chain);
  4861. }
  4862. void SelectionDAGLowering::visitMalloc(MallocInst &I) {
  4863. SDValue Src = getValue(I.getOperand(0));
  4864. // Scale up by the type size in the original i32 type width. Various
  4865. // mid-level optimizers may make assumptions about demanded bits etc from the
  4866. // i32-ness of the optimizer: we do not want to promote to i64 and then
  4867. // multiply on 64-bit targets.
  4868. // FIXME: Malloc inst should go away: PR715.
  4869. uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
  4870. if (ElementSize != 1)
  4871. Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
  4872. Src, DAG.getConstant(ElementSize, Src.getValueType()));
  4873. MVT IntPtr = TLI.getPointerTy();
  4874. if (IntPtr.bitsLT(Src.getValueType()))
  4875. Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
  4876. else if (IntPtr.bitsGT(Src.getValueType()))
  4877. Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
  4878. TargetLowering::ArgListTy Args;
  4879. TargetLowering::ArgListEntry Entry;
  4880. Entry.Node = Src;
  4881. Entry.Ty = TLI.getTargetData()->getIntPtrType();
  4882. Args.push_back(Entry);
  4883. std::pair<SDValue,SDValue> Result =
  4884. TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
  4885. CallingConv::C, PerformTailCallOpt,
  4886. DAG.getExternalSymbol("malloc", IntPtr),
  4887. Args, DAG, getCurDebugLoc());
  4888. setValue(&I, Result.first); // Pointers always fit in registers
  4889. DAG.setRoot(Result.second);
  4890. }
  4891. void SelectionDAGLowering::visitFree(FreeInst &I) {
  4892. TargetLowering::ArgListTy Args;
  4893. TargetLowering::ArgListEntry Entry;
  4894. Entry.Node = getValue(I.getOperand(0));
  4895. Entry.Ty = TLI.getTargetData()->getIntPtrType();
  4896. Args.push_back(Entry);
  4897. MVT IntPtr = TLI.getPointerTy();
  4898. std::pair<SDValue,SDValue> Result =
  4899. TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
  4900. CallingConv::C, PerformTailCallOpt,
  4901. DAG.getExternalSymbol("free", IntPtr), Args, DAG,
  4902. getCurDebugLoc());
  4903. DAG.setRoot(Result.second);
  4904. }
  4905. void SelectionDAGLowering::visitVAStart(CallInst &I) {
  4906. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
  4907. MVT::Other, getRoot(),
  4908. getValue(I.getOperand(1)),
  4909. DAG.getSrcValue(I.getOperand(1))));
  4910. }
  4911. void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
  4912. SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
  4913. getRoot(), getValue(I.getOperand(0)),
  4914. DAG.getSrcValue(I.getOperand(0)));
  4915. setValue(&I, V);
  4916. DAG.setRoot(V.getValue(1));
  4917. }
  4918. void SelectionDAGLowering::visitVAEnd(CallInst &I) {
  4919. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
  4920. MVT::Other, getRoot(),
  4921. getValue(I.getOperand(1)),
  4922. DAG.getSrcValue(I.getOperand(1))));
  4923. }
  4924. void SelectionDAGLowering::visitVACopy(CallInst &I) {
  4925. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
  4926. MVT::Other, getRoot(),
  4927. getValue(I.getOperand(1)),
  4928. getValue(I.getOperand(2)),
  4929. DAG.getSrcValue(I.getOperand(1)),
  4930. DAG.getSrcValue(I.getOperand(2))));
  4931. }
  4932. /// TargetLowering::LowerArguments - This is the default LowerArguments
  4933. /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
  4934. /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
  4935. /// integrated into SDISel.
  4936. void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
  4937. SmallVectorImpl<SDValue> &ArgValues,
  4938. DebugLoc dl) {
  4939. // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
  4940. SmallVector<SDValue, 3+16> Ops;
  4941. Ops.push_back(DAG.getRoot());
  4942. Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
  4943. Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
  4944. // Add one result value for each formal argument.
  4945. SmallVector<MVT, 16> RetVals;
  4946. unsigned j = 1;
  4947. for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
  4948. I != E; ++I, ++j) {
  4949. SmallVector<MVT, 4> ValueVTs;
  4950. ComputeValueVTs(*this, I->getType(), ValueVTs);
  4951. for (unsigned Value = 0, NumValues = ValueVTs.size();
  4952. Value != NumValues; ++Value) {
  4953. MVT VT = ValueVTs[Value];
  4954. const Type *ArgTy = VT.getTypeForMVT();
  4955. ISD::ArgFlagsTy Flags;
  4956. unsigned OriginalAlignment =
  4957. getTargetData()->getABITypeAlignment(ArgTy);
  4958. if (F.paramHasAttr(j, Attribute::ZExt))
  4959. Flags.setZExt();
  4960. if (F.paramHasAttr(j, Attribute::SExt))
  4961. Flags.setSExt();
  4962. if (F.paramHasAttr(j, Attribute::InReg))
  4963. Flags.setInReg();
  4964. if (F.paramHasAttr(j, Attribute::StructRet))
  4965. Flags.setSRet();
  4966. if (F.paramHasAttr(j, Attribute::ByVal)) {
  4967. Flags.setByVal();
  4968. const PointerType *Ty = cast<PointerType>(I->getType());
  4969. const Type *ElementTy = Ty->getElementType();
  4970. unsigned FrameAlign = getByValTypeAlignment(ElementTy);
  4971. unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
  4972. // For ByVal, alignment should be passed from FE. BE will guess if
  4973. // this info is not there but there are cases it cannot get right.
  4974. if (F.getParamAlignment(j))
  4975. FrameAlign = F.getParamAlignment(j);
  4976. Flags.setByValAlign(FrameAlign);
  4977. Flags.setByValSize(FrameSize);
  4978. }
  4979. if (F.paramHasAttr(j, Attribute::Nest))
  4980. Flags.setNest();
  4981. Flags.setOrigAlign(OriginalAlignment);
  4982. MVT RegisterVT = getRegisterType(VT);
  4983. unsigned NumRegs = getNumRegisters(VT);
  4984. for (unsigned i = 0; i != NumRegs; ++i) {
  4985. RetVals.push_back(RegisterVT);
  4986. ISD::ArgFlagsTy MyFlags = Flags;
  4987. if (NumRegs > 1 && i == 0)
  4988. MyFlags.setSplit();
  4989. // if it isn't first piece, alignment must be 1
  4990. else if (i > 0)
  4991. MyFlags.setOrigAlign(1);
  4992. Ops.push_back(DAG.getArgFlags(MyFlags));
  4993. }
  4994. }
  4995. }
  4996. RetVals.push_back(MVT::Other);
  4997. // Create the node.
  4998. SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
  4999. DAG.getVTList(&RetVals[0], RetVals.size()),
  5000. &Ops[0], Ops.size()).getNode();
  5001. // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
  5002. // allows exposing the loads that may be part of the argument access to the
  5003. // first DAGCombiner pass.
  5004. SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
  5005. // The number of results should match up, except that the lowered one may have
  5006. // an extra flag result.
  5007. assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
  5008. (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
  5009. TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
  5010. && "Lowering produced unexpected number of results!");
  5011. // The FORMAL_ARGUMENTS node itself is likely no longer needed.
  5012. if (Result != TmpRes.getNode() && Result->use_empty()) {
  5013. HandleSDNode Dummy(DAG.getRoot());
  5014. DAG.RemoveDeadNode(Result);
  5015. }
  5016. Result = TmpRes.getNode();
  5017. unsigned NumArgRegs = Result->getNumValues() - 1;
  5018. DAG.setRoot(SDValue(Result, NumArgRegs));
  5019. // Set up the return result vector.
  5020. unsigned i = 0;
  5021. unsigned Idx = 1;
  5022. for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
  5023. ++I, ++Idx) {
  5024. SmallVector<MVT, 4> ValueVTs;
  5025. ComputeValueVTs(*this, I->getType(), ValueVTs);
  5026. for (unsigned Value = 0, NumValues = ValueVTs.size();
  5027. Value != NumValues; ++Value) {
  5028. MVT VT = ValueVTs[Value];
  5029. MVT PartVT = getRegisterType(VT);
  5030. unsigned NumParts = getNumRegisters(VT);
  5031. SmallVector<SDValue, 4> Parts(NumParts);
  5032. for (unsigned j = 0; j != NumParts; ++j)
  5033. Parts[j] = SDValue(Result, i++);
  5034. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  5035. if (F.paramHasAttr(Idx, Attribute::SExt))
  5036. AssertOp = ISD::AssertSext;
  5037. else if (F.paramHasAttr(Idx, Attribute::ZExt))
  5038. AssertOp = ISD::AssertZext;
  5039. ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
  5040. PartVT, VT, AssertOp));
  5041. }
  5042. }
  5043. assert(i == NumArgRegs && "Argument register count mismatch!");
  5044. }
  5045. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  5046. /// implementation, which just inserts an ISD::CALL node, which is later custom
  5047. /// lowered by the target to something concrete. FIXME: When all targets are
  5048. /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
  5049. std::pair<SDValue, SDValue>
  5050. TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
  5051. bool RetSExt, bool RetZExt, bool isVarArg,
  5052. bool isInreg,
  5053. unsigned CallingConv, bool isTailCall,
  5054. SDValue Callee,
  5055. ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
  5056. assert((!isTailCall || PerformTailCallOpt) &&
  5057. "isTailCall set when tail-call optimizations are disabled!");
  5058. SmallVector<SDValue, 32> Ops;
  5059. Ops.push_back(Chain); // Op#0 - Chain
  5060. Ops.push_back(Callee);
  5061. // Handle all of the outgoing arguments.
  5062. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  5063. SmallVector<MVT, 4> ValueVTs;
  5064. ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
  5065. for (unsigned Value = 0, NumValues = ValueVTs.size();
  5066. Value != NumValues; ++Value) {
  5067. MVT VT = ValueVTs[Value];
  5068. const Type *ArgTy = VT.getTypeForMVT();
  5069. SDValue Op = SDValue(Args[i].Node.getNode(),
  5070. Args[i].Node.getResNo() + Value);
  5071. ISD::ArgFlagsTy Flags;
  5072. unsigned OriginalAlignment =
  5073. getTargetData()->getABITypeAlignment(ArgTy);
  5074. if (Args[i].isZExt)
  5075. Flags.setZExt();
  5076. if (Args[i].isSExt)
  5077. Flags.setSExt();
  5078. if (Args[i].isInReg)
  5079. Flags.setInReg();
  5080. if (Args[i].isSRet)
  5081. Flags.setSRet();
  5082. if (Args[i].isByVal) {
  5083. Flags.setByVal();
  5084. const PointerType *Ty = cast<PointerType>(Args[i].Ty);
  5085. const Type *ElementTy = Ty->getElementType();
  5086. unsigned FrameAlign = getByValTypeAlignment(ElementTy);
  5087. unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
  5088. // For ByVal, alignment should come from FE. BE will guess if this
  5089. // info is not there but there are cases it cannot get right.
  5090. if (Args[i].Alignment)
  5091. FrameAlign = Args[i].Alignment;
  5092. Flags.setByValAlign(FrameAlign);
  5093. Flags.setByValSize(FrameSize);
  5094. }
  5095. if (Args[i].isNest)
  5096. Flags.setNest();
  5097. Flags.setOrigAlign(OriginalAlignment);
  5098. MVT PartVT = getRegisterType(VT);
  5099. unsigned NumParts = getNumRegisters(VT);
  5100. SmallVector<SDValue, 4> Parts(NumParts);
  5101. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  5102. if (Args[i].isSExt)
  5103. ExtendKind = ISD::SIGN_EXTEND;
  5104. else if (Args[i].isZExt)
  5105. ExtendKind = ISD::ZERO_EXTEND;
  5106. getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
  5107. for (unsigned i = 0; i != NumParts; ++i) {
  5108. // if it isn't first piece, alignment must be 1
  5109. ISD::ArgFlagsTy MyFlags = Flags;
  5110. if (NumParts > 1 && i == 0)
  5111. MyFlags.setSplit();
  5112. else if (i != 0)
  5113. MyFlags.setOrigAlign(1);
  5114. Ops.push_back(Parts[i]);
  5115. Ops.push_back(DAG.getArgFlags(MyFlags));
  5116. }
  5117. }
  5118. }
  5119. // Figure out the result value types. We start by making a list of
  5120. // the potentially illegal return value types.
  5121. SmallVector<MVT, 4> LoweredRetTys;
  5122. SmallVector<MVT, 4> RetTys;
  5123. ComputeValueVTs(*this, RetTy, RetTys);
  5124. // Then we translate that to a list of legal types.
  5125. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  5126. MVT VT = RetTys[I];
  5127. MVT RegisterVT = getRegisterType(VT);
  5128. unsigned NumRegs = getNumRegisters(VT);
  5129. for (unsigned i = 0; i != NumRegs; ++i)
  5130. LoweredRetTys.push_back(RegisterVT);
  5131. }
  5132. LoweredRetTys.push_back(MVT::Other); // Always has a chain.
  5133. // Create the CALL node.
  5134. SDValue Res = DAG.getCall(CallingConv, dl,
  5135. isVarArg, isTailCall, isInreg,
  5136. DAG.getVTList(&LoweredRetTys[0],
  5137. LoweredRetTys.size()),
  5138. &Ops[0], Ops.size()
  5139. );
  5140. Chain = Res.getValue(LoweredRetTys.size() - 1);
  5141. // Gather up the call result into a single value.
  5142. if (RetTy != Type::VoidTy && !RetTys.empty()) {
  5143. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  5144. if (RetSExt)
  5145. AssertOp = ISD::AssertSext;
  5146. else if (RetZExt)
  5147. AssertOp = ISD::AssertZext;
  5148. SmallVector<SDValue, 4> ReturnValues;
  5149. unsigned RegNo = 0;
  5150. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  5151. MVT VT = RetTys[I];
  5152. MVT RegisterVT = getRegisterType(VT);
  5153. unsigned NumRegs = getNumRegisters(VT);
  5154. unsigned RegNoEnd = NumRegs + RegNo;
  5155. SmallVector<SDValue, 4> Results;
  5156. for (; RegNo != RegNoEnd; ++RegNo)
  5157. Results.push_back(Res.getValue(RegNo));
  5158. SDValue ReturnValue =
  5159. getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
  5160. AssertOp);
  5161. ReturnValues.push_back(ReturnValue);
  5162. }
  5163. Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  5164. DAG.getVTList(&RetTys[0], RetTys.size()),
  5165. &ReturnValues[0], ReturnValues.size());
  5166. }
  5167. return std::make_pair(Res, Chain);
  5168. }
  5169. void TargetLowering::LowerOperationWrapper(SDNode *N,
  5170. SmallVectorImpl<SDValue> &Results,
  5171. SelectionDAG &DAG) {
  5172. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  5173. if (Res.getNode())
  5174. Results.push_back(Res);
  5175. }
  5176. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
  5177. assert(0 && "LowerOperation not implemented for this target!");
  5178. abort();
  5179. return SDValue();
  5180. }
  5181. void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
  5182. SDValue Op = getValue(V);
  5183. assert((Op.getOpcode() != ISD::CopyFromReg ||
  5184. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  5185. "Copy from a reg to the same reg!");
  5186. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  5187. RegsForValue RFV(TLI, Reg, V->getType());
  5188. SDValue Chain = DAG.getEntryNode();
  5189. RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
  5190. PendingExports.push_back(Chain);
  5191. }
  5192. #include "llvm/CodeGen/SelectionDAGISel.h"
  5193. void SelectionDAGISel::
  5194. LowerArguments(BasicBlock *LLVMBB) {
  5195. // If this is the entry block, emit arguments.
  5196. Function &F = *LLVMBB->getParent();
  5197. SDValue OldRoot = SDL->DAG.getRoot();
  5198. SmallVector<SDValue, 16> Args;
  5199. TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
  5200. unsigned a = 0;
  5201. for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
  5202. AI != E; ++AI) {
  5203. SmallVector<MVT, 4> ValueVTs;
  5204. ComputeValueVTs(TLI, AI->getType(), ValueVTs);
  5205. unsigned NumValues = ValueVTs.size();
  5206. if (!AI->use_empty()) {
  5207. SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
  5208. SDL->getCurDebugLoc()));
  5209. // If this argument is live outside of the entry block, insert a copy from
  5210. // whereever we got it to the vreg that other BB's will reference it as.
  5211. SDL->CopyToExportRegsIfNeeded(AI);
  5212. }
  5213. a += NumValues;
  5214. }
  5215. // Finally, if the target has anything special to do, allow it to do so.
  5216. // FIXME: this should insert code into the DAG!
  5217. EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
  5218. }
  5219. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  5220. /// ensure constants are generated when needed. Remember the virtual registers
  5221. /// that need to be added to the Machine PHI nodes as input. We cannot just
  5222. /// directly add them, because expansion might result in multiple MBB's for one
  5223. /// BB. As such, the start of the BB might correspond to a different MBB than
  5224. /// the end.
  5225. ///
  5226. void
  5227. SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
  5228. TerminatorInst *TI = LLVMBB->getTerminator();
  5229. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  5230. // Check successor nodes' PHI nodes that expect a constant to be available
  5231. // from this block.
  5232. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  5233. BasicBlock *SuccBB = TI->getSuccessor(succ);
  5234. if (!isa<PHINode>(SuccBB->begin())) continue;
  5235. MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
  5236. // If this terminator has multiple identical successors (common for
  5237. // switches), only handle each succ once.
  5238. if (!SuccsHandled.insert(SuccMBB)) continue;
  5239. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  5240. PHINode *PN;
  5241. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  5242. // nodes and Machine PHI nodes, but the incoming operands have not been
  5243. // emitted yet.
  5244. for (BasicBlock::iterator I = SuccBB->begin();
  5245. (PN = dyn_cast<PHINode>(I)); ++I) {
  5246. // Ignore dead phi's.
  5247. if (PN->use_empty()) continue;
  5248. unsigned Reg;
  5249. Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  5250. if (Constant *C = dyn_cast<Constant>(PHIOp)) {
  5251. unsigned &RegOut = SDL->ConstantsOut[C];
  5252. if (RegOut == 0) {
  5253. RegOut = FuncInfo->CreateRegForValue(C);
  5254. SDL->CopyValueToVirtualRegister(C, RegOut);
  5255. }
  5256. Reg = RegOut;
  5257. } else {
  5258. Reg = FuncInfo->ValueMap[PHIOp];
  5259. if (Reg == 0) {
  5260. assert(isa<AllocaInst>(PHIOp) &&
  5261. FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  5262. "Didn't codegen value into a register!??");
  5263. Reg = FuncInfo->CreateRegForValue(PHIOp);
  5264. SDL->CopyValueToVirtualRegister(PHIOp, Reg);
  5265. }
  5266. }
  5267. // Remember that this register needs to added to the machine PHI node as
  5268. // the input for this MBB.
  5269. SmallVector<MVT, 4> ValueVTs;
  5270. ComputeValueVTs(TLI, PN->getType(), ValueVTs);
  5271. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  5272. MVT VT = ValueVTs[vti];
  5273. unsigned NumRegisters = TLI.getNumRegisters(VT);
  5274. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  5275. SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
  5276. Reg += NumRegisters;
  5277. }
  5278. }
  5279. }
  5280. SDL->ConstantsOut.clear();
  5281. }
  5282. /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
  5283. /// supports legal types, and it emits MachineInstrs directly instead of
  5284. /// creating SelectionDAG nodes.
  5285. ///
  5286. bool
  5287. SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
  5288. FastISel *F) {
  5289. TerminatorInst *TI = LLVMBB->getTerminator();
  5290. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  5291. unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
  5292. // Check successor nodes' PHI nodes that expect a constant to be available
  5293. // from this block.
  5294. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  5295. BasicBlock *SuccBB = TI->getSuccessor(succ);
  5296. if (!isa<PHINode>(SuccBB->begin())) continue;
  5297. MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
  5298. // If this terminator has multiple identical successors (common for
  5299. // switches), only handle each succ once.
  5300. if (!SuccsHandled.insert(SuccMBB)) continue;
  5301. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  5302. PHINode *PN;
  5303. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  5304. // nodes and Machine PHI nodes, but the incoming operands have not been
  5305. // emitted yet.
  5306. for (BasicBlock::iterator I = SuccBB->begin();
  5307. (PN = dyn_cast<PHINode>(I)); ++I) {
  5308. // Ignore dead phi's.
  5309. if (PN->use_empty()) continue;
  5310. // Only handle legal types. Two interesting things to note here. First,
  5311. // by bailing out early, we may leave behind some dead instructions,
  5312. // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
  5313. // own moves. Second, this check is necessary becuase FastISel doesn't
  5314. // use CreateRegForValue to create registers, so it always creates
  5315. // exactly one register for each non-void instruction.
  5316. MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
  5317. if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
  5318. // Promote MVT::i1.
  5319. if (VT == MVT::i1)
  5320. VT = TLI.getTypeToTransformTo(VT);
  5321. else {
  5322. SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
  5323. return false;
  5324. }
  5325. }
  5326. Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  5327. unsigned Reg = F->getRegForValue(PHIOp);
  5328. if (Reg == 0) {
  5329. SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
  5330. return false;
  5331. }
  5332. SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
  5333. }
  5334. }
  5335. return true;
  5336. }