LegalizeDAG.cpp 193 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021
  1. //===- LegalizeDAG.cpp - Implement SelectionDAG::Legalize -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the SelectionDAG::Legalize method.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/APFloat.h"
  13. #include "llvm/ADT/APInt.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/Analysis/TargetLibraryInfo.h"
  20. #include "llvm/CodeGen/ISDOpcodes.h"
  21. #include "llvm/CodeGen/MachineFunction.h"
  22. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  23. #include "llvm/CodeGen/MachineMemOperand.h"
  24. #include "llvm/CodeGen/RuntimeLibcalls.h"
  25. #include "llvm/CodeGen/SelectionDAG.h"
  26. #include "llvm/CodeGen/SelectionDAGNodes.h"
  27. #include "llvm/CodeGen/TargetFrameLowering.h"
  28. #include "llvm/CodeGen/TargetLowering.h"
  29. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  30. #include "llvm/CodeGen/ValueTypes.h"
  31. #include "llvm/IR/CallingConv.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/DerivedTypes.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/Metadata.h"
  37. #include "llvm/IR/Type.h"
  38. #include "llvm/Support/Casting.h"
  39. #include "llvm/Support/Compiler.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/MachineValueType.h"
  43. #include "llvm/Support/MathExtras.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include "llvm/Target/TargetMachine.h"
  46. #include "llvm/Target/TargetOptions.h"
  47. #include <algorithm>
  48. #include <cassert>
  49. #include <cstdint>
  50. #include <tuple>
  51. #include <utility>
  52. using namespace llvm;
  53. #define DEBUG_TYPE "legalizedag"
  54. namespace {
  55. /// Keeps track of state when getting the sign of a floating-point value as an
  56. /// integer.
  57. struct FloatSignAsInt {
  58. EVT FloatVT;
  59. SDValue Chain;
  60. SDValue FloatPtr;
  61. SDValue IntPtr;
  62. MachinePointerInfo IntPointerInfo;
  63. MachinePointerInfo FloatPointerInfo;
  64. SDValue IntValue;
  65. APInt SignMask;
  66. uint8_t SignBit;
  67. };
  68. //===----------------------------------------------------------------------===//
  69. /// This takes an arbitrary SelectionDAG as input and
  70. /// hacks on it until the target machine can handle it. This involves
  71. /// eliminating value sizes the machine cannot handle (promoting small sizes to
  72. /// large sizes or splitting up large values into small values) as well as
  73. /// eliminating operations the machine cannot handle.
  74. ///
  75. /// This code also does a small amount of optimization and recognition of idioms
  76. /// as part of its processing. For example, if a target does not support a
  77. /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
  78. /// will attempt merge setcc and brc instructions into brcc's.
  79. class SelectionDAGLegalize {
  80. const TargetMachine &TM;
  81. const TargetLowering &TLI;
  82. SelectionDAG &DAG;
  83. /// The set of nodes which have already been legalized. We hold a
  84. /// reference to it in order to update as necessary on node deletion.
  85. SmallPtrSetImpl<SDNode *> &LegalizedNodes;
  86. /// A set of all the nodes updated during legalization.
  87. SmallSetVector<SDNode *, 16> *UpdatedNodes;
  88. EVT getSetCCResultType(EVT VT) const {
  89. return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
  90. }
  91. // Libcall insertion helpers.
  92. public:
  93. SelectionDAGLegalize(SelectionDAG &DAG,
  94. SmallPtrSetImpl<SDNode *> &LegalizedNodes,
  95. SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
  96. : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
  97. LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {}
  98. /// Legalizes the given operation.
  99. void LegalizeOp(SDNode *Node);
  100. private:
  101. SDValue OptimizeFloatStore(StoreSDNode *ST);
  102. void LegalizeLoadOps(SDNode *Node);
  103. void LegalizeStoreOps(SDNode *Node);
  104. /// Some targets cannot handle a variable
  105. /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
  106. /// is necessary to spill the vector being inserted into to memory, perform
  107. /// the insert there, and then read the result back.
  108. SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
  109. const SDLoc &dl);
  110. SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx,
  111. const SDLoc &dl);
  112. /// Return a vector shuffle operation which
  113. /// performs the same shuffe in terms of order or result bytes, but on a type
  114. /// whose vector element type is narrower than the original shuffle type.
  115. /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
  116. SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl,
  117. SDValue N1, SDValue N2,
  118. ArrayRef<int> Mask) const;
  119. SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
  120. void ExpandFPLibCall(SDNode *Node, RTLIB::Libcall LC,
  121. SmallVectorImpl<SDValue> &Results);
  122. void ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
  123. RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
  124. RTLIB::Libcall Call_F128,
  125. RTLIB::Libcall Call_PPCF128,
  126. SmallVectorImpl<SDValue> &Results);
  127. SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
  128. RTLIB::Libcall Call_I8,
  129. RTLIB::Libcall Call_I16,
  130. RTLIB::Libcall Call_I32,
  131. RTLIB::Libcall Call_I64,
  132. RTLIB::Libcall Call_I128);
  133. void ExpandArgFPLibCall(SDNode *Node,
  134. RTLIB::Libcall Call_F32, RTLIB::Libcall Call_F64,
  135. RTLIB::Libcall Call_F80, RTLIB::Libcall Call_F128,
  136. RTLIB::Libcall Call_PPCF128,
  137. SmallVectorImpl<SDValue> &Results);
  138. void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
  139. void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
  140. SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
  141. const SDLoc &dl);
  142. SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
  143. const SDLoc &dl, SDValue ChainIn);
  144. SDValue ExpandBUILD_VECTOR(SDNode *Node);
  145. SDValue ExpandSPLAT_VECTOR(SDNode *Node);
  146. SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
  147. void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
  148. SmallVectorImpl<SDValue> &Results);
  149. void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL,
  150. SDValue Value) const;
  151. SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL,
  152. SDValue NewIntValue) const;
  153. SDValue ExpandFCOPYSIGN(SDNode *Node) const;
  154. SDValue ExpandFABS(SDNode *Node) const;
  155. SDValue ExpandFNEG(SDNode *Node) const;
  156. SDValue ExpandLegalINT_TO_FP(SDNode *Node, SDValue &Chain);
  157. void PromoteLegalINT_TO_FP(SDNode *N, const SDLoc &dl,
  158. SmallVectorImpl<SDValue> &Results);
  159. void PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
  160. SmallVectorImpl<SDValue> &Results);
  161. SDValue PromoteLegalFP_TO_INT_SAT(SDNode *Node, const SDLoc &dl);
  162. SDValue ExpandPARITY(SDValue Op, const SDLoc &dl);
  163. SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
  164. SDValue ExpandInsertToVectorThroughStack(SDValue Op);
  165. SDValue ExpandVectorBuildThroughStack(SDNode* Node);
  166. SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
  167. SDValue ExpandConstant(ConstantSDNode *CP);
  168. // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall
  169. bool ExpandNode(SDNode *Node);
  170. void ConvertNodeToLibcall(SDNode *Node);
  171. void PromoteNode(SDNode *Node);
  172. public:
  173. // Node replacement helpers
  174. void ReplacedNode(SDNode *N) {
  175. LegalizedNodes.erase(N);
  176. if (UpdatedNodes)
  177. UpdatedNodes->insert(N);
  178. }
  179. void ReplaceNode(SDNode *Old, SDNode *New) {
  180. LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
  181. dbgs() << " with: "; New->dump(&DAG));
  182. assert(Old->getNumValues() == New->getNumValues() &&
  183. "Replacing one node with another that produces a different number "
  184. "of values!");
  185. DAG.ReplaceAllUsesWith(Old, New);
  186. if (UpdatedNodes)
  187. UpdatedNodes->insert(New);
  188. ReplacedNode(Old);
  189. }
  190. void ReplaceNode(SDValue Old, SDValue New) {
  191. LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
  192. dbgs() << " with: "; New->dump(&DAG));
  193. DAG.ReplaceAllUsesWith(Old, New);
  194. if (UpdatedNodes)
  195. UpdatedNodes->insert(New.getNode());
  196. ReplacedNode(Old.getNode());
  197. }
  198. void ReplaceNode(SDNode *Old, const SDValue *New) {
  199. LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
  200. DAG.ReplaceAllUsesWith(Old, New);
  201. for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
  202. LLVM_DEBUG(dbgs() << (i == 0 ? " with: " : " and: ");
  203. New[i]->dump(&DAG));
  204. if (UpdatedNodes)
  205. UpdatedNodes->insert(New[i].getNode());
  206. }
  207. ReplacedNode(Old);
  208. }
  209. void ReplaceNodeWithValue(SDValue Old, SDValue New) {
  210. LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
  211. dbgs() << " with: "; New->dump(&DAG));
  212. DAG.ReplaceAllUsesOfValueWith(Old, New);
  213. if (UpdatedNodes)
  214. UpdatedNodes->insert(New.getNode());
  215. ReplacedNode(Old.getNode());
  216. }
  217. };
  218. } // end anonymous namespace
  219. /// Return a vector shuffle operation which
  220. /// performs the same shuffle in terms of order or result bytes, but on a type
  221. /// whose vector element type is narrower than the original shuffle type.
  222. /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
  223. SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType(
  224. EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
  225. ArrayRef<int> Mask) const {
  226. unsigned NumMaskElts = VT.getVectorNumElements();
  227. unsigned NumDestElts = NVT.getVectorNumElements();
  228. unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
  229. assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
  230. if (NumEltsGrowth == 1)
  231. return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask);
  232. SmallVector<int, 8> NewMask;
  233. for (unsigned i = 0; i != NumMaskElts; ++i) {
  234. int Idx = Mask[i];
  235. for (unsigned j = 0; j != NumEltsGrowth; ++j) {
  236. if (Idx < 0)
  237. NewMask.push_back(-1);
  238. else
  239. NewMask.push_back(Idx * NumEltsGrowth + j);
  240. }
  241. }
  242. assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
  243. assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
  244. return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask);
  245. }
  246. /// Expands the ConstantFP node to an integer constant or
  247. /// a load from the constant pool.
  248. SDValue
  249. SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
  250. bool Extend = false;
  251. SDLoc dl(CFP);
  252. // If a FP immediate is precise when represented as a float and if the
  253. // target can do an extending load from float to double, we put it into
  254. // the constant pool as a float, even if it's is statically typed as a
  255. // double. This shrinks FP constants and canonicalizes them for targets where
  256. // an FP extending load is the same cost as a normal load (such as on the x87
  257. // fp stack or PPC FP unit).
  258. EVT VT = CFP->getValueType(0);
  259. ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
  260. if (!UseCP) {
  261. assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
  262. return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl,
  263. (VT == MVT::f64) ? MVT::i64 : MVT::i32);
  264. }
  265. APFloat APF = CFP->getValueAPF();
  266. EVT OrigVT = VT;
  267. EVT SVT = VT;
  268. // We don't want to shrink SNaNs. Converting the SNaN back to its real type
  269. // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ).
  270. if (!APF.isSignaling()) {
  271. while (SVT != MVT::f32 && SVT != MVT::f16) {
  272. SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
  273. if (ConstantFPSDNode::isValueValidForType(SVT, APF) &&
  274. // Only do this if the target has a native EXTLOAD instruction from
  275. // smaller type.
  276. TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) &&
  277. TLI.ShouldShrinkFPConstant(OrigVT)) {
  278. Type *SType = SVT.getTypeForEVT(*DAG.getContext());
  279. LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
  280. VT = SVT;
  281. Extend = true;
  282. }
  283. }
  284. }
  285. SDValue CPIdx =
  286. DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout()));
  287. Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
  288. if (Extend) {
  289. SDValue Result = DAG.getExtLoad(
  290. ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx,
  291. MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT,
  292. Alignment);
  293. return Result;
  294. }
  295. SDValue Result = DAG.getLoad(
  296. OrigVT, dl, DAG.getEntryNode(), CPIdx,
  297. MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
  298. return Result;
  299. }
  300. /// Expands the Constant node to a load from the constant pool.
  301. SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) {
  302. SDLoc dl(CP);
  303. EVT VT = CP->getValueType(0);
  304. SDValue CPIdx = DAG.getConstantPool(CP->getConstantIntValue(),
  305. TLI.getPointerTy(DAG.getDataLayout()));
  306. Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
  307. SDValue Result = DAG.getLoad(
  308. VT, dl, DAG.getEntryNode(), CPIdx,
  309. MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
  310. return Result;
  311. }
  312. /// Some target cannot handle a variable insertion index for the
  313. /// INSERT_VECTOR_ELT instruction. In this case, it
  314. /// is necessary to spill the vector being inserted into to memory, perform
  315. /// the insert there, and then read the result back.
  316. SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec,
  317. SDValue Val,
  318. SDValue Idx,
  319. const SDLoc &dl) {
  320. SDValue Tmp1 = Vec;
  321. SDValue Tmp2 = Val;
  322. SDValue Tmp3 = Idx;
  323. // If the target doesn't support this, we have to spill the input vector
  324. // to a temporary stack slot, update the element, then reload it. This is
  325. // badness. We could also load the value into a vector register (either
  326. // with a "move to register" or "extload into register" instruction, then
  327. // permute it into place, if the idx is a constant and if the idx is
  328. // supported by the target.
  329. EVT VT = Tmp1.getValueType();
  330. EVT EltVT = VT.getVectorElementType();
  331. SDValue StackPtr = DAG.CreateStackTemporary(VT);
  332. int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
  333. // Store the vector.
  334. SDValue Ch = DAG.getStore(
  335. DAG.getEntryNode(), dl, Tmp1, StackPtr,
  336. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
  337. SDValue StackPtr2 = TLI.getVectorElementPointer(DAG, StackPtr, VT, Tmp3);
  338. // Store the scalar value.
  339. Ch = DAG.getTruncStore(
  340. Ch, dl, Tmp2, StackPtr2,
  341. MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), EltVT);
  342. // Load the updated vector.
  343. return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack(
  344. DAG.getMachineFunction(), SPFI));
  345. }
  346. SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
  347. SDValue Idx,
  348. const SDLoc &dl) {
  349. if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
  350. // SCALAR_TO_VECTOR requires that the type of the value being inserted
  351. // match the element type of the vector being created, except for
  352. // integers in which case the inserted value can be over width.
  353. EVT EltVT = Vec.getValueType().getVectorElementType();
  354. if (Val.getValueType() == EltVT ||
  355. (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
  356. SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
  357. Vec.getValueType(), Val);
  358. unsigned NumElts = Vec.getValueType().getVectorNumElements();
  359. // We generate a shuffle of InVec and ScVec, so the shuffle mask
  360. // should be 0,1,2,3,4,5... with the appropriate element replaced with
  361. // elt 0 of the RHS.
  362. SmallVector<int, 8> ShufOps;
  363. for (unsigned i = 0; i != NumElts; ++i)
  364. ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
  365. return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps);
  366. }
  367. }
  368. return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
  369. }
  370. SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
  371. if (!ISD::isNormalStore(ST))
  372. return SDValue();
  373. LLVM_DEBUG(dbgs() << "Optimizing float store operations\n");
  374. // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
  375. // FIXME: move this to the DAG Combiner! Note that we can't regress due
  376. // to phase ordering between legalized code and the dag combiner. This
  377. // probably means that we need to integrate dag combiner and legalizer
  378. // together.
  379. // We generally can't do this one for long doubles.
  380. SDValue Chain = ST->getChain();
  381. SDValue Ptr = ST->getBasePtr();
  382. SDValue Value = ST->getValue();
  383. MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
  384. AAMDNodes AAInfo = ST->getAAInfo();
  385. SDLoc dl(ST);
  386. // Don't optimise TargetConstantFP
  387. if (Value.getOpcode() == ISD::TargetConstantFP)
  388. return SDValue();
  389. if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
  390. if (CFP->getValueType(0) == MVT::f32 &&
  391. TLI.isTypeLegal(MVT::i32)) {
  392. SDValue Con = DAG.getConstant(CFP->getValueAPF().
  393. bitcastToAPInt().zextOrTrunc(32),
  394. SDLoc(CFP), MVT::i32);
  395. return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
  396. ST->getOriginalAlign(), MMOFlags, AAInfo);
  397. }
  398. if (CFP->getValueType(0) == MVT::f64) {
  399. // If this target supports 64-bit registers, do a single 64-bit store.
  400. if (TLI.isTypeLegal(MVT::i64)) {
  401. SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
  402. zextOrTrunc(64), SDLoc(CFP), MVT::i64);
  403. return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
  404. ST->getOriginalAlign(), MMOFlags, AAInfo);
  405. }
  406. if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
  407. // Otherwise, if the target supports 32-bit registers, use 2 32-bit
  408. // stores. If the target supports neither 32- nor 64-bits, this
  409. // xform is certainly not worth it.
  410. const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
  411. SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
  412. SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
  413. if (DAG.getDataLayout().isBigEndian())
  414. std::swap(Lo, Hi);
  415. Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(),
  416. ST->getOriginalAlign(), MMOFlags, AAInfo);
  417. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(4), dl);
  418. Hi = DAG.getStore(Chain, dl, Hi, Ptr,
  419. ST->getPointerInfo().getWithOffset(4),
  420. ST->getOriginalAlign(), MMOFlags, AAInfo);
  421. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
  422. }
  423. }
  424. }
  425. return SDValue();
  426. }
  427. void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
  428. StoreSDNode *ST = cast<StoreSDNode>(Node);
  429. SDValue Chain = ST->getChain();
  430. SDValue Ptr = ST->getBasePtr();
  431. SDLoc dl(Node);
  432. MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
  433. AAMDNodes AAInfo = ST->getAAInfo();
  434. if (!ST->isTruncatingStore()) {
  435. LLVM_DEBUG(dbgs() << "Legalizing store operation\n");
  436. if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
  437. ReplaceNode(ST, OptStore);
  438. return;
  439. }
  440. SDValue Value = ST->getValue();
  441. MVT VT = Value.getSimpleValueType();
  442. switch (TLI.getOperationAction(ISD::STORE, VT)) {
  443. default: llvm_unreachable("This action is not supported yet!");
  444. case TargetLowering::Legal: {
  445. // If this is an unaligned store and the target doesn't support it,
  446. // expand it.
  447. EVT MemVT = ST->getMemoryVT();
  448. const DataLayout &DL = DAG.getDataLayout();
  449. if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
  450. *ST->getMemOperand())) {
  451. LLVM_DEBUG(dbgs() << "Expanding unsupported unaligned store\n");
  452. SDValue Result = TLI.expandUnalignedStore(ST, DAG);
  453. ReplaceNode(SDValue(ST, 0), Result);
  454. } else
  455. LLVM_DEBUG(dbgs() << "Legal store\n");
  456. break;
  457. }
  458. case TargetLowering::Custom: {
  459. LLVM_DEBUG(dbgs() << "Trying custom lowering\n");
  460. SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
  461. if (Res && Res != SDValue(Node, 0))
  462. ReplaceNode(SDValue(Node, 0), Res);
  463. return;
  464. }
  465. case TargetLowering::Promote: {
  466. MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
  467. assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
  468. "Can only promote stores to same size type");
  469. Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
  470. SDValue Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
  471. ST->getOriginalAlign(), MMOFlags, AAInfo);
  472. ReplaceNode(SDValue(Node, 0), Result);
  473. break;
  474. }
  475. }
  476. return;
  477. }
  478. LLVM_DEBUG(dbgs() << "Legalizing truncating store operations\n");
  479. SDValue Value = ST->getValue();
  480. EVT StVT = ST->getMemoryVT();
  481. TypeSize StWidth = StVT.getSizeInBits();
  482. TypeSize StSize = StVT.getStoreSizeInBits();
  483. auto &DL = DAG.getDataLayout();
  484. if (StWidth != StSize) {
  485. // Promote to a byte-sized store with upper bits zero if not
  486. // storing an integral number of bytes. For example, promote
  487. // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
  488. EVT NVT = EVT::getIntegerVT(*DAG.getContext(), StSize.getFixedSize());
  489. Value = DAG.getZeroExtendInReg(Value, dl, StVT);
  490. SDValue Result =
  491. DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT,
  492. ST->getOriginalAlign(), MMOFlags, AAInfo);
  493. ReplaceNode(SDValue(Node, 0), Result);
  494. } else if (!StVT.isVector() && !isPowerOf2_64(StWidth.getFixedSize())) {
  495. // If not storing a power-of-2 number of bits, expand as two stores.
  496. assert(!StVT.isVector() && "Unsupported truncstore!");
  497. unsigned StWidthBits = StWidth.getFixedSize();
  498. unsigned LogStWidth = Log2_32(StWidthBits);
  499. assert(LogStWidth < 32);
  500. unsigned RoundWidth = 1 << LogStWidth;
  501. assert(RoundWidth < StWidthBits);
  502. unsigned ExtraWidth = StWidthBits - RoundWidth;
  503. assert(ExtraWidth < RoundWidth);
  504. assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
  505. "Store size not an integral number of bytes!");
  506. EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
  507. EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
  508. SDValue Lo, Hi;
  509. unsigned IncrementSize;
  510. if (DL.isLittleEndian()) {
  511. // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
  512. // Store the bottom RoundWidth bits.
  513. Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
  514. RoundVT, ST->getOriginalAlign(), MMOFlags, AAInfo);
  515. // Store the remaining ExtraWidth bits.
  516. IncrementSize = RoundWidth / 8;
  517. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(IncrementSize), dl);
  518. Hi = DAG.getNode(
  519. ISD::SRL, dl, Value.getValueType(), Value,
  520. DAG.getConstant(RoundWidth, dl,
  521. TLI.getShiftAmountTy(Value.getValueType(), DL)));
  522. Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
  523. ST->getPointerInfo().getWithOffset(IncrementSize),
  524. ExtraVT, ST->getOriginalAlign(), MMOFlags, AAInfo);
  525. } else {
  526. // Big endian - avoid unaligned stores.
  527. // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
  528. // Store the top RoundWidth bits.
  529. Hi = DAG.getNode(
  530. ISD::SRL, dl, Value.getValueType(), Value,
  531. DAG.getConstant(ExtraWidth, dl,
  532. TLI.getShiftAmountTy(Value.getValueType(), DL)));
  533. Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(), RoundVT,
  534. ST->getOriginalAlign(), MMOFlags, AAInfo);
  535. // Store the remaining ExtraWidth bits.
  536. IncrementSize = RoundWidth / 8;
  537. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
  538. DAG.getConstant(IncrementSize, dl,
  539. Ptr.getValueType()));
  540. Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
  541. ST->getPointerInfo().getWithOffset(IncrementSize),
  542. ExtraVT, ST->getOriginalAlign(), MMOFlags, AAInfo);
  543. }
  544. // The order of the stores doesn't matter.
  545. SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
  546. ReplaceNode(SDValue(Node, 0), Result);
  547. } else {
  548. switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
  549. default: llvm_unreachable("This action is not supported yet!");
  550. case TargetLowering::Legal: {
  551. EVT MemVT = ST->getMemoryVT();
  552. // If this is an unaligned store and the target doesn't support it,
  553. // expand it.
  554. if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
  555. *ST->getMemOperand())) {
  556. SDValue Result = TLI.expandUnalignedStore(ST, DAG);
  557. ReplaceNode(SDValue(ST, 0), Result);
  558. }
  559. break;
  560. }
  561. case TargetLowering::Custom: {
  562. SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
  563. if (Res && Res != SDValue(Node, 0))
  564. ReplaceNode(SDValue(Node, 0), Res);
  565. return;
  566. }
  567. case TargetLowering::Expand:
  568. assert(!StVT.isVector() &&
  569. "Vector Stores are handled in LegalizeVectorOps");
  570. SDValue Result;
  571. // TRUNCSTORE:i16 i32 -> STORE i16
  572. if (TLI.isTypeLegal(StVT)) {
  573. Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
  574. Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
  575. ST->getOriginalAlign(), MMOFlags, AAInfo);
  576. } else {
  577. // The in-memory type isn't legal. Truncate to the type it would promote
  578. // to, and then do a truncstore.
  579. Value = DAG.getNode(ISD::TRUNCATE, dl,
  580. TLI.getTypeToTransformTo(*DAG.getContext(), StVT),
  581. Value);
  582. Result =
  583. DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), StVT,
  584. ST->getOriginalAlign(), MMOFlags, AAInfo);
  585. }
  586. ReplaceNode(SDValue(Node, 0), Result);
  587. break;
  588. }
  589. }
  590. }
  591. void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
  592. LoadSDNode *LD = cast<LoadSDNode>(Node);
  593. SDValue Chain = LD->getChain(); // The chain.
  594. SDValue Ptr = LD->getBasePtr(); // The base pointer.
  595. SDValue Value; // The value returned by the load op.
  596. SDLoc dl(Node);
  597. ISD::LoadExtType ExtType = LD->getExtensionType();
  598. if (ExtType == ISD::NON_EXTLOAD) {
  599. LLVM_DEBUG(dbgs() << "Legalizing non-extending load operation\n");
  600. MVT VT = Node->getSimpleValueType(0);
  601. SDValue RVal = SDValue(Node, 0);
  602. SDValue RChain = SDValue(Node, 1);
  603. switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
  604. default: llvm_unreachable("This action is not supported yet!");
  605. case TargetLowering::Legal: {
  606. EVT MemVT = LD->getMemoryVT();
  607. const DataLayout &DL = DAG.getDataLayout();
  608. // If this is an unaligned load and the target doesn't support it,
  609. // expand it.
  610. if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
  611. *LD->getMemOperand())) {
  612. std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG);
  613. }
  614. break;
  615. }
  616. case TargetLowering::Custom:
  617. if (SDValue Res = TLI.LowerOperation(RVal, DAG)) {
  618. RVal = Res;
  619. RChain = Res.getValue(1);
  620. }
  621. break;
  622. case TargetLowering::Promote: {
  623. MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
  624. assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
  625. "Can only promote loads to same size type");
  626. SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
  627. RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
  628. RChain = Res.getValue(1);
  629. break;
  630. }
  631. }
  632. if (RChain.getNode() != Node) {
  633. assert(RVal.getNode() != Node && "Load must be completely replaced");
  634. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
  635. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
  636. if (UpdatedNodes) {
  637. UpdatedNodes->insert(RVal.getNode());
  638. UpdatedNodes->insert(RChain.getNode());
  639. }
  640. ReplacedNode(Node);
  641. }
  642. return;
  643. }
  644. LLVM_DEBUG(dbgs() << "Legalizing extending load operation\n");
  645. EVT SrcVT = LD->getMemoryVT();
  646. TypeSize SrcWidth = SrcVT.getSizeInBits();
  647. MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
  648. AAMDNodes AAInfo = LD->getAAInfo();
  649. if (SrcWidth != SrcVT.getStoreSizeInBits() &&
  650. // Some targets pretend to have an i1 loading operation, and actually
  651. // load an i8. This trick is correct for ZEXTLOAD because the top 7
  652. // bits are guaranteed to be zero; it helps the optimizers understand
  653. // that these bits are zero. It is also useful for EXTLOAD, since it
  654. // tells the optimizers that those bits are undefined. It would be
  655. // nice to have an effective generic way of getting these benefits...
  656. // Until such a way is found, don't insist on promoting i1 here.
  657. (SrcVT != MVT::i1 ||
  658. TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) ==
  659. TargetLowering::Promote)) {
  660. // Promote to a byte-sized load if not loading an integral number of
  661. // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
  662. unsigned NewWidth = SrcVT.getStoreSizeInBits();
  663. EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
  664. SDValue Ch;
  665. // The extra bits are guaranteed to be zero, since we stored them that
  666. // way. A zext load from NVT thus automatically gives zext from SrcVT.
  667. ISD::LoadExtType NewExtType =
  668. ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
  669. SDValue Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
  670. Chain, Ptr, LD->getPointerInfo(), NVT,
  671. LD->getOriginalAlign(), MMOFlags, AAInfo);
  672. Ch = Result.getValue(1); // The chain.
  673. if (ExtType == ISD::SEXTLOAD)
  674. // Having the top bits zero doesn't help when sign extending.
  675. Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
  676. Result.getValueType(),
  677. Result, DAG.getValueType(SrcVT));
  678. else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
  679. // All the top bits are guaranteed to be zero - inform the optimizers.
  680. Result = DAG.getNode(ISD::AssertZext, dl,
  681. Result.getValueType(), Result,
  682. DAG.getValueType(SrcVT));
  683. Value = Result;
  684. Chain = Ch;
  685. } else if (!isPowerOf2_64(SrcWidth.getKnownMinSize())) {
  686. // If not loading a power-of-2 number of bits, expand as two loads.
  687. assert(!SrcVT.isVector() && "Unsupported extload!");
  688. unsigned SrcWidthBits = SrcWidth.getFixedSize();
  689. unsigned LogSrcWidth = Log2_32(SrcWidthBits);
  690. assert(LogSrcWidth < 32);
  691. unsigned RoundWidth = 1 << LogSrcWidth;
  692. assert(RoundWidth < SrcWidthBits);
  693. unsigned ExtraWidth = SrcWidthBits - RoundWidth;
  694. assert(ExtraWidth < RoundWidth);
  695. assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
  696. "Load size not an integral number of bytes!");
  697. EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
  698. EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
  699. SDValue Lo, Hi, Ch;
  700. unsigned IncrementSize;
  701. auto &DL = DAG.getDataLayout();
  702. if (DL.isLittleEndian()) {
  703. // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
  704. // Load the bottom RoundWidth bits.
  705. Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
  706. LD->getPointerInfo(), RoundVT, LD->getOriginalAlign(),
  707. MMOFlags, AAInfo);
  708. // Load the remaining ExtraWidth bits.
  709. IncrementSize = RoundWidth / 8;
  710. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(IncrementSize), dl);
  711. Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
  712. LD->getPointerInfo().getWithOffset(IncrementSize),
  713. ExtraVT, LD->getOriginalAlign(), MMOFlags, AAInfo);
  714. // Build a factor node to remember that this load is independent of
  715. // the other one.
  716. Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
  717. Hi.getValue(1));
  718. // Move the top bits to the right place.
  719. Hi = DAG.getNode(
  720. ISD::SHL, dl, Hi.getValueType(), Hi,
  721. DAG.getConstant(RoundWidth, dl,
  722. TLI.getShiftAmountTy(Hi.getValueType(), DL)));
  723. // Join the hi and lo parts.
  724. Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
  725. } else {
  726. // Big endian - avoid unaligned loads.
  727. // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
  728. // Load the top RoundWidth bits.
  729. Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
  730. LD->getPointerInfo(), RoundVT, LD->getOriginalAlign(),
  731. MMOFlags, AAInfo);
  732. // Load the remaining ExtraWidth bits.
  733. IncrementSize = RoundWidth / 8;
  734. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(IncrementSize), dl);
  735. Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
  736. LD->getPointerInfo().getWithOffset(IncrementSize),
  737. ExtraVT, LD->getOriginalAlign(), MMOFlags, AAInfo);
  738. // Build a factor node to remember that this load is independent of
  739. // the other one.
  740. Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
  741. Hi.getValue(1));
  742. // Move the top bits to the right place.
  743. Hi = DAG.getNode(
  744. ISD::SHL, dl, Hi.getValueType(), Hi,
  745. DAG.getConstant(ExtraWidth, dl,
  746. TLI.getShiftAmountTy(Hi.getValueType(), DL)));
  747. // Join the hi and lo parts.
  748. Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
  749. }
  750. Chain = Ch;
  751. } else {
  752. bool isCustom = false;
  753. switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0),
  754. SrcVT.getSimpleVT())) {
  755. default: llvm_unreachable("This action is not supported yet!");
  756. case TargetLowering::Custom:
  757. isCustom = true;
  758. LLVM_FALLTHROUGH;
  759. case TargetLowering::Legal:
  760. Value = SDValue(Node, 0);
  761. Chain = SDValue(Node, 1);
  762. if (isCustom) {
  763. if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
  764. Value = Res;
  765. Chain = Res.getValue(1);
  766. }
  767. } else {
  768. // If this is an unaligned load and the target doesn't support it,
  769. // expand it.
  770. EVT MemVT = LD->getMemoryVT();
  771. const DataLayout &DL = DAG.getDataLayout();
  772. if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
  773. *LD->getMemOperand())) {
  774. std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG);
  775. }
  776. }
  777. break;
  778. case TargetLowering::Expand: {
  779. EVT DestVT = Node->getValueType(0);
  780. if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) {
  781. // If the source type is not legal, see if there is a legal extload to
  782. // an intermediate type that we can then extend further.
  783. EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT());
  784. if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
  785. TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) {
  786. // If we are loading a legal type, this is a non-extload followed by a
  787. // full extend.
  788. ISD::LoadExtType MidExtType =
  789. (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
  790. SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
  791. SrcVT, LD->getMemOperand());
  792. unsigned ExtendOp =
  793. ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType);
  794. Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
  795. Chain = Load.getValue(1);
  796. break;
  797. }
  798. // Handle the special case of fp16 extloads. EXTLOAD doesn't have the
  799. // normal undefined upper bits behavior to allow using an in-reg extend
  800. // with the illegal FP type, so load as an integer and do the
  801. // from-integer conversion.
  802. if (SrcVT.getScalarType() == MVT::f16) {
  803. EVT ISrcVT = SrcVT.changeTypeToInteger();
  804. EVT IDestVT = DestVT.changeTypeToInteger();
  805. EVT ILoadVT = TLI.getRegisterType(IDestVT.getSimpleVT());
  806. SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, ILoadVT, Chain,
  807. Ptr, ISrcVT, LD->getMemOperand());
  808. Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result);
  809. Chain = Result.getValue(1);
  810. break;
  811. }
  812. }
  813. assert(!SrcVT.isVector() &&
  814. "Vector Loads are handled in LegalizeVectorOps");
  815. // FIXME: This does not work for vectors on most targets. Sign-
  816. // and zero-extend operations are currently folded into extending
  817. // loads, whether they are legal or not, and then we end up here
  818. // without any support for legalizing them.
  819. assert(ExtType != ISD::EXTLOAD &&
  820. "EXTLOAD should always be supported!");
  821. // Turn the unsupported load into an EXTLOAD followed by an
  822. // explicit zero/sign extend inreg.
  823. SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
  824. Node->getValueType(0),
  825. Chain, Ptr, SrcVT,
  826. LD->getMemOperand());
  827. SDValue ValRes;
  828. if (ExtType == ISD::SEXTLOAD)
  829. ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
  830. Result.getValueType(),
  831. Result, DAG.getValueType(SrcVT));
  832. else
  833. ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
  834. Value = ValRes;
  835. Chain = Result.getValue(1);
  836. break;
  837. }
  838. }
  839. }
  840. // Since loads produce two values, make sure to remember that we legalized
  841. // both of them.
  842. if (Chain.getNode() != Node) {
  843. assert(Value.getNode() != Node && "Load must be completely replaced");
  844. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
  845. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
  846. if (UpdatedNodes) {
  847. UpdatedNodes->insert(Value.getNode());
  848. UpdatedNodes->insert(Chain.getNode());
  849. }
  850. ReplacedNode(Node);
  851. }
  852. }
  853. /// Return a legal replacement for the given operation, with all legal operands.
  854. void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
  855. LLVM_DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
  856. // Allow illegal target nodes and illegal registers.
  857. if (Node->getOpcode() == ISD::TargetConstant ||
  858. Node->getOpcode() == ISD::Register)
  859. return;
  860. #ifndef NDEBUG
  861. for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
  862. assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
  863. TargetLowering::TypeLegal &&
  864. "Unexpected illegal type!");
  865. for (const SDValue &Op : Node->op_values())
  866. assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) ==
  867. TargetLowering::TypeLegal ||
  868. Op.getOpcode() == ISD::TargetConstant ||
  869. Op.getOpcode() == ISD::Register) &&
  870. "Unexpected illegal type!");
  871. #endif
  872. // Figure out the correct action; the way to query this varies by opcode
  873. TargetLowering::LegalizeAction Action = TargetLowering::Legal;
  874. bool SimpleFinishLegalizing = true;
  875. switch (Node->getOpcode()) {
  876. case ISD::INTRINSIC_W_CHAIN:
  877. case ISD::INTRINSIC_WO_CHAIN:
  878. case ISD::INTRINSIC_VOID:
  879. case ISD::STACKSAVE:
  880. Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
  881. break;
  882. case ISD::GET_DYNAMIC_AREA_OFFSET:
  883. Action = TLI.getOperationAction(Node->getOpcode(),
  884. Node->getValueType(0));
  885. break;
  886. case ISD::VAARG:
  887. Action = TLI.getOperationAction(Node->getOpcode(),
  888. Node->getValueType(0));
  889. if (Action != TargetLowering::Promote)
  890. Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
  891. break;
  892. case ISD::FP_TO_FP16:
  893. case ISD::SINT_TO_FP:
  894. case ISD::UINT_TO_FP:
  895. case ISD::EXTRACT_VECTOR_ELT:
  896. case ISD::LROUND:
  897. case ISD::LLROUND:
  898. case ISD::LRINT:
  899. case ISD::LLRINT:
  900. Action = TLI.getOperationAction(Node->getOpcode(),
  901. Node->getOperand(0).getValueType());
  902. break;
  903. case ISD::STRICT_FP_TO_FP16:
  904. case ISD::STRICT_SINT_TO_FP:
  905. case ISD::STRICT_UINT_TO_FP:
  906. case ISD::STRICT_LRINT:
  907. case ISD::STRICT_LLRINT:
  908. case ISD::STRICT_LROUND:
  909. case ISD::STRICT_LLROUND:
  910. // These pseudo-ops are the same as the other STRICT_ ops except
  911. // they are registered with setOperationAction() using the input type
  912. // instead of the output type.
  913. Action = TLI.getOperationAction(Node->getOpcode(),
  914. Node->getOperand(1).getValueType());
  915. break;
  916. case ISD::SIGN_EXTEND_INREG: {
  917. EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
  918. Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
  919. break;
  920. }
  921. case ISD::ATOMIC_STORE:
  922. Action = TLI.getOperationAction(Node->getOpcode(),
  923. Node->getOperand(2).getValueType());
  924. break;
  925. case ISD::SELECT_CC:
  926. case ISD::STRICT_FSETCC:
  927. case ISD::STRICT_FSETCCS:
  928. case ISD::SETCC:
  929. case ISD::BR_CC: {
  930. unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
  931. Node->getOpcode() == ISD::STRICT_FSETCC ? 3 :
  932. Node->getOpcode() == ISD::STRICT_FSETCCS ? 3 :
  933. Node->getOpcode() == ISD::SETCC ? 2 : 1;
  934. unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 :
  935. Node->getOpcode() == ISD::STRICT_FSETCC ? 1 :
  936. Node->getOpcode() == ISD::STRICT_FSETCCS ? 1 : 0;
  937. MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
  938. ISD::CondCode CCCode =
  939. cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
  940. Action = TLI.getCondCodeAction(CCCode, OpVT);
  941. if (Action == TargetLowering::Legal) {
  942. if (Node->getOpcode() == ISD::SELECT_CC)
  943. Action = TLI.getOperationAction(Node->getOpcode(),
  944. Node->getValueType(0));
  945. else
  946. Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
  947. }
  948. break;
  949. }
  950. case ISD::LOAD:
  951. case ISD::STORE:
  952. // FIXME: Model these properly. LOAD and STORE are complicated, and
  953. // STORE expects the unlegalized operand in some cases.
  954. SimpleFinishLegalizing = false;
  955. break;
  956. case ISD::CALLSEQ_START:
  957. case ISD::CALLSEQ_END:
  958. // FIXME: This shouldn't be necessary. These nodes have special properties
  959. // dealing with the recursive nature of legalization. Removing this
  960. // special case should be done as part of making LegalizeDAG non-recursive.
  961. SimpleFinishLegalizing = false;
  962. break;
  963. case ISD::EXTRACT_ELEMENT:
  964. case ISD::FLT_ROUNDS_:
  965. case ISD::MERGE_VALUES:
  966. case ISD::EH_RETURN:
  967. case ISD::FRAME_TO_ARGS_OFFSET:
  968. case ISD::EH_DWARF_CFA:
  969. case ISD::EH_SJLJ_SETJMP:
  970. case ISD::EH_SJLJ_LONGJMP:
  971. case ISD::EH_SJLJ_SETUP_DISPATCH:
  972. // These operations lie about being legal: when they claim to be legal,
  973. // they should actually be expanded.
  974. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  975. if (Action == TargetLowering::Legal)
  976. Action = TargetLowering::Expand;
  977. break;
  978. case ISD::INIT_TRAMPOLINE:
  979. case ISD::ADJUST_TRAMPOLINE:
  980. case ISD::FRAMEADDR:
  981. case ISD::RETURNADDR:
  982. case ISD::ADDROFRETURNADDR:
  983. case ISD::SPONENTRY:
  984. // These operations lie about being legal: when they claim to be legal,
  985. // they should actually be custom-lowered.
  986. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  987. if (Action == TargetLowering::Legal)
  988. Action = TargetLowering::Custom;
  989. break;
  990. case ISD::READCYCLECOUNTER:
  991. // READCYCLECOUNTER returns an i64, even if type legalization might have
  992. // expanded that to several smaller types.
  993. Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64);
  994. break;
  995. case ISD::READ_REGISTER:
  996. case ISD::WRITE_REGISTER:
  997. // Named register is legal in the DAG, but blocked by register name
  998. // selection if not implemented by target (to chose the correct register)
  999. // They'll be converted to Copy(To/From)Reg.
  1000. Action = TargetLowering::Legal;
  1001. break;
  1002. case ISD::UBSANTRAP:
  1003. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  1004. if (Action == TargetLowering::Expand) {
  1005. // replace ISD::UBSANTRAP with ISD::TRAP
  1006. SDValue NewVal;
  1007. NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
  1008. Node->getOperand(0));
  1009. ReplaceNode(Node, NewVal.getNode());
  1010. LegalizeOp(NewVal.getNode());
  1011. return;
  1012. }
  1013. break;
  1014. case ISD::DEBUGTRAP:
  1015. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  1016. if (Action == TargetLowering::Expand) {
  1017. // replace ISD::DEBUGTRAP with ISD::TRAP
  1018. SDValue NewVal;
  1019. NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
  1020. Node->getOperand(0));
  1021. ReplaceNode(Node, NewVal.getNode());
  1022. LegalizeOp(NewVal.getNode());
  1023. return;
  1024. }
  1025. break;
  1026. case ISD::SADDSAT:
  1027. case ISD::UADDSAT:
  1028. case ISD::SSUBSAT:
  1029. case ISD::USUBSAT:
  1030. case ISD::SSHLSAT:
  1031. case ISD::USHLSAT:
  1032. case ISD::FP_TO_SINT_SAT:
  1033. case ISD::FP_TO_UINT_SAT:
  1034. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  1035. break;
  1036. case ISD::SMULFIX:
  1037. case ISD::SMULFIXSAT:
  1038. case ISD::UMULFIX:
  1039. case ISD::UMULFIXSAT:
  1040. case ISD::SDIVFIX:
  1041. case ISD::SDIVFIXSAT:
  1042. case ISD::UDIVFIX:
  1043. case ISD::UDIVFIXSAT: {
  1044. unsigned Scale = Node->getConstantOperandVal(2);
  1045. Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
  1046. Node->getValueType(0), Scale);
  1047. break;
  1048. }
  1049. case ISD::MSCATTER:
  1050. Action = TLI.getOperationAction(Node->getOpcode(),
  1051. cast<MaskedScatterSDNode>(Node)->getValue().getValueType());
  1052. break;
  1053. case ISD::MSTORE:
  1054. Action = TLI.getOperationAction(Node->getOpcode(),
  1055. cast<MaskedStoreSDNode>(Node)->getValue().getValueType());
  1056. break;
  1057. case ISD::VP_SCATTER:
  1058. Action = TLI.getOperationAction(
  1059. Node->getOpcode(),
  1060. cast<VPScatterSDNode>(Node)->getValue().getValueType());
  1061. break;
  1062. case ISD::VP_STORE:
  1063. Action = TLI.getOperationAction(
  1064. Node->getOpcode(),
  1065. cast<VPStoreSDNode>(Node)->getValue().getValueType());
  1066. break;
  1067. case ISD::VECREDUCE_FADD:
  1068. case ISD::VECREDUCE_FMUL:
  1069. case ISD::VECREDUCE_ADD:
  1070. case ISD::VECREDUCE_MUL:
  1071. case ISD::VECREDUCE_AND:
  1072. case ISD::VECREDUCE_OR:
  1073. case ISD::VECREDUCE_XOR:
  1074. case ISD::VECREDUCE_SMAX:
  1075. case ISD::VECREDUCE_SMIN:
  1076. case ISD::VECREDUCE_UMAX:
  1077. case ISD::VECREDUCE_UMIN:
  1078. case ISD::VECREDUCE_FMAX:
  1079. case ISD::VECREDUCE_FMIN:
  1080. Action = TLI.getOperationAction(
  1081. Node->getOpcode(), Node->getOperand(0).getValueType());
  1082. break;
  1083. case ISD::VECREDUCE_SEQ_FADD:
  1084. case ISD::VECREDUCE_SEQ_FMUL:
  1085. case ISD::VP_REDUCE_FADD:
  1086. case ISD::VP_REDUCE_FMUL:
  1087. case ISD::VP_REDUCE_ADD:
  1088. case ISD::VP_REDUCE_MUL:
  1089. case ISD::VP_REDUCE_AND:
  1090. case ISD::VP_REDUCE_OR:
  1091. case ISD::VP_REDUCE_XOR:
  1092. case ISD::VP_REDUCE_SMAX:
  1093. case ISD::VP_REDUCE_SMIN:
  1094. case ISD::VP_REDUCE_UMAX:
  1095. case ISD::VP_REDUCE_UMIN:
  1096. case ISD::VP_REDUCE_FMAX:
  1097. case ISD::VP_REDUCE_FMIN:
  1098. case ISD::VP_REDUCE_SEQ_FADD:
  1099. case ISD::VP_REDUCE_SEQ_FMUL:
  1100. Action = TLI.getOperationAction(
  1101. Node->getOpcode(), Node->getOperand(1).getValueType());
  1102. break;
  1103. default:
  1104. if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
  1105. Action = TargetLowering::Legal;
  1106. } else {
  1107. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  1108. }
  1109. break;
  1110. }
  1111. if (SimpleFinishLegalizing) {
  1112. SDNode *NewNode = Node;
  1113. switch (Node->getOpcode()) {
  1114. default: break;
  1115. case ISD::SHL:
  1116. case ISD::SRL:
  1117. case ISD::SRA:
  1118. case ISD::ROTL:
  1119. case ISD::ROTR: {
  1120. // Legalizing shifts/rotates requires adjusting the shift amount
  1121. // to the appropriate width.
  1122. SDValue Op0 = Node->getOperand(0);
  1123. SDValue Op1 = Node->getOperand(1);
  1124. if (!Op1.getValueType().isVector()) {
  1125. SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1);
  1126. // The getShiftAmountOperand() may create a new operand node or
  1127. // return the existing one. If new operand is created we need
  1128. // to update the parent node.
  1129. // Do not try to legalize SAO here! It will be automatically legalized
  1130. // in the next round.
  1131. if (SAO != Op1)
  1132. NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO);
  1133. }
  1134. }
  1135. break;
  1136. case ISD::FSHL:
  1137. case ISD::FSHR:
  1138. case ISD::SRL_PARTS:
  1139. case ISD::SRA_PARTS:
  1140. case ISD::SHL_PARTS: {
  1141. // Legalizing shifts/rotates requires adjusting the shift amount
  1142. // to the appropriate width.
  1143. SDValue Op0 = Node->getOperand(0);
  1144. SDValue Op1 = Node->getOperand(1);
  1145. SDValue Op2 = Node->getOperand(2);
  1146. if (!Op2.getValueType().isVector()) {
  1147. SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2);
  1148. // The getShiftAmountOperand() may create a new operand node or
  1149. // return the existing one. If new operand is created we need
  1150. // to update the parent node.
  1151. if (SAO != Op2)
  1152. NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO);
  1153. }
  1154. break;
  1155. }
  1156. }
  1157. if (NewNode != Node) {
  1158. ReplaceNode(Node, NewNode);
  1159. Node = NewNode;
  1160. }
  1161. switch (Action) {
  1162. case TargetLowering::Legal:
  1163. LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
  1164. return;
  1165. case TargetLowering::Custom:
  1166. LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
  1167. // FIXME: The handling for custom lowering with multiple results is
  1168. // a complete mess.
  1169. if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
  1170. if (!(Res.getNode() != Node || Res.getResNo() != 0))
  1171. return;
  1172. if (Node->getNumValues() == 1) {
  1173. // Verify the new types match the original. Glue is waived because
  1174. // ISD::ADDC can be legalized by replacing Glue with an integer type.
  1175. assert((Res.getValueType() == Node->getValueType(0) ||
  1176. Node->getValueType(0) == MVT::Glue) &&
  1177. "Type mismatch for custom legalized operation");
  1178. LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
  1179. // We can just directly replace this node with the lowered value.
  1180. ReplaceNode(SDValue(Node, 0), Res);
  1181. return;
  1182. }
  1183. SmallVector<SDValue, 8> ResultVals;
  1184. for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
  1185. // Verify the new types match the original. Glue is waived because
  1186. // ISD::ADDC can be legalized by replacing Glue with an integer type.
  1187. assert((Res->getValueType(i) == Node->getValueType(i) ||
  1188. Node->getValueType(i) == MVT::Glue) &&
  1189. "Type mismatch for custom legalized operation");
  1190. ResultVals.push_back(Res.getValue(i));
  1191. }
  1192. LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
  1193. ReplaceNode(Node, ResultVals.data());
  1194. return;
  1195. }
  1196. LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
  1197. LLVM_FALLTHROUGH;
  1198. case TargetLowering::Expand:
  1199. if (ExpandNode(Node))
  1200. return;
  1201. LLVM_FALLTHROUGH;
  1202. case TargetLowering::LibCall:
  1203. ConvertNodeToLibcall(Node);
  1204. return;
  1205. case TargetLowering::Promote:
  1206. PromoteNode(Node);
  1207. return;
  1208. }
  1209. }
  1210. switch (Node->getOpcode()) {
  1211. default:
  1212. #ifndef NDEBUG
  1213. dbgs() << "NODE: ";
  1214. Node->dump( &DAG);
  1215. dbgs() << "\n";
  1216. #endif
  1217. llvm_unreachable("Do not know how to legalize this operator!");
  1218. case ISD::CALLSEQ_START:
  1219. case ISD::CALLSEQ_END:
  1220. break;
  1221. case ISD::LOAD:
  1222. return LegalizeLoadOps(Node);
  1223. case ISD::STORE:
  1224. return LegalizeStoreOps(Node);
  1225. }
  1226. }
  1227. SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
  1228. SDValue Vec = Op.getOperand(0);
  1229. SDValue Idx = Op.getOperand(1);
  1230. SDLoc dl(Op);
  1231. // Before we generate a new store to a temporary stack slot, see if there is
  1232. // already one that we can use. There often is because when we scalarize
  1233. // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
  1234. // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
  1235. // the vector. If all are expanded here, we don't want one store per vector
  1236. // element.
  1237. // Caches for hasPredecessorHelper
  1238. SmallPtrSet<const SDNode *, 32> Visited;
  1239. SmallVector<const SDNode *, 16> Worklist;
  1240. Visited.insert(Op.getNode());
  1241. Worklist.push_back(Idx.getNode());
  1242. SDValue StackPtr, Ch;
  1243. for (SDNode *User : Vec.getNode()->uses()) {
  1244. if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
  1245. if (ST->isIndexed() || ST->isTruncatingStore() ||
  1246. ST->getValue() != Vec)
  1247. continue;
  1248. // Make sure that nothing else could have stored into the destination of
  1249. // this store.
  1250. if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
  1251. continue;
  1252. // If the index is dependent on the store we will introduce a cycle when
  1253. // creating the load (the load uses the index, and by replacing the chain
  1254. // we will make the index dependent on the load). Also, the store might be
  1255. // dependent on the extractelement and introduce a cycle when creating
  1256. // the load.
  1257. if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) ||
  1258. ST->hasPredecessor(Op.getNode()))
  1259. continue;
  1260. StackPtr = ST->getBasePtr();
  1261. Ch = SDValue(ST, 0);
  1262. break;
  1263. }
  1264. }
  1265. EVT VecVT = Vec.getValueType();
  1266. if (!Ch.getNode()) {
  1267. // Store the value to a temporary stack slot, then LOAD the returned part.
  1268. StackPtr = DAG.CreateStackTemporary(VecVT);
  1269. Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
  1270. MachinePointerInfo());
  1271. }
  1272. SDValue NewLoad;
  1273. if (Op.getValueType().isVector()) {
  1274. StackPtr = TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT,
  1275. Op.getValueType(), Idx);
  1276. NewLoad =
  1277. DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo());
  1278. } else {
  1279. StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
  1280. NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
  1281. MachinePointerInfo(),
  1282. VecVT.getVectorElementType());
  1283. }
  1284. // Replace the chain going out of the store, by the one out of the load.
  1285. DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
  1286. // We introduced a cycle though, so update the loads operands, making sure
  1287. // to use the original store's chain as an incoming chain.
  1288. SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(),
  1289. NewLoad->op_end());
  1290. NewLoadOperands[0] = Ch;
  1291. NewLoad =
  1292. SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
  1293. return NewLoad;
  1294. }
  1295. SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
  1296. assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
  1297. SDValue Vec = Op.getOperand(0);
  1298. SDValue Part = Op.getOperand(1);
  1299. SDValue Idx = Op.getOperand(2);
  1300. SDLoc dl(Op);
  1301. // Store the value to a temporary stack slot, then LOAD the returned part.
  1302. EVT VecVT = Vec.getValueType();
  1303. EVT SubVecVT = Part.getValueType();
  1304. SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
  1305. int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
  1306. MachinePointerInfo PtrInfo =
  1307. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
  1308. // First store the whole vector.
  1309. SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo);
  1310. // Then store the inserted part.
  1311. SDValue SubStackPtr =
  1312. TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT, SubVecVT, Idx);
  1313. // Store the subvector.
  1314. Ch = DAG.getStore(
  1315. Ch, dl, Part, SubStackPtr,
  1316. MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1317. // Finally, load the updated vector.
  1318. return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo);
  1319. }
  1320. SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
  1321. assert((Node->getOpcode() == ISD::BUILD_VECTOR ||
  1322. Node->getOpcode() == ISD::CONCAT_VECTORS) &&
  1323. "Unexpected opcode!");
  1324. // We can't handle this case efficiently. Allocate a sufficiently
  1325. // aligned object on the stack, store each operand into it, then load
  1326. // the result as a vector.
  1327. // Create the stack frame object.
  1328. EVT VT = Node->getValueType(0);
  1329. EVT MemVT = isa<BuildVectorSDNode>(Node) ? VT.getVectorElementType()
  1330. : Node->getOperand(0).getValueType();
  1331. SDLoc dl(Node);
  1332. SDValue FIPtr = DAG.CreateStackTemporary(VT);
  1333. int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
  1334. MachinePointerInfo PtrInfo =
  1335. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
  1336. // Emit a store of each element to the stack slot.
  1337. SmallVector<SDValue, 8> Stores;
  1338. unsigned TypeByteSize = MemVT.getSizeInBits() / 8;
  1339. assert(TypeByteSize > 0 && "Vector element type too small for stack store!");
  1340. // If the destination vector element type of a BUILD_VECTOR is narrower than
  1341. // the source element type, only store the bits necessary.
  1342. bool Truncate = isa<BuildVectorSDNode>(Node) &&
  1343. MemVT.bitsLT(Node->getOperand(0).getValueType());
  1344. // Store (in the right endianness) the elements to memory.
  1345. for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
  1346. // Ignore undef elements.
  1347. if (Node->getOperand(i).isUndef()) continue;
  1348. unsigned Offset = TypeByteSize*i;
  1349. SDValue Idx = DAG.getMemBasePlusOffset(FIPtr, TypeSize::Fixed(Offset), dl);
  1350. if (Truncate)
  1351. Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
  1352. Node->getOperand(i), Idx,
  1353. PtrInfo.getWithOffset(Offset), MemVT));
  1354. else
  1355. Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
  1356. Idx, PtrInfo.getWithOffset(Offset)));
  1357. }
  1358. SDValue StoreChain;
  1359. if (!Stores.empty()) // Not all undef elements?
  1360. StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
  1361. else
  1362. StoreChain = DAG.getEntryNode();
  1363. // Result is a load from the stack slot.
  1364. return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo);
  1365. }
  1366. /// Bitcast a floating-point value to an integer value. Only bitcast the part
  1367. /// containing the sign bit if the target has no integer value capable of
  1368. /// holding all bits of the floating-point value.
  1369. void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State,
  1370. const SDLoc &DL,
  1371. SDValue Value) const {
  1372. EVT FloatVT = Value.getValueType();
  1373. unsigned NumBits = FloatVT.getScalarSizeInBits();
  1374. State.FloatVT = FloatVT;
  1375. EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
  1376. // Convert to an integer of the same size.
  1377. if (TLI.isTypeLegal(IVT)) {
  1378. State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value);
  1379. State.SignMask = APInt::getSignMask(NumBits);
  1380. State.SignBit = NumBits - 1;
  1381. return;
  1382. }
  1383. auto &DataLayout = DAG.getDataLayout();
  1384. // Store the float to memory, then load the sign part out as an integer.
  1385. MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8);
  1386. // First create a temporary that is aligned for both the load and store.
  1387. SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
  1388. int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
  1389. // Then store the float to it.
  1390. State.FloatPtr = StackPtr;
  1391. MachineFunction &MF = DAG.getMachineFunction();
  1392. State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI);
  1393. State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr,
  1394. State.FloatPointerInfo);
  1395. SDValue IntPtr;
  1396. if (DataLayout.isBigEndian()) {
  1397. assert(FloatVT.isByteSized() && "Unsupported floating point type!");
  1398. // Load out a legal integer with the same sign bit as the float.
  1399. IntPtr = StackPtr;
  1400. State.IntPointerInfo = State.FloatPointerInfo;
  1401. } else {
  1402. // Advance the pointer so that the loaded byte will contain the sign bit.
  1403. unsigned ByteOffset = (NumBits / 8) - 1;
  1404. IntPtr =
  1405. DAG.getMemBasePlusOffset(StackPtr, TypeSize::Fixed(ByteOffset), DL);
  1406. State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI,
  1407. ByteOffset);
  1408. }
  1409. State.IntPtr = IntPtr;
  1410. State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr,
  1411. State.IntPointerInfo, MVT::i8);
  1412. State.SignMask = APInt::getOneBitSet(LoadTy.getScalarSizeInBits(), 7);
  1413. State.SignBit = 7;
  1414. }
  1415. /// Replace the integer value produced by getSignAsIntValue() with a new value
  1416. /// and cast the result back to a floating-point type.
  1417. SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State,
  1418. const SDLoc &DL,
  1419. SDValue NewIntValue) const {
  1420. if (!State.Chain)
  1421. return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue);
  1422. // Override the part containing the sign bit in the value stored on the stack.
  1423. SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr,
  1424. State.IntPointerInfo, MVT::i8);
  1425. return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr,
  1426. State.FloatPointerInfo);
  1427. }
  1428. SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const {
  1429. SDLoc DL(Node);
  1430. SDValue Mag = Node->getOperand(0);
  1431. SDValue Sign = Node->getOperand(1);
  1432. // Get sign bit into an integer value.
  1433. FloatSignAsInt SignAsInt;
  1434. getSignAsIntValue(SignAsInt, DL, Sign);
  1435. EVT IntVT = SignAsInt.IntValue.getValueType();
  1436. SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
  1437. SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue,
  1438. SignMask);
  1439. // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X)
  1440. EVT FloatVT = Mag.getValueType();
  1441. if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) &&
  1442. TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) {
  1443. SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag);
  1444. SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue);
  1445. SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit,
  1446. DAG.getConstant(0, DL, IntVT), ISD::SETNE);
  1447. return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue);
  1448. }
  1449. // Transform Mag value to integer, and clear the sign bit.
  1450. FloatSignAsInt MagAsInt;
  1451. getSignAsIntValue(MagAsInt, DL, Mag);
  1452. EVT MagVT = MagAsInt.IntValue.getValueType();
  1453. SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT);
  1454. SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue,
  1455. ClearSignMask);
  1456. // Get the signbit at the right position for MagAsInt.
  1457. int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit;
  1458. EVT ShiftVT = IntVT;
  1459. if (SignBit.getScalarValueSizeInBits() <
  1460. ClearedSign.getScalarValueSizeInBits()) {
  1461. SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit);
  1462. ShiftVT = MagVT;
  1463. }
  1464. if (ShiftAmount > 0) {
  1465. SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT);
  1466. SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst);
  1467. } else if (ShiftAmount < 0) {
  1468. SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT);
  1469. SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst);
  1470. }
  1471. if (SignBit.getScalarValueSizeInBits() >
  1472. ClearedSign.getScalarValueSizeInBits()) {
  1473. SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit);
  1474. }
  1475. // Store the part with the modified sign and convert back to float.
  1476. SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit);
  1477. return modifySignAsInt(MagAsInt, DL, CopiedSign);
  1478. }
  1479. SDValue SelectionDAGLegalize::ExpandFNEG(SDNode *Node) const {
  1480. // Get the sign bit as an integer.
  1481. SDLoc DL(Node);
  1482. FloatSignAsInt SignAsInt;
  1483. getSignAsIntValue(SignAsInt, DL, Node->getOperand(0));
  1484. EVT IntVT = SignAsInt.IntValue.getValueType();
  1485. // Flip the sign.
  1486. SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
  1487. SDValue SignFlip =
  1488. DAG.getNode(ISD::XOR, DL, IntVT, SignAsInt.IntValue, SignMask);
  1489. // Convert back to float.
  1490. return modifySignAsInt(SignAsInt, DL, SignFlip);
  1491. }
  1492. SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const {
  1493. SDLoc DL(Node);
  1494. SDValue Value = Node->getOperand(0);
  1495. // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal.
  1496. EVT FloatVT = Value.getValueType();
  1497. if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) {
  1498. SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT);
  1499. return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero);
  1500. }
  1501. // Transform value to integer, clear the sign bit and transform back.
  1502. FloatSignAsInt ValueAsInt;
  1503. getSignAsIntValue(ValueAsInt, DL, Value);
  1504. EVT IntVT = ValueAsInt.IntValue.getValueType();
  1505. SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT);
  1506. SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue,
  1507. ClearSignMask);
  1508. return modifySignAsInt(ValueAsInt, DL, ClearedSign);
  1509. }
  1510. void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
  1511. SmallVectorImpl<SDValue> &Results) {
  1512. Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
  1513. assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
  1514. " not tell us which reg is the stack pointer!");
  1515. SDLoc dl(Node);
  1516. EVT VT = Node->getValueType(0);
  1517. SDValue Tmp1 = SDValue(Node, 0);
  1518. SDValue Tmp2 = SDValue(Node, 1);
  1519. SDValue Tmp3 = Node->getOperand(2);
  1520. SDValue Chain = Tmp1.getOperand(0);
  1521. // Chain the dynamic stack allocation so that it doesn't modify the stack
  1522. // pointer when other instructions are using the stack.
  1523. Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
  1524. SDValue Size = Tmp2.getOperand(1);
  1525. SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
  1526. Chain = SP.getValue(1);
  1527. Align Alignment = cast<ConstantSDNode>(Tmp3)->getAlignValue();
  1528. const TargetFrameLowering *TFL = DAG.getSubtarget().getFrameLowering();
  1529. unsigned Opc =
  1530. TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
  1531. ISD::ADD : ISD::SUB;
  1532. Align StackAlign = TFL->getStackAlign();
  1533. Tmp1 = DAG.getNode(Opc, dl, VT, SP, Size); // Value
  1534. if (Alignment > StackAlign)
  1535. Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
  1536. DAG.getConstant(-Alignment.value(), dl, VT));
  1537. Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
  1538. Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
  1539. DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
  1540. Results.push_back(Tmp1);
  1541. Results.push_back(Tmp2);
  1542. }
  1543. /// Emit a store/load combination to the stack. This stores
  1544. /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
  1545. /// a load from the stack slot to DestVT, extending it if needed.
  1546. /// The resultant code need not be legal.
  1547. SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
  1548. EVT DestVT, const SDLoc &dl) {
  1549. return EmitStackConvert(SrcOp, SlotVT, DestVT, dl, DAG.getEntryNode());
  1550. }
  1551. SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
  1552. EVT DestVT, const SDLoc &dl,
  1553. SDValue Chain) {
  1554. unsigned SrcSize = SrcOp.getValueSizeInBits();
  1555. unsigned SlotSize = SlotVT.getSizeInBits();
  1556. unsigned DestSize = DestVT.getSizeInBits();
  1557. Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
  1558. Align DestAlign = DAG.getDataLayout().getPrefTypeAlign(DestType);
  1559. // Don't convert with stack if the load/store is expensive.
  1560. if ((SrcSize > SlotSize &&
  1561. !TLI.isTruncStoreLegalOrCustom(SrcOp.getValueType(), SlotVT)) ||
  1562. (SlotSize < DestSize &&
  1563. !TLI.isLoadExtLegalOrCustom(ISD::EXTLOAD, DestVT, SlotVT)))
  1564. return SDValue();
  1565. // Create the stack frame object.
  1566. Align SrcAlign = DAG.getDataLayout().getPrefTypeAlign(
  1567. SrcOp.getValueType().getTypeForEVT(*DAG.getContext()));
  1568. SDValue FIPtr = DAG.CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign);
  1569. FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
  1570. int SPFI = StackPtrFI->getIndex();
  1571. MachinePointerInfo PtrInfo =
  1572. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
  1573. // Emit a store to the stack slot. Use a truncstore if the input value is
  1574. // later than DestVT.
  1575. SDValue Store;
  1576. if (SrcSize > SlotSize)
  1577. Store = DAG.getTruncStore(Chain, dl, SrcOp, FIPtr, PtrInfo,
  1578. SlotVT, SrcAlign);
  1579. else {
  1580. assert(SrcSize == SlotSize && "Invalid store");
  1581. Store =
  1582. DAG.getStore(Chain, dl, SrcOp, FIPtr, PtrInfo, SrcAlign);
  1583. }
  1584. // Result is a load from the stack slot.
  1585. if (SlotSize == DestSize)
  1586. return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign);
  1587. assert(SlotSize < DestSize && "Unknown extension!");
  1588. return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT,
  1589. DestAlign);
  1590. }
  1591. SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
  1592. SDLoc dl(Node);
  1593. // Create a vector sized/aligned stack slot, store the value to element #0,
  1594. // then load the whole vector back out.
  1595. SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
  1596. FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
  1597. int SPFI = StackPtrFI->getIndex();
  1598. SDValue Ch = DAG.getTruncStore(
  1599. DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr,
  1600. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI),
  1601. Node->getValueType(0).getVectorElementType());
  1602. return DAG.getLoad(
  1603. Node->getValueType(0), dl, Ch, StackPtr,
  1604. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
  1605. }
  1606. static bool
  1607. ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG,
  1608. const TargetLowering &TLI, SDValue &Res) {
  1609. unsigned NumElems = Node->getNumOperands();
  1610. SDLoc dl(Node);
  1611. EVT VT = Node->getValueType(0);
  1612. // Try to group the scalars into pairs, shuffle the pairs together, then
  1613. // shuffle the pairs of pairs together, etc. until the vector has
  1614. // been built. This will work only if all of the necessary shuffle masks
  1615. // are legal.
  1616. // We do this in two phases; first to check the legality of the shuffles,
  1617. // and next, assuming that all shuffles are legal, to create the new nodes.
  1618. for (int Phase = 0; Phase < 2; ++Phase) {
  1619. SmallVector<std::pair<SDValue, SmallVector<int, 16>>, 16> IntermedVals,
  1620. NewIntermedVals;
  1621. for (unsigned i = 0; i < NumElems; ++i) {
  1622. SDValue V = Node->getOperand(i);
  1623. if (V.isUndef())
  1624. continue;
  1625. SDValue Vec;
  1626. if (Phase)
  1627. Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
  1628. IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
  1629. }
  1630. while (IntermedVals.size() > 2) {
  1631. NewIntermedVals.clear();
  1632. for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
  1633. // This vector and the next vector are shuffled together (simply to
  1634. // append the one to the other).
  1635. SmallVector<int, 16> ShuffleVec(NumElems, -1);
  1636. SmallVector<int, 16> FinalIndices;
  1637. FinalIndices.reserve(IntermedVals[i].second.size() +
  1638. IntermedVals[i+1].second.size());
  1639. int k = 0;
  1640. for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
  1641. ++j, ++k) {
  1642. ShuffleVec[k] = j;
  1643. FinalIndices.push_back(IntermedVals[i].second[j]);
  1644. }
  1645. for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
  1646. ++j, ++k) {
  1647. ShuffleVec[k] = NumElems + j;
  1648. FinalIndices.push_back(IntermedVals[i+1].second[j]);
  1649. }
  1650. SDValue Shuffle;
  1651. if (Phase)
  1652. Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
  1653. IntermedVals[i+1].first,
  1654. ShuffleVec);
  1655. else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
  1656. return false;
  1657. NewIntermedVals.push_back(
  1658. std::make_pair(Shuffle, std::move(FinalIndices)));
  1659. }
  1660. // If we had an odd number of defined values, then append the last
  1661. // element to the array of new vectors.
  1662. if ((IntermedVals.size() & 1) != 0)
  1663. NewIntermedVals.push_back(IntermedVals.back());
  1664. IntermedVals.swap(NewIntermedVals);
  1665. }
  1666. assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
  1667. "Invalid number of intermediate vectors");
  1668. SDValue Vec1 = IntermedVals[0].first;
  1669. SDValue Vec2;
  1670. if (IntermedVals.size() > 1)
  1671. Vec2 = IntermedVals[1].first;
  1672. else if (Phase)
  1673. Vec2 = DAG.getUNDEF(VT);
  1674. SmallVector<int, 16> ShuffleVec(NumElems, -1);
  1675. for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
  1676. ShuffleVec[IntermedVals[0].second[i]] = i;
  1677. for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
  1678. ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
  1679. if (Phase)
  1680. Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
  1681. else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
  1682. return false;
  1683. }
  1684. return true;
  1685. }
  1686. /// Expand a BUILD_VECTOR node on targets that don't
  1687. /// support the operation, but do support the resultant vector type.
  1688. SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
  1689. unsigned NumElems = Node->getNumOperands();
  1690. SDValue Value1, Value2;
  1691. SDLoc dl(Node);
  1692. EVT VT = Node->getValueType(0);
  1693. EVT OpVT = Node->getOperand(0).getValueType();
  1694. EVT EltVT = VT.getVectorElementType();
  1695. // If the only non-undef value is the low element, turn this into a
  1696. // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
  1697. bool isOnlyLowElement = true;
  1698. bool MoreThanTwoValues = false;
  1699. bool isConstant = true;
  1700. for (unsigned i = 0; i < NumElems; ++i) {
  1701. SDValue V = Node->getOperand(i);
  1702. if (V.isUndef())
  1703. continue;
  1704. if (i > 0)
  1705. isOnlyLowElement = false;
  1706. if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
  1707. isConstant = false;
  1708. if (!Value1.getNode()) {
  1709. Value1 = V;
  1710. } else if (!Value2.getNode()) {
  1711. if (V != Value1)
  1712. Value2 = V;
  1713. } else if (V != Value1 && V != Value2) {
  1714. MoreThanTwoValues = true;
  1715. }
  1716. }
  1717. if (!Value1.getNode())
  1718. return DAG.getUNDEF(VT);
  1719. if (isOnlyLowElement)
  1720. return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
  1721. // If all elements are constants, create a load from the constant pool.
  1722. if (isConstant) {
  1723. SmallVector<Constant*, 16> CV;
  1724. for (unsigned i = 0, e = NumElems; i != e; ++i) {
  1725. if (ConstantFPSDNode *V =
  1726. dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
  1727. CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
  1728. } else if (ConstantSDNode *V =
  1729. dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
  1730. if (OpVT==EltVT)
  1731. CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
  1732. else {
  1733. // If OpVT and EltVT don't match, EltVT is not legal and the
  1734. // element values have been promoted/truncated earlier. Undo this;
  1735. // we don't want a v16i8 to become a v16i32 for example.
  1736. const ConstantInt *CI = V->getConstantIntValue();
  1737. CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
  1738. CI->getZExtValue()));
  1739. }
  1740. } else {
  1741. assert(Node->getOperand(i).isUndef());
  1742. Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
  1743. CV.push_back(UndefValue::get(OpNTy));
  1744. }
  1745. }
  1746. Constant *CP = ConstantVector::get(CV);
  1747. SDValue CPIdx =
  1748. DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout()));
  1749. Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
  1750. return DAG.getLoad(
  1751. VT, dl, DAG.getEntryNode(), CPIdx,
  1752. MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
  1753. Alignment);
  1754. }
  1755. SmallSet<SDValue, 16> DefinedValues;
  1756. for (unsigned i = 0; i < NumElems; ++i) {
  1757. if (Node->getOperand(i).isUndef())
  1758. continue;
  1759. DefinedValues.insert(Node->getOperand(i));
  1760. }
  1761. if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
  1762. if (!MoreThanTwoValues) {
  1763. SmallVector<int, 8> ShuffleVec(NumElems, -1);
  1764. for (unsigned i = 0; i < NumElems; ++i) {
  1765. SDValue V = Node->getOperand(i);
  1766. if (V.isUndef())
  1767. continue;
  1768. ShuffleVec[i] = V == Value1 ? 0 : NumElems;
  1769. }
  1770. if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
  1771. // Get the splatted value into the low element of a vector register.
  1772. SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
  1773. SDValue Vec2;
  1774. if (Value2.getNode())
  1775. Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
  1776. else
  1777. Vec2 = DAG.getUNDEF(VT);
  1778. // Return shuffle(LowValVec, undef, <0,0,0,0>)
  1779. return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
  1780. }
  1781. } else {
  1782. SDValue Res;
  1783. if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
  1784. return Res;
  1785. }
  1786. }
  1787. // Otherwise, we can't handle this case efficiently.
  1788. return ExpandVectorBuildThroughStack(Node);
  1789. }
  1790. SDValue SelectionDAGLegalize::ExpandSPLAT_VECTOR(SDNode *Node) {
  1791. SDLoc DL(Node);
  1792. EVT VT = Node->getValueType(0);
  1793. SDValue SplatVal = Node->getOperand(0);
  1794. return DAG.getSplatBuildVector(VT, DL, SplatVal);
  1795. }
  1796. // Expand a node into a call to a libcall. If the result value
  1797. // does not fit into a register, return the lo part and set the hi part to the
  1798. // by-reg argument. If it does fit into a single register, return the result
  1799. // and leave the Hi part unset.
  1800. SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
  1801. bool isSigned) {
  1802. TargetLowering::ArgListTy Args;
  1803. TargetLowering::ArgListEntry Entry;
  1804. for (const SDValue &Op : Node->op_values()) {
  1805. EVT ArgVT = Op.getValueType();
  1806. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  1807. Entry.Node = Op;
  1808. Entry.Ty = ArgTy;
  1809. Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
  1810. Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
  1811. Args.push_back(Entry);
  1812. }
  1813. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  1814. TLI.getPointerTy(DAG.getDataLayout()));
  1815. EVT RetVT = Node->getValueType(0);
  1816. Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
  1817. // By default, the input chain to this libcall is the entry node of the
  1818. // function. If the libcall is going to be emitted as a tail call then
  1819. // TLI.isUsedByReturnOnly will change it to the right chain if the return
  1820. // node which is being folded has a non-entry input chain.
  1821. SDValue InChain = DAG.getEntryNode();
  1822. // isTailCall may be true since the callee does not reference caller stack
  1823. // frame. Check if it's in the right position and that the return types match.
  1824. SDValue TCChain = InChain;
  1825. const Function &F = DAG.getMachineFunction().getFunction();
  1826. bool isTailCall =
  1827. TLI.isInTailCallPosition(DAG, Node, TCChain) &&
  1828. (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
  1829. if (isTailCall)
  1830. InChain = TCChain;
  1831. TargetLowering::CallLoweringInfo CLI(DAG);
  1832. bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned);
  1833. CLI.setDebugLoc(SDLoc(Node))
  1834. .setChain(InChain)
  1835. .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
  1836. std::move(Args))
  1837. .setTailCall(isTailCall)
  1838. .setSExtResult(signExtend)
  1839. .setZExtResult(!signExtend)
  1840. .setIsPostTypeLegalization(true);
  1841. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  1842. if (!CallInfo.second.getNode()) {
  1843. LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump(&DAG));
  1844. // It's a tailcall, return the chain (which is the DAG root).
  1845. return DAG.getRoot();
  1846. }
  1847. LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump(&DAG));
  1848. return CallInfo.first;
  1849. }
  1850. void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
  1851. RTLIB::Libcall LC,
  1852. SmallVectorImpl<SDValue> &Results) {
  1853. if (LC == RTLIB::UNKNOWN_LIBCALL)
  1854. llvm_unreachable("Can't create an unknown libcall!");
  1855. if (Node->isStrictFPOpcode()) {
  1856. EVT RetVT = Node->getValueType(0);
  1857. SmallVector<SDValue, 4> Ops(drop_begin(Node->ops()));
  1858. TargetLowering::MakeLibCallOptions CallOptions;
  1859. // FIXME: This doesn't support tail calls.
  1860. std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT,
  1861. Ops, CallOptions,
  1862. SDLoc(Node),
  1863. Node->getOperand(0));
  1864. Results.push_back(Tmp.first);
  1865. Results.push_back(Tmp.second);
  1866. } else {
  1867. SDValue Tmp = ExpandLibCall(LC, Node, false);
  1868. Results.push_back(Tmp);
  1869. }
  1870. }
  1871. /// Expand the node to a libcall based on the result type.
  1872. void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
  1873. RTLIB::Libcall Call_F32,
  1874. RTLIB::Libcall Call_F64,
  1875. RTLIB::Libcall Call_F80,
  1876. RTLIB::Libcall Call_F128,
  1877. RTLIB::Libcall Call_PPCF128,
  1878. SmallVectorImpl<SDValue> &Results) {
  1879. RTLIB::Libcall LC = RTLIB::getFPLibCall(Node->getSimpleValueType(0),
  1880. Call_F32, Call_F64, Call_F80,
  1881. Call_F128, Call_PPCF128);
  1882. ExpandFPLibCall(Node, LC, Results);
  1883. }
  1884. SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
  1885. RTLIB::Libcall Call_I8,
  1886. RTLIB::Libcall Call_I16,
  1887. RTLIB::Libcall Call_I32,
  1888. RTLIB::Libcall Call_I64,
  1889. RTLIB::Libcall Call_I128) {
  1890. RTLIB::Libcall LC;
  1891. switch (Node->getSimpleValueType(0).SimpleTy) {
  1892. default: llvm_unreachable("Unexpected request for libcall!");
  1893. case MVT::i8: LC = Call_I8; break;
  1894. case MVT::i16: LC = Call_I16; break;
  1895. case MVT::i32: LC = Call_I32; break;
  1896. case MVT::i64: LC = Call_I64; break;
  1897. case MVT::i128: LC = Call_I128; break;
  1898. }
  1899. return ExpandLibCall(LC, Node, isSigned);
  1900. }
  1901. /// Expand the node to a libcall based on first argument type (for instance
  1902. /// lround and its variant).
  1903. void SelectionDAGLegalize::ExpandArgFPLibCall(SDNode* Node,
  1904. RTLIB::Libcall Call_F32,
  1905. RTLIB::Libcall Call_F64,
  1906. RTLIB::Libcall Call_F80,
  1907. RTLIB::Libcall Call_F128,
  1908. RTLIB::Libcall Call_PPCF128,
  1909. SmallVectorImpl<SDValue> &Results) {
  1910. EVT InVT = Node->getOperand(Node->isStrictFPOpcode() ? 1 : 0).getValueType();
  1911. RTLIB::Libcall LC = RTLIB::getFPLibCall(InVT.getSimpleVT(),
  1912. Call_F32, Call_F64, Call_F80,
  1913. Call_F128, Call_PPCF128);
  1914. ExpandFPLibCall(Node, LC, Results);
  1915. }
  1916. /// Issue libcalls to __{u}divmod to compute div / rem pairs.
  1917. void
  1918. SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
  1919. SmallVectorImpl<SDValue> &Results) {
  1920. unsigned Opcode = Node->getOpcode();
  1921. bool isSigned = Opcode == ISD::SDIVREM;
  1922. RTLIB::Libcall LC;
  1923. switch (Node->getSimpleValueType(0).SimpleTy) {
  1924. default: llvm_unreachable("Unexpected request for libcall!");
  1925. case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
  1926. case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
  1927. case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
  1928. case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
  1929. case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
  1930. }
  1931. // The input chain to this libcall is the entry node of the function.
  1932. // Legalizing the call will automatically add the previous call to the
  1933. // dependence.
  1934. SDValue InChain = DAG.getEntryNode();
  1935. EVT RetVT = Node->getValueType(0);
  1936. Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
  1937. TargetLowering::ArgListTy Args;
  1938. TargetLowering::ArgListEntry Entry;
  1939. for (const SDValue &Op : Node->op_values()) {
  1940. EVT ArgVT = Op.getValueType();
  1941. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  1942. Entry.Node = Op;
  1943. Entry.Ty = ArgTy;
  1944. Entry.IsSExt = isSigned;
  1945. Entry.IsZExt = !isSigned;
  1946. Args.push_back(Entry);
  1947. }
  1948. // Also pass the return address of the remainder.
  1949. SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
  1950. Entry.Node = FIPtr;
  1951. Entry.Ty = RetTy->getPointerTo();
  1952. Entry.IsSExt = isSigned;
  1953. Entry.IsZExt = !isSigned;
  1954. Args.push_back(Entry);
  1955. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  1956. TLI.getPointerTy(DAG.getDataLayout()));
  1957. SDLoc dl(Node);
  1958. TargetLowering::CallLoweringInfo CLI(DAG);
  1959. CLI.setDebugLoc(dl)
  1960. .setChain(InChain)
  1961. .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
  1962. std::move(Args))
  1963. .setSExtResult(isSigned)
  1964. .setZExtResult(!isSigned);
  1965. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  1966. // Remainder is loaded back from the stack frame.
  1967. SDValue Rem =
  1968. DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo());
  1969. Results.push_back(CallInfo.first);
  1970. Results.push_back(Rem);
  1971. }
  1972. /// Return true if sincos libcall is available.
  1973. static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
  1974. RTLIB::Libcall LC;
  1975. switch (Node->getSimpleValueType(0).SimpleTy) {
  1976. default: llvm_unreachable("Unexpected request for libcall!");
  1977. case MVT::f32: LC = RTLIB::SINCOS_F32; break;
  1978. case MVT::f64: LC = RTLIB::SINCOS_F64; break;
  1979. case MVT::f80: LC = RTLIB::SINCOS_F80; break;
  1980. case MVT::f128: LC = RTLIB::SINCOS_F128; break;
  1981. case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
  1982. }
  1983. return TLI.getLibcallName(LC) != nullptr;
  1984. }
  1985. /// Only issue sincos libcall if both sin and cos are needed.
  1986. static bool useSinCos(SDNode *Node) {
  1987. unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
  1988. ? ISD::FCOS : ISD::FSIN;
  1989. SDValue Op0 = Node->getOperand(0);
  1990. for (const SDNode *User : Op0.getNode()->uses()) {
  1991. if (User == Node)
  1992. continue;
  1993. // The other user might have been turned into sincos already.
  1994. if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
  1995. return true;
  1996. }
  1997. return false;
  1998. }
  1999. /// Issue libcalls to sincos to compute sin / cos pairs.
  2000. void
  2001. SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
  2002. SmallVectorImpl<SDValue> &Results) {
  2003. RTLIB::Libcall LC;
  2004. switch (Node->getSimpleValueType(0).SimpleTy) {
  2005. default: llvm_unreachable("Unexpected request for libcall!");
  2006. case MVT::f32: LC = RTLIB::SINCOS_F32; break;
  2007. case MVT::f64: LC = RTLIB::SINCOS_F64; break;
  2008. case MVT::f80: LC = RTLIB::SINCOS_F80; break;
  2009. case MVT::f128: LC = RTLIB::SINCOS_F128; break;
  2010. case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
  2011. }
  2012. // The input chain to this libcall is the entry node of the function.
  2013. // Legalizing the call will automatically add the previous call to the
  2014. // dependence.
  2015. SDValue InChain = DAG.getEntryNode();
  2016. EVT RetVT = Node->getValueType(0);
  2017. Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
  2018. TargetLowering::ArgListTy Args;
  2019. TargetLowering::ArgListEntry Entry;
  2020. // Pass the argument.
  2021. Entry.Node = Node->getOperand(0);
  2022. Entry.Ty = RetTy;
  2023. Entry.IsSExt = false;
  2024. Entry.IsZExt = false;
  2025. Args.push_back(Entry);
  2026. // Pass the return address of sin.
  2027. SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
  2028. Entry.Node = SinPtr;
  2029. Entry.Ty = RetTy->getPointerTo();
  2030. Entry.IsSExt = false;
  2031. Entry.IsZExt = false;
  2032. Args.push_back(Entry);
  2033. // Also pass the return address of the cos.
  2034. SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
  2035. Entry.Node = CosPtr;
  2036. Entry.Ty = RetTy->getPointerTo();
  2037. Entry.IsSExt = false;
  2038. Entry.IsZExt = false;
  2039. Args.push_back(Entry);
  2040. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  2041. TLI.getPointerTy(DAG.getDataLayout()));
  2042. SDLoc dl(Node);
  2043. TargetLowering::CallLoweringInfo CLI(DAG);
  2044. CLI.setDebugLoc(dl).setChain(InChain).setLibCallee(
  2045. TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee,
  2046. std::move(Args));
  2047. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  2048. Results.push_back(
  2049. DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo()));
  2050. Results.push_back(
  2051. DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo()));
  2052. }
  2053. /// This function is responsible for legalizing a
  2054. /// INT_TO_FP operation of the specified operand when the target requests that
  2055. /// we expand it. At this point, we know that the result and operand types are
  2056. /// legal for the target.
  2057. SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(SDNode *Node,
  2058. SDValue &Chain) {
  2059. bool isSigned = (Node->getOpcode() == ISD::STRICT_SINT_TO_FP ||
  2060. Node->getOpcode() == ISD::SINT_TO_FP);
  2061. EVT DestVT = Node->getValueType(0);
  2062. SDLoc dl(Node);
  2063. unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
  2064. SDValue Op0 = Node->getOperand(OpNo);
  2065. EVT SrcVT = Op0.getValueType();
  2066. // TODO: Should any fast-math-flags be set for the created nodes?
  2067. LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n");
  2068. if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64) &&
  2069. (DestVT.bitsLE(MVT::f64) ||
  2070. TLI.isOperationLegal(Node->isStrictFPOpcode() ? ISD::STRICT_FP_EXTEND
  2071. : ISD::FP_EXTEND,
  2072. DestVT))) {
  2073. LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double "
  2074. "expansion\n");
  2075. // Get the stack frame index of a 8 byte buffer.
  2076. SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
  2077. SDValue Lo = Op0;
  2078. // if signed map to unsigned space
  2079. if (isSigned) {
  2080. // Invert sign bit (signed to unsigned mapping).
  2081. Lo = DAG.getNode(ISD::XOR, dl, MVT::i32, Lo,
  2082. DAG.getConstant(0x80000000u, dl, MVT::i32));
  2083. }
  2084. // Initial hi portion of constructed double.
  2085. SDValue Hi = DAG.getConstant(0x43300000u, dl, MVT::i32);
  2086. // If this a big endian target, swap the lo and high data.
  2087. if (DAG.getDataLayout().isBigEndian())
  2088. std::swap(Lo, Hi);
  2089. SDValue MemChain = DAG.getEntryNode();
  2090. // Store the lo of the constructed double.
  2091. SDValue Store1 = DAG.getStore(MemChain, dl, Lo, StackSlot,
  2092. MachinePointerInfo());
  2093. // Store the hi of the constructed double.
  2094. SDValue HiPtr = DAG.getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), dl);
  2095. SDValue Store2 =
  2096. DAG.getStore(MemChain, dl, Hi, HiPtr, MachinePointerInfo());
  2097. MemChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
  2098. // load the constructed double
  2099. SDValue Load =
  2100. DAG.getLoad(MVT::f64, dl, MemChain, StackSlot, MachinePointerInfo());
  2101. // FP constant to bias correct the final result
  2102. SDValue Bias = DAG.getConstantFP(isSigned ?
  2103. BitsToDouble(0x4330000080000000ULL) :
  2104. BitsToDouble(0x4330000000000000ULL),
  2105. dl, MVT::f64);
  2106. // Subtract the bias and get the final result.
  2107. SDValue Sub;
  2108. SDValue Result;
  2109. if (Node->isStrictFPOpcode()) {
  2110. Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
  2111. {Node->getOperand(0), Load, Bias});
  2112. Chain = Sub.getValue(1);
  2113. if (DestVT != Sub.getValueType()) {
  2114. std::pair<SDValue, SDValue> ResultPair;
  2115. ResultPair =
  2116. DAG.getStrictFPExtendOrRound(Sub, Chain, dl, DestVT);
  2117. Result = ResultPair.first;
  2118. Chain = ResultPair.second;
  2119. }
  2120. else
  2121. Result = Sub;
  2122. } else {
  2123. Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
  2124. Result = DAG.getFPExtendOrRound(Sub, dl, DestVT);
  2125. }
  2126. return Result;
  2127. }
  2128. if (isSigned)
  2129. return SDValue();
  2130. // TODO: Generalize this for use with other types.
  2131. if (((SrcVT == MVT::i32 || SrcVT == MVT::i64) && DestVT == MVT::f32) ||
  2132. (SrcVT == MVT::i64 && DestVT == MVT::f64)) {
  2133. LLVM_DEBUG(dbgs() << "Converting unsigned i32/i64 to f32/f64\n");
  2134. // For unsigned conversions, convert them to signed conversions using the
  2135. // algorithm from the x86_64 __floatundisf in compiler_rt. That method
  2136. // should be valid for i32->f32 as well.
  2137. // More generally this transform should be valid if there are 3 more bits
  2138. // in the integer type than the significand. Rounding uses the first bit
  2139. // after the width of the significand and the OR of all bits after that. So
  2140. // we need to be able to OR the shifted out bit into one of the bits that
  2141. // participate in the OR.
  2142. // TODO: This really should be implemented using a branch rather than a
  2143. // select. We happen to get lucky and machinesink does the right
  2144. // thing most of the time. This would be a good candidate for a
  2145. // pseudo-op, or, even better, for whole-function isel.
  2146. EVT SetCCVT = getSetCCResultType(SrcVT);
  2147. SDValue SignBitTest = DAG.getSetCC(
  2148. dl, SetCCVT, Op0, DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
  2149. EVT ShiftVT = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout());
  2150. SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT);
  2151. SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Op0, ShiftConst);
  2152. SDValue AndConst = DAG.getConstant(1, dl, SrcVT);
  2153. SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Op0, AndConst);
  2154. SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr);
  2155. SDValue Slow, Fast;
  2156. if (Node->isStrictFPOpcode()) {
  2157. // In strict mode, we must avoid spurious exceptions, and therefore
  2158. // must make sure to only emit a single STRICT_SINT_TO_FP.
  2159. SDValue InCvt = DAG.getSelect(dl, SrcVT, SignBitTest, Or, Op0);
  2160. Fast = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other },
  2161. { Node->getOperand(0), InCvt });
  2162. Slow = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other },
  2163. { Fast.getValue(1), Fast, Fast });
  2164. Chain = Slow.getValue(1);
  2165. // The STRICT_SINT_TO_FP inherits the exception mode from the
  2166. // incoming STRICT_UINT_TO_FP node; the STRICT_FADD node can
  2167. // never raise any exception.
  2168. SDNodeFlags Flags;
  2169. Flags.setNoFPExcept(Node->getFlags().hasNoFPExcept());
  2170. Fast->setFlags(Flags);
  2171. Flags.setNoFPExcept(true);
  2172. Slow->setFlags(Flags);
  2173. } else {
  2174. SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Or);
  2175. Slow = DAG.getNode(ISD::FADD, dl, DestVT, SignCvt, SignCvt);
  2176. Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
  2177. }
  2178. return DAG.getSelect(dl, DestVT, SignBitTest, Slow, Fast);
  2179. }
  2180. // Don't expand it if there isn't cheap fadd.
  2181. if (!TLI.isOperationLegalOrCustom(
  2182. Node->isStrictFPOpcode() ? ISD::STRICT_FADD : ISD::FADD, DestVT))
  2183. return SDValue();
  2184. // The following optimization is valid only if every value in SrcVT (when
  2185. // treated as signed) is representable in DestVT. Check that the mantissa
  2186. // size of DestVT is >= than the number of bits in SrcVT -1.
  2187. assert(APFloat::semanticsPrecision(DAG.EVTToAPFloatSemantics(DestVT)) >=
  2188. SrcVT.getSizeInBits() - 1 &&
  2189. "Cannot perform lossless SINT_TO_FP!");
  2190. SDValue Tmp1;
  2191. if (Node->isStrictFPOpcode()) {
  2192. Tmp1 = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other },
  2193. { Node->getOperand(0), Op0 });
  2194. } else
  2195. Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
  2196. SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0,
  2197. DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
  2198. SDValue Zero = DAG.getIntPtrConstant(0, dl),
  2199. Four = DAG.getIntPtrConstant(4, dl);
  2200. SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
  2201. SignSet, Four, Zero);
  2202. // If the sign bit of the integer is set, the large number will be treated
  2203. // as a negative number. To counteract this, the dynamic code adds an
  2204. // offset depending on the data type.
  2205. uint64_t FF;
  2206. switch (SrcVT.getSimpleVT().SimpleTy) {
  2207. default:
  2208. return SDValue();
  2209. case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
  2210. case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
  2211. case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
  2212. case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
  2213. }
  2214. if (DAG.getDataLayout().isLittleEndian())
  2215. FF <<= 32;
  2216. Constant *FudgeFactor = ConstantInt::get(
  2217. Type::getInt64Ty(*DAG.getContext()), FF);
  2218. SDValue CPIdx =
  2219. DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout()));
  2220. Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
  2221. CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
  2222. Alignment = commonAlignment(Alignment, 4);
  2223. SDValue FudgeInReg;
  2224. if (DestVT == MVT::f32)
  2225. FudgeInReg = DAG.getLoad(
  2226. MVT::f32, dl, DAG.getEntryNode(), CPIdx,
  2227. MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
  2228. Alignment);
  2229. else {
  2230. SDValue Load = DAG.getExtLoad(
  2231. ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx,
  2232. MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
  2233. Alignment);
  2234. HandleSDNode Handle(Load);
  2235. LegalizeOp(Load.getNode());
  2236. FudgeInReg = Handle.getValue();
  2237. }
  2238. if (Node->isStrictFPOpcode()) {
  2239. SDValue Result = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other },
  2240. { Tmp1.getValue(1), Tmp1, FudgeInReg });
  2241. Chain = Result.getValue(1);
  2242. return Result;
  2243. }
  2244. return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
  2245. }
  2246. /// This function is responsible for legalizing a
  2247. /// *INT_TO_FP operation of the specified operand when the target requests that
  2248. /// we promote it. At this point, we know that the result and operand types are
  2249. /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
  2250. /// operation that takes a larger input.
  2251. void SelectionDAGLegalize::PromoteLegalINT_TO_FP(
  2252. SDNode *N, const SDLoc &dl, SmallVectorImpl<SDValue> &Results) {
  2253. bool IsStrict = N->isStrictFPOpcode();
  2254. bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
  2255. N->getOpcode() == ISD::STRICT_SINT_TO_FP;
  2256. EVT DestVT = N->getValueType(0);
  2257. SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
  2258. unsigned UIntOp = IsStrict ? ISD::STRICT_UINT_TO_FP : ISD::UINT_TO_FP;
  2259. unsigned SIntOp = IsStrict ? ISD::STRICT_SINT_TO_FP : ISD::SINT_TO_FP;
  2260. // First step, figure out the appropriate *INT_TO_FP operation to use.
  2261. EVT NewInTy = LegalOp.getValueType();
  2262. unsigned OpToUse = 0;
  2263. // Scan for the appropriate larger type to use.
  2264. while (true) {
  2265. NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
  2266. assert(NewInTy.isInteger() && "Ran out of possibilities!");
  2267. // If the target supports SINT_TO_FP of this type, use it.
  2268. if (TLI.isOperationLegalOrCustom(SIntOp, NewInTy)) {
  2269. OpToUse = SIntOp;
  2270. break;
  2271. }
  2272. if (IsSigned)
  2273. continue;
  2274. // If the target supports UINT_TO_FP of this type, use it.
  2275. if (TLI.isOperationLegalOrCustom(UIntOp, NewInTy)) {
  2276. OpToUse = UIntOp;
  2277. break;
  2278. }
  2279. // Otherwise, try a larger type.
  2280. }
  2281. // Okay, we found the operation and type to use. Zero extend our input to the
  2282. // desired type then run the operation on it.
  2283. if (IsStrict) {
  2284. SDValue Res =
  2285. DAG.getNode(OpToUse, dl, {DestVT, MVT::Other},
  2286. {N->getOperand(0),
  2287. DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
  2288. dl, NewInTy, LegalOp)});
  2289. Results.push_back(Res);
  2290. Results.push_back(Res.getValue(1));
  2291. return;
  2292. }
  2293. Results.push_back(
  2294. DAG.getNode(OpToUse, dl, DestVT,
  2295. DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
  2296. dl, NewInTy, LegalOp)));
  2297. }
  2298. /// This function is responsible for legalizing a
  2299. /// FP_TO_*INT operation of the specified operand when the target requests that
  2300. /// we promote it. At this point, we know that the result and operand types are
  2301. /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
  2302. /// operation that returns a larger result.
  2303. void SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
  2304. SmallVectorImpl<SDValue> &Results) {
  2305. bool IsStrict = N->isStrictFPOpcode();
  2306. bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
  2307. N->getOpcode() == ISD::STRICT_FP_TO_SINT;
  2308. EVT DestVT = N->getValueType(0);
  2309. SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
  2310. // First step, figure out the appropriate FP_TO*INT operation to use.
  2311. EVT NewOutTy = DestVT;
  2312. unsigned OpToUse = 0;
  2313. // Scan for the appropriate larger type to use.
  2314. while (true) {
  2315. NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
  2316. assert(NewOutTy.isInteger() && "Ran out of possibilities!");
  2317. // A larger signed type can hold all unsigned values of the requested type,
  2318. // so using FP_TO_SINT is valid
  2319. OpToUse = IsStrict ? ISD::STRICT_FP_TO_SINT : ISD::FP_TO_SINT;
  2320. if (TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
  2321. break;
  2322. // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
  2323. OpToUse = IsStrict ? ISD::STRICT_FP_TO_UINT : ISD::FP_TO_UINT;
  2324. if (!IsSigned && TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
  2325. break;
  2326. // Otherwise, try a larger type.
  2327. }
  2328. // Okay, we found the operation and type to use.
  2329. SDValue Operation;
  2330. if (IsStrict) {
  2331. SDVTList VTs = DAG.getVTList(NewOutTy, MVT::Other);
  2332. Operation = DAG.getNode(OpToUse, dl, VTs, N->getOperand(0), LegalOp);
  2333. } else
  2334. Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
  2335. // Truncate the result of the extended FP_TO_*INT operation to the desired
  2336. // size.
  2337. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
  2338. Results.push_back(Trunc);
  2339. if (IsStrict)
  2340. Results.push_back(Operation.getValue(1));
  2341. }
  2342. /// Promote FP_TO_*INT_SAT operation to a larger result type. At this point
  2343. /// the result and operand types are legal and there must be a legal
  2344. /// FP_TO_*INT_SAT operation for a larger result type.
  2345. SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT_SAT(SDNode *Node,
  2346. const SDLoc &dl) {
  2347. unsigned Opcode = Node->getOpcode();
  2348. // Scan for the appropriate larger type to use.
  2349. EVT NewOutTy = Node->getValueType(0);
  2350. while (true) {
  2351. NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy + 1);
  2352. assert(NewOutTy.isInteger() && "Ran out of possibilities!");
  2353. if (TLI.isOperationLegalOrCustom(Opcode, NewOutTy))
  2354. break;
  2355. }
  2356. // Saturation width is determined by second operand, so we don't have to
  2357. // perform any fixup and can directly truncate the result.
  2358. SDValue Result = DAG.getNode(Opcode, dl, NewOutTy, Node->getOperand(0),
  2359. Node->getOperand(1));
  2360. return DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Result);
  2361. }
  2362. /// Open code the operations for PARITY of the specified operation.
  2363. SDValue SelectionDAGLegalize::ExpandPARITY(SDValue Op, const SDLoc &dl) {
  2364. EVT VT = Op.getValueType();
  2365. EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
  2366. unsigned Sz = VT.getScalarSizeInBits();
  2367. // If CTPOP is legal, use it. Otherwise use shifts and xor.
  2368. SDValue Result;
  2369. if (TLI.isOperationLegalOrPromote(ISD::CTPOP, VT)) {
  2370. Result = DAG.getNode(ISD::CTPOP, dl, VT, Op);
  2371. } else {
  2372. Result = Op;
  2373. for (unsigned i = Log2_32_Ceil(Sz); i != 0;) {
  2374. SDValue Shift = DAG.getNode(ISD::SRL, dl, VT, Result,
  2375. DAG.getConstant(1ULL << (--i), dl, ShVT));
  2376. Result = DAG.getNode(ISD::XOR, dl, VT, Result, Shift);
  2377. }
  2378. }
  2379. return DAG.getNode(ISD::AND, dl, VT, Result, DAG.getConstant(1, dl, VT));
  2380. }
  2381. bool SelectionDAGLegalize::ExpandNode(SDNode *Node) {
  2382. LLVM_DEBUG(dbgs() << "Trying to expand node\n");
  2383. SmallVector<SDValue, 8> Results;
  2384. SDLoc dl(Node);
  2385. SDValue Tmp1, Tmp2, Tmp3, Tmp4;
  2386. bool NeedInvert;
  2387. switch (Node->getOpcode()) {
  2388. case ISD::ABS:
  2389. if ((Tmp1 = TLI.expandABS(Node, DAG)))
  2390. Results.push_back(Tmp1);
  2391. break;
  2392. case ISD::CTPOP:
  2393. if ((Tmp1 = TLI.expandCTPOP(Node, DAG)))
  2394. Results.push_back(Tmp1);
  2395. break;
  2396. case ISD::CTLZ:
  2397. case ISD::CTLZ_ZERO_UNDEF:
  2398. if ((Tmp1 = TLI.expandCTLZ(Node, DAG)))
  2399. Results.push_back(Tmp1);
  2400. break;
  2401. case ISD::CTTZ:
  2402. case ISD::CTTZ_ZERO_UNDEF:
  2403. if ((Tmp1 = TLI.expandCTTZ(Node, DAG)))
  2404. Results.push_back(Tmp1);
  2405. break;
  2406. case ISD::BITREVERSE:
  2407. if ((Tmp1 = TLI.expandBITREVERSE(Node, DAG)))
  2408. Results.push_back(Tmp1);
  2409. break;
  2410. case ISD::BSWAP:
  2411. if ((Tmp1 = TLI.expandBSWAP(Node, DAG)))
  2412. Results.push_back(Tmp1);
  2413. break;
  2414. case ISD::PARITY:
  2415. Results.push_back(ExpandPARITY(Node->getOperand(0), dl));
  2416. break;
  2417. case ISD::FRAMEADDR:
  2418. case ISD::RETURNADDR:
  2419. case ISD::FRAME_TO_ARGS_OFFSET:
  2420. Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
  2421. break;
  2422. case ISD::EH_DWARF_CFA: {
  2423. SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl,
  2424. TLI.getPointerTy(DAG.getDataLayout()));
  2425. SDValue Offset = DAG.getNode(ISD::ADD, dl,
  2426. CfaArg.getValueType(),
  2427. DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
  2428. CfaArg.getValueType()),
  2429. CfaArg);
  2430. SDValue FA = DAG.getNode(
  2431. ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout()),
  2432. DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())));
  2433. Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(),
  2434. FA, Offset));
  2435. break;
  2436. }
  2437. case ISD::FLT_ROUNDS_:
  2438. Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
  2439. Results.push_back(Node->getOperand(0));
  2440. break;
  2441. case ISD::EH_RETURN:
  2442. case ISD::EH_LABEL:
  2443. case ISD::PREFETCH:
  2444. case ISD::VAEND:
  2445. case ISD::EH_SJLJ_LONGJMP:
  2446. // If the target didn't expand these, there's nothing to do, so just
  2447. // preserve the chain and be done.
  2448. Results.push_back(Node->getOperand(0));
  2449. break;
  2450. case ISD::READCYCLECOUNTER:
  2451. // If the target didn't expand this, just return 'zero' and preserve the
  2452. // chain.
  2453. Results.append(Node->getNumValues() - 1,
  2454. DAG.getConstant(0, dl, Node->getValueType(0)));
  2455. Results.push_back(Node->getOperand(0));
  2456. break;
  2457. case ISD::EH_SJLJ_SETJMP:
  2458. // If the target didn't expand this, just return 'zero' and preserve the
  2459. // chain.
  2460. Results.push_back(DAG.getConstant(0, dl, MVT::i32));
  2461. Results.push_back(Node->getOperand(0));
  2462. break;
  2463. case ISD::ATOMIC_LOAD: {
  2464. // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
  2465. SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
  2466. SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
  2467. SDValue Swap = DAG.getAtomicCmpSwap(
  2468. ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
  2469. Node->getOperand(0), Node->getOperand(1), Zero, Zero,
  2470. cast<AtomicSDNode>(Node)->getMemOperand());
  2471. Results.push_back(Swap.getValue(0));
  2472. Results.push_back(Swap.getValue(1));
  2473. break;
  2474. }
  2475. case ISD::ATOMIC_STORE: {
  2476. // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
  2477. SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
  2478. cast<AtomicSDNode>(Node)->getMemoryVT(),
  2479. Node->getOperand(0),
  2480. Node->getOperand(1), Node->getOperand(2),
  2481. cast<AtomicSDNode>(Node)->getMemOperand());
  2482. Results.push_back(Swap.getValue(1));
  2483. break;
  2484. }
  2485. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
  2486. // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
  2487. // splits out the success value as a comparison. Expanding the resulting
  2488. // ATOMIC_CMP_SWAP will produce a libcall.
  2489. SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
  2490. SDValue Res = DAG.getAtomicCmpSwap(
  2491. ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
  2492. Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
  2493. Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand());
  2494. SDValue ExtRes = Res;
  2495. SDValue LHS = Res;
  2496. SDValue RHS = Node->getOperand(1);
  2497. EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT();
  2498. EVT OuterType = Node->getValueType(0);
  2499. switch (TLI.getExtendForAtomicOps()) {
  2500. case ISD::SIGN_EXTEND:
  2501. LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res,
  2502. DAG.getValueType(AtomicType));
  2503. RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType,
  2504. Node->getOperand(2), DAG.getValueType(AtomicType));
  2505. ExtRes = LHS;
  2506. break;
  2507. case ISD::ZERO_EXTEND:
  2508. LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res,
  2509. DAG.getValueType(AtomicType));
  2510. RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
  2511. ExtRes = LHS;
  2512. break;
  2513. case ISD::ANY_EXTEND:
  2514. LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType);
  2515. RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
  2516. break;
  2517. default:
  2518. llvm_unreachable("Invalid atomic op extension");
  2519. }
  2520. SDValue Success =
  2521. DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ);
  2522. Results.push_back(ExtRes.getValue(0));
  2523. Results.push_back(Success);
  2524. Results.push_back(Res.getValue(1));
  2525. break;
  2526. }
  2527. case ISD::DYNAMIC_STACKALLOC:
  2528. ExpandDYNAMIC_STACKALLOC(Node, Results);
  2529. break;
  2530. case ISD::MERGE_VALUES:
  2531. for (unsigned i = 0; i < Node->getNumValues(); i++)
  2532. Results.push_back(Node->getOperand(i));
  2533. break;
  2534. case ISD::UNDEF: {
  2535. EVT VT = Node->getValueType(0);
  2536. if (VT.isInteger())
  2537. Results.push_back(DAG.getConstant(0, dl, VT));
  2538. else {
  2539. assert(VT.isFloatingPoint() && "Unknown value type!");
  2540. Results.push_back(DAG.getConstantFP(0, dl, VT));
  2541. }
  2542. break;
  2543. }
  2544. case ISD::STRICT_FP_ROUND:
  2545. // When strict mode is enforced we can't do expansion because it
  2546. // does not honor the "strict" properties. Only libcall is allowed.
  2547. if (TLI.isStrictFPEnabled())
  2548. break;
  2549. // We might as well mutate to FP_ROUND when FP_ROUND operation is legal
  2550. // since this operation is more efficient than stack operation.
  2551. if (TLI.getStrictFPOperationAction(Node->getOpcode(),
  2552. Node->getValueType(0))
  2553. == TargetLowering::Legal)
  2554. break;
  2555. // We fall back to use stack operation when the FP_ROUND operation
  2556. // isn't available.
  2557. if ((Tmp1 = EmitStackConvert(Node->getOperand(1), Node->getValueType(0),
  2558. Node->getValueType(0), dl,
  2559. Node->getOperand(0)))) {
  2560. ReplaceNode(Node, Tmp1.getNode());
  2561. LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_ROUND node\n");
  2562. return true;
  2563. }
  2564. break;
  2565. case ISD::FP_ROUND:
  2566. case ISD::BITCAST:
  2567. if ((Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
  2568. Node->getValueType(0), dl)))
  2569. Results.push_back(Tmp1);
  2570. break;
  2571. case ISD::STRICT_FP_EXTEND:
  2572. // When strict mode is enforced we can't do expansion because it
  2573. // does not honor the "strict" properties. Only libcall is allowed.
  2574. if (TLI.isStrictFPEnabled())
  2575. break;
  2576. // We might as well mutate to FP_EXTEND when FP_EXTEND operation is legal
  2577. // since this operation is more efficient than stack operation.
  2578. if (TLI.getStrictFPOperationAction(Node->getOpcode(),
  2579. Node->getValueType(0))
  2580. == TargetLowering::Legal)
  2581. break;
  2582. // We fall back to use stack operation when the FP_EXTEND operation
  2583. // isn't available.
  2584. if ((Tmp1 = EmitStackConvert(
  2585. Node->getOperand(1), Node->getOperand(1).getValueType(),
  2586. Node->getValueType(0), dl, Node->getOperand(0)))) {
  2587. ReplaceNode(Node, Tmp1.getNode());
  2588. LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_EXTEND node\n");
  2589. return true;
  2590. }
  2591. break;
  2592. case ISD::FP_EXTEND:
  2593. if ((Tmp1 = EmitStackConvert(Node->getOperand(0),
  2594. Node->getOperand(0).getValueType(),
  2595. Node->getValueType(0), dl)))
  2596. Results.push_back(Tmp1);
  2597. break;
  2598. case ISD::SIGN_EXTEND_INREG: {
  2599. EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
  2600. EVT VT = Node->getValueType(0);
  2601. // An in-register sign-extend of a boolean is a negation:
  2602. // 'true' (1) sign-extended is -1.
  2603. // 'false' (0) sign-extended is 0.
  2604. // However, we must mask the high bits of the source operand because the
  2605. // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero.
  2606. // TODO: Do this for vectors too?
  2607. if (ExtraVT.getSizeInBits() == 1) {
  2608. SDValue One = DAG.getConstant(1, dl, VT);
  2609. SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One);
  2610. SDValue Zero = DAG.getConstant(0, dl, VT);
  2611. SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And);
  2612. Results.push_back(Neg);
  2613. break;
  2614. }
  2615. // NOTE: we could fall back on load/store here too for targets without
  2616. // SRA. However, it is doubtful that any exist.
  2617. EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
  2618. unsigned BitsDiff = VT.getScalarSizeInBits() -
  2619. ExtraVT.getScalarSizeInBits();
  2620. SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy);
  2621. Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
  2622. Node->getOperand(0), ShiftCst);
  2623. Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
  2624. Results.push_back(Tmp1);
  2625. break;
  2626. }
  2627. case ISD::UINT_TO_FP:
  2628. case ISD::STRICT_UINT_TO_FP:
  2629. if (TLI.expandUINT_TO_FP(Node, Tmp1, Tmp2, DAG)) {
  2630. Results.push_back(Tmp1);
  2631. if (Node->isStrictFPOpcode())
  2632. Results.push_back(Tmp2);
  2633. break;
  2634. }
  2635. LLVM_FALLTHROUGH;
  2636. case ISD::SINT_TO_FP:
  2637. case ISD::STRICT_SINT_TO_FP:
  2638. if ((Tmp1 = ExpandLegalINT_TO_FP(Node, Tmp2))) {
  2639. Results.push_back(Tmp1);
  2640. if (Node->isStrictFPOpcode())
  2641. Results.push_back(Tmp2);
  2642. }
  2643. break;
  2644. case ISD::FP_TO_SINT:
  2645. if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
  2646. Results.push_back(Tmp1);
  2647. break;
  2648. case ISD::STRICT_FP_TO_SINT:
  2649. if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) {
  2650. ReplaceNode(Node, Tmp1.getNode());
  2651. LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_SINT node\n");
  2652. return true;
  2653. }
  2654. break;
  2655. case ISD::FP_TO_UINT:
  2656. if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG))
  2657. Results.push_back(Tmp1);
  2658. break;
  2659. case ISD::STRICT_FP_TO_UINT:
  2660. if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) {
  2661. // Relink the chain.
  2662. DAG.ReplaceAllUsesOfValueWith(SDValue(Node,1), Tmp2);
  2663. // Replace the new UINT result.
  2664. ReplaceNodeWithValue(SDValue(Node, 0), Tmp1);
  2665. LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_UINT node\n");
  2666. return true;
  2667. }
  2668. break;
  2669. case ISD::FP_TO_SINT_SAT:
  2670. case ISD::FP_TO_UINT_SAT:
  2671. Results.push_back(TLI.expandFP_TO_INT_SAT(Node, DAG));
  2672. break;
  2673. case ISD::VAARG:
  2674. Results.push_back(DAG.expandVAArg(Node));
  2675. Results.push_back(Results[0].getValue(1));
  2676. break;
  2677. case ISD::VACOPY:
  2678. Results.push_back(DAG.expandVACopy(Node));
  2679. break;
  2680. case ISD::EXTRACT_VECTOR_ELT:
  2681. if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
  2682. // This must be an access of the only element. Return it.
  2683. Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
  2684. Node->getOperand(0));
  2685. else
  2686. Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
  2687. Results.push_back(Tmp1);
  2688. break;
  2689. case ISD::EXTRACT_SUBVECTOR:
  2690. Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
  2691. break;
  2692. case ISD::INSERT_SUBVECTOR:
  2693. Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
  2694. break;
  2695. case ISD::CONCAT_VECTORS:
  2696. Results.push_back(ExpandVectorBuildThroughStack(Node));
  2697. break;
  2698. case ISD::SCALAR_TO_VECTOR:
  2699. Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
  2700. break;
  2701. case ISD::INSERT_VECTOR_ELT:
  2702. Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
  2703. Node->getOperand(1),
  2704. Node->getOperand(2), dl));
  2705. break;
  2706. case ISD::VECTOR_SHUFFLE: {
  2707. SmallVector<int, 32> NewMask;
  2708. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
  2709. EVT VT = Node->getValueType(0);
  2710. EVT EltVT = VT.getVectorElementType();
  2711. SDValue Op0 = Node->getOperand(0);
  2712. SDValue Op1 = Node->getOperand(1);
  2713. if (!TLI.isTypeLegal(EltVT)) {
  2714. EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
  2715. // BUILD_VECTOR operands are allowed to be wider than the element type.
  2716. // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
  2717. // it.
  2718. if (NewEltVT.bitsLT(EltVT)) {
  2719. // Convert shuffle node.
  2720. // If original node was v4i64 and the new EltVT is i32,
  2721. // cast operands to v8i32 and re-build the mask.
  2722. // Calculate new VT, the size of the new VT should be equal to original.
  2723. EVT NewVT =
  2724. EVT::getVectorVT(*DAG.getContext(), NewEltVT,
  2725. VT.getSizeInBits() / NewEltVT.getSizeInBits());
  2726. assert(NewVT.bitsEq(VT));
  2727. // cast operands to new VT
  2728. Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
  2729. Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
  2730. // Convert the shuffle mask
  2731. unsigned int factor =
  2732. NewVT.getVectorNumElements()/VT.getVectorNumElements();
  2733. // EltVT gets smaller
  2734. assert(factor > 0);
  2735. for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
  2736. if (Mask[i] < 0) {
  2737. for (unsigned fi = 0; fi < factor; ++fi)
  2738. NewMask.push_back(Mask[i]);
  2739. }
  2740. else {
  2741. for (unsigned fi = 0; fi < factor; ++fi)
  2742. NewMask.push_back(Mask[i]*factor+fi);
  2743. }
  2744. }
  2745. Mask = NewMask;
  2746. VT = NewVT;
  2747. }
  2748. EltVT = NewEltVT;
  2749. }
  2750. unsigned NumElems = VT.getVectorNumElements();
  2751. SmallVector<SDValue, 16> Ops;
  2752. for (unsigned i = 0; i != NumElems; ++i) {
  2753. if (Mask[i] < 0) {
  2754. Ops.push_back(DAG.getUNDEF(EltVT));
  2755. continue;
  2756. }
  2757. unsigned Idx = Mask[i];
  2758. if (Idx < NumElems)
  2759. Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
  2760. DAG.getVectorIdxConstant(Idx, dl)));
  2761. else
  2762. Ops.push_back(
  2763. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
  2764. DAG.getVectorIdxConstant(Idx - NumElems, dl)));
  2765. }
  2766. Tmp1 = DAG.getBuildVector(VT, dl, Ops);
  2767. // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
  2768. Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
  2769. Results.push_back(Tmp1);
  2770. break;
  2771. }
  2772. case ISD::VECTOR_SPLICE: {
  2773. Results.push_back(TLI.expandVectorSplice(Node, DAG));
  2774. break;
  2775. }
  2776. case ISD::EXTRACT_ELEMENT: {
  2777. EVT OpTy = Node->getOperand(0).getValueType();
  2778. if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
  2779. // 1 -> Hi
  2780. Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
  2781. DAG.getConstant(OpTy.getSizeInBits() / 2, dl,
  2782. TLI.getShiftAmountTy(
  2783. Node->getOperand(0).getValueType(),
  2784. DAG.getDataLayout())));
  2785. Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
  2786. } else {
  2787. // 0 -> Lo
  2788. Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
  2789. Node->getOperand(0));
  2790. }
  2791. Results.push_back(Tmp1);
  2792. break;
  2793. }
  2794. case ISD::STACKSAVE:
  2795. // Expand to CopyFromReg if the target set
  2796. // StackPointerRegisterToSaveRestore.
  2797. if (Register SP = TLI.getStackPointerRegisterToSaveRestore()) {
  2798. Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
  2799. Node->getValueType(0)));
  2800. Results.push_back(Results[0].getValue(1));
  2801. } else {
  2802. Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
  2803. Results.push_back(Node->getOperand(0));
  2804. }
  2805. break;
  2806. case ISD::STACKRESTORE:
  2807. // Expand to CopyToReg if the target set
  2808. // StackPointerRegisterToSaveRestore.
  2809. if (Register SP = TLI.getStackPointerRegisterToSaveRestore()) {
  2810. Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
  2811. Node->getOperand(1)));
  2812. } else {
  2813. Results.push_back(Node->getOperand(0));
  2814. }
  2815. break;
  2816. case ISD::GET_DYNAMIC_AREA_OFFSET:
  2817. Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
  2818. Results.push_back(Results[0].getValue(0));
  2819. break;
  2820. case ISD::FCOPYSIGN:
  2821. Results.push_back(ExpandFCOPYSIGN(Node));
  2822. break;
  2823. case ISD::FNEG:
  2824. Results.push_back(ExpandFNEG(Node));
  2825. break;
  2826. case ISD::FABS:
  2827. Results.push_back(ExpandFABS(Node));
  2828. break;
  2829. case ISD::SMIN:
  2830. case ISD::SMAX:
  2831. case ISD::UMIN:
  2832. case ISD::UMAX: {
  2833. // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
  2834. ISD::CondCode Pred;
  2835. switch (Node->getOpcode()) {
  2836. default: llvm_unreachable("How did we get here?");
  2837. case ISD::SMAX: Pred = ISD::SETGT; break;
  2838. case ISD::SMIN: Pred = ISD::SETLT; break;
  2839. case ISD::UMAX: Pred = ISD::SETUGT; break;
  2840. case ISD::UMIN: Pred = ISD::SETULT; break;
  2841. }
  2842. Tmp1 = Node->getOperand(0);
  2843. Tmp2 = Node->getOperand(1);
  2844. Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
  2845. Results.push_back(Tmp1);
  2846. break;
  2847. }
  2848. case ISD::FMINNUM:
  2849. case ISD::FMAXNUM: {
  2850. if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG))
  2851. Results.push_back(Expanded);
  2852. break;
  2853. }
  2854. case ISD::FSIN:
  2855. case ISD::FCOS: {
  2856. EVT VT = Node->getValueType(0);
  2857. // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
  2858. // fcos which share the same operand and both are used.
  2859. if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
  2860. isSinCosLibcallAvailable(Node, TLI))
  2861. && useSinCos(Node)) {
  2862. SDVTList VTs = DAG.getVTList(VT, VT);
  2863. Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
  2864. if (Node->getOpcode() == ISD::FCOS)
  2865. Tmp1 = Tmp1.getValue(1);
  2866. Results.push_back(Tmp1);
  2867. }
  2868. break;
  2869. }
  2870. case ISD::FMAD:
  2871. llvm_unreachable("Illegal fmad should never be formed");
  2872. case ISD::FP16_TO_FP:
  2873. if (Node->getValueType(0) != MVT::f32) {
  2874. // We can extend to types bigger than f32 in two steps without changing
  2875. // the result. Since "f16 -> f32" is much more commonly available, give
  2876. // CodeGen the option of emitting that before resorting to a libcall.
  2877. SDValue Res =
  2878. DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
  2879. Results.push_back(
  2880. DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
  2881. }
  2882. break;
  2883. case ISD::STRICT_FP16_TO_FP:
  2884. if (Node->getValueType(0) != MVT::f32) {
  2885. // We can extend to types bigger than f32 in two steps without changing
  2886. // the result. Since "f16 -> f32" is much more commonly available, give
  2887. // CodeGen the option of emitting that before resorting to a libcall.
  2888. SDValue Res =
  2889. DAG.getNode(ISD::STRICT_FP16_TO_FP, dl, {MVT::f32, MVT::Other},
  2890. {Node->getOperand(0), Node->getOperand(1)});
  2891. Res = DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
  2892. {Node->getValueType(0), MVT::Other},
  2893. {Res.getValue(1), Res});
  2894. Results.push_back(Res);
  2895. Results.push_back(Res.getValue(1));
  2896. }
  2897. break;
  2898. case ISD::FP_TO_FP16:
  2899. LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n");
  2900. if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) {
  2901. SDValue Op = Node->getOperand(0);
  2902. MVT SVT = Op.getSimpleValueType();
  2903. if ((SVT == MVT::f64 || SVT == MVT::f80) &&
  2904. TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) {
  2905. // Under fastmath, we can expand this node into a fround followed by
  2906. // a float-half conversion.
  2907. SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
  2908. DAG.getIntPtrConstant(0, dl));
  2909. Results.push_back(
  2910. DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal));
  2911. }
  2912. }
  2913. break;
  2914. case ISD::ConstantFP: {
  2915. ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
  2916. // Check to see if this FP immediate is already legal.
  2917. // If this is a legal constant, turn it into a TargetConstantFP node.
  2918. if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0),
  2919. DAG.shouldOptForSize()))
  2920. Results.push_back(ExpandConstantFP(CFP, true));
  2921. break;
  2922. }
  2923. case ISD::Constant: {
  2924. ConstantSDNode *CP = cast<ConstantSDNode>(Node);
  2925. Results.push_back(ExpandConstant(CP));
  2926. break;
  2927. }
  2928. case ISD::FSUB: {
  2929. EVT VT = Node->getValueType(0);
  2930. if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
  2931. TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) {
  2932. const SDNodeFlags Flags = Node->getFlags();
  2933. Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
  2934. Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
  2935. Results.push_back(Tmp1);
  2936. }
  2937. break;
  2938. }
  2939. case ISD::SUB: {
  2940. EVT VT = Node->getValueType(0);
  2941. assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
  2942. TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
  2943. "Don't know how to expand this subtraction!");
  2944. Tmp1 = DAG.getNOT(dl, Node->getOperand(1), VT);
  2945. Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
  2946. Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
  2947. break;
  2948. }
  2949. case ISD::UREM:
  2950. case ISD::SREM:
  2951. if (TLI.expandREM(Node, Tmp1, DAG))
  2952. Results.push_back(Tmp1);
  2953. break;
  2954. case ISD::UDIV:
  2955. case ISD::SDIV: {
  2956. bool isSigned = Node->getOpcode() == ISD::SDIV;
  2957. unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
  2958. EVT VT = Node->getValueType(0);
  2959. if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
  2960. SDVTList VTs = DAG.getVTList(VT, VT);
  2961. Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
  2962. Node->getOperand(1));
  2963. Results.push_back(Tmp1);
  2964. }
  2965. break;
  2966. }
  2967. case ISD::MULHU:
  2968. case ISD::MULHS: {
  2969. unsigned ExpandOpcode =
  2970. Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI;
  2971. EVT VT = Node->getValueType(0);
  2972. SDVTList VTs = DAG.getVTList(VT, VT);
  2973. Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
  2974. Node->getOperand(1));
  2975. Results.push_back(Tmp1.getValue(1));
  2976. break;
  2977. }
  2978. case ISD::UMUL_LOHI:
  2979. case ISD::SMUL_LOHI: {
  2980. SDValue LHS = Node->getOperand(0);
  2981. SDValue RHS = Node->getOperand(1);
  2982. MVT VT = LHS.getSimpleValueType();
  2983. unsigned MULHOpcode =
  2984. Node->getOpcode() == ISD::UMUL_LOHI ? ISD::MULHU : ISD::MULHS;
  2985. if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) {
  2986. Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS));
  2987. Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS));
  2988. break;
  2989. }
  2990. SmallVector<SDValue, 4> Halves;
  2991. EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext());
  2992. assert(TLI.isTypeLegal(HalfType));
  2993. if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, dl, LHS, RHS, Halves,
  2994. HalfType, DAG,
  2995. TargetLowering::MulExpansionKind::Always)) {
  2996. for (unsigned i = 0; i < 2; ++i) {
  2997. SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]);
  2998. SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]);
  2999. SDValue Shift = DAG.getConstant(
  3000. HalfType.getScalarSizeInBits(), dl,
  3001. TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
  3002. Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
  3003. Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
  3004. }
  3005. break;
  3006. }
  3007. break;
  3008. }
  3009. case ISD::MUL: {
  3010. EVT VT = Node->getValueType(0);
  3011. SDVTList VTs = DAG.getVTList(VT, VT);
  3012. // See if multiply or divide can be lowered using two-result operations.
  3013. // We just need the low half of the multiply; try both the signed
  3014. // and unsigned forms. If the target supports both SMUL_LOHI and
  3015. // UMUL_LOHI, form a preference by checking which forms of plain
  3016. // MULH it supports.
  3017. bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
  3018. bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
  3019. bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
  3020. bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
  3021. unsigned OpToUse = 0;
  3022. if (HasSMUL_LOHI && !HasMULHS) {
  3023. OpToUse = ISD::SMUL_LOHI;
  3024. } else if (HasUMUL_LOHI && !HasMULHU) {
  3025. OpToUse = ISD::UMUL_LOHI;
  3026. } else if (HasSMUL_LOHI) {
  3027. OpToUse = ISD::SMUL_LOHI;
  3028. } else if (HasUMUL_LOHI) {
  3029. OpToUse = ISD::UMUL_LOHI;
  3030. }
  3031. if (OpToUse) {
  3032. Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
  3033. Node->getOperand(1)));
  3034. break;
  3035. }
  3036. SDValue Lo, Hi;
  3037. EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
  3038. if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
  3039. TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
  3040. TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
  3041. TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
  3042. TLI.expandMUL(Node, Lo, Hi, HalfType, DAG,
  3043. TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) {
  3044. Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
  3045. Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
  3046. SDValue Shift =
  3047. DAG.getConstant(HalfType.getSizeInBits(), dl,
  3048. TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
  3049. Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
  3050. Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
  3051. }
  3052. break;
  3053. }
  3054. case ISD::FSHL:
  3055. case ISD::FSHR:
  3056. if (SDValue Expanded = TLI.expandFunnelShift(Node, DAG))
  3057. Results.push_back(Expanded);
  3058. break;
  3059. case ISD::ROTL:
  3060. case ISD::ROTR:
  3061. if (SDValue Expanded = TLI.expandROT(Node, true /*AllowVectorOps*/, DAG))
  3062. Results.push_back(Expanded);
  3063. break;
  3064. case ISD::SADDSAT:
  3065. case ISD::UADDSAT:
  3066. case ISD::SSUBSAT:
  3067. case ISD::USUBSAT:
  3068. Results.push_back(TLI.expandAddSubSat(Node, DAG));
  3069. break;
  3070. case ISD::SSHLSAT:
  3071. case ISD::USHLSAT:
  3072. Results.push_back(TLI.expandShlSat(Node, DAG));
  3073. break;
  3074. case ISD::SMULFIX:
  3075. case ISD::SMULFIXSAT:
  3076. case ISD::UMULFIX:
  3077. case ISD::UMULFIXSAT:
  3078. Results.push_back(TLI.expandFixedPointMul(Node, DAG));
  3079. break;
  3080. case ISD::SDIVFIX:
  3081. case ISD::SDIVFIXSAT:
  3082. case ISD::UDIVFIX:
  3083. case ISD::UDIVFIXSAT:
  3084. if (SDValue V = TLI.expandFixedPointDiv(Node->getOpcode(), SDLoc(Node),
  3085. Node->getOperand(0),
  3086. Node->getOperand(1),
  3087. Node->getConstantOperandVal(2),
  3088. DAG)) {
  3089. Results.push_back(V);
  3090. break;
  3091. }
  3092. // FIXME: We might want to retry here with a wider type if we fail, if that
  3093. // type is legal.
  3094. // FIXME: Technically, so long as we only have sdivfixes where BW+Scale is
  3095. // <= 128 (which is the case for all of the default Embedded-C types),
  3096. // we will only get here with types and scales that we could always expand
  3097. // if we were allowed to generate libcalls to division functions of illegal
  3098. // type. But we cannot do that.
  3099. llvm_unreachable("Cannot expand DIVFIX!");
  3100. case ISD::ADDCARRY:
  3101. case ISD::SUBCARRY: {
  3102. SDValue LHS = Node->getOperand(0);
  3103. SDValue RHS = Node->getOperand(1);
  3104. SDValue Carry = Node->getOperand(2);
  3105. bool IsAdd = Node->getOpcode() == ISD::ADDCARRY;
  3106. // Initial add of the 2 operands.
  3107. unsigned Op = IsAdd ? ISD::ADD : ISD::SUB;
  3108. EVT VT = LHS.getValueType();
  3109. SDValue Sum = DAG.getNode(Op, dl, VT, LHS, RHS);
  3110. // Initial check for overflow.
  3111. EVT CarryType = Node->getValueType(1);
  3112. EVT SetCCType = getSetCCResultType(Node->getValueType(0));
  3113. ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
  3114. SDValue Overflow = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
  3115. // Add of the sum and the carry.
  3116. SDValue One = DAG.getConstant(1, dl, VT);
  3117. SDValue CarryExt =
  3118. DAG.getNode(ISD::AND, dl, VT, DAG.getZExtOrTrunc(Carry, dl, VT), One);
  3119. SDValue Sum2 = DAG.getNode(Op, dl, VT, Sum, CarryExt);
  3120. // Second check for overflow. If we are adding, we can only overflow if the
  3121. // initial sum is all 1s ang the carry is set, resulting in a new sum of 0.
  3122. // If we are subtracting, we can only overflow if the initial sum is 0 and
  3123. // the carry is set, resulting in a new sum of all 1s.
  3124. SDValue Zero = DAG.getConstant(0, dl, VT);
  3125. SDValue Overflow2 =
  3126. IsAdd ? DAG.getSetCC(dl, SetCCType, Sum2, Zero, ISD::SETEQ)
  3127. : DAG.getSetCC(dl, SetCCType, Sum, Zero, ISD::SETEQ);
  3128. Overflow2 = DAG.getNode(ISD::AND, dl, SetCCType, Overflow2,
  3129. DAG.getZExtOrTrunc(Carry, dl, SetCCType));
  3130. SDValue ResultCarry =
  3131. DAG.getNode(ISD::OR, dl, SetCCType, Overflow, Overflow2);
  3132. Results.push_back(Sum2);
  3133. Results.push_back(DAG.getBoolExtOrTrunc(ResultCarry, dl, CarryType, VT));
  3134. break;
  3135. }
  3136. case ISD::SADDO:
  3137. case ISD::SSUBO: {
  3138. SDValue Result, Overflow;
  3139. TLI.expandSADDSUBO(Node, Result, Overflow, DAG);
  3140. Results.push_back(Result);
  3141. Results.push_back(Overflow);
  3142. break;
  3143. }
  3144. case ISD::UADDO:
  3145. case ISD::USUBO: {
  3146. SDValue Result, Overflow;
  3147. TLI.expandUADDSUBO(Node, Result, Overflow, DAG);
  3148. Results.push_back(Result);
  3149. Results.push_back(Overflow);
  3150. break;
  3151. }
  3152. case ISD::UMULO:
  3153. case ISD::SMULO: {
  3154. SDValue Result, Overflow;
  3155. if (TLI.expandMULO(Node, Result, Overflow, DAG)) {
  3156. Results.push_back(Result);
  3157. Results.push_back(Overflow);
  3158. }
  3159. break;
  3160. }
  3161. case ISD::BUILD_PAIR: {
  3162. EVT PairTy = Node->getValueType(0);
  3163. Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
  3164. Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
  3165. Tmp2 = DAG.getNode(
  3166. ISD::SHL, dl, PairTy, Tmp2,
  3167. DAG.getConstant(PairTy.getSizeInBits() / 2, dl,
  3168. TLI.getShiftAmountTy(PairTy, DAG.getDataLayout())));
  3169. Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
  3170. break;
  3171. }
  3172. case ISD::SELECT:
  3173. Tmp1 = Node->getOperand(0);
  3174. Tmp2 = Node->getOperand(1);
  3175. Tmp3 = Node->getOperand(2);
  3176. if (Tmp1.getOpcode() == ISD::SETCC) {
  3177. Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
  3178. Tmp2, Tmp3,
  3179. cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
  3180. } else {
  3181. Tmp1 = DAG.getSelectCC(dl, Tmp1,
  3182. DAG.getConstant(0, dl, Tmp1.getValueType()),
  3183. Tmp2, Tmp3, ISD::SETNE);
  3184. }
  3185. Tmp1->setFlags(Node->getFlags());
  3186. Results.push_back(Tmp1);
  3187. break;
  3188. case ISD::BR_JT: {
  3189. SDValue Chain = Node->getOperand(0);
  3190. SDValue Table = Node->getOperand(1);
  3191. SDValue Index = Node->getOperand(2);
  3192. const DataLayout &TD = DAG.getDataLayout();
  3193. EVT PTy = TLI.getPointerTy(TD);
  3194. unsigned EntrySize =
  3195. DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
  3196. // For power-of-two jumptable entry sizes convert multiplication to a shift.
  3197. // This transformation needs to be done here since otherwise the MIPS
  3198. // backend will end up emitting a three instruction multiply sequence
  3199. // instead of a single shift and MSP430 will call a runtime function.
  3200. if (llvm::isPowerOf2_32(EntrySize))
  3201. Index = DAG.getNode(
  3202. ISD::SHL, dl, Index.getValueType(), Index,
  3203. DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType()));
  3204. else
  3205. Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
  3206. DAG.getConstant(EntrySize, dl, Index.getValueType()));
  3207. SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
  3208. Index, Table);
  3209. EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
  3210. SDValue LD = DAG.getExtLoad(
  3211. ISD::SEXTLOAD, dl, PTy, Chain, Addr,
  3212. MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT);
  3213. Addr = LD;
  3214. if (TLI.isJumpTableRelative()) {
  3215. // For PIC, the sequence is:
  3216. // BRIND(load(Jumptable + index) + RelocBase)
  3217. // RelocBase can be JumpTable, GOT or some sort of global base.
  3218. Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
  3219. TLI.getPICJumpTableRelocBase(Table, DAG));
  3220. }
  3221. Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, DAG);
  3222. Results.push_back(Tmp1);
  3223. break;
  3224. }
  3225. case ISD::BRCOND:
  3226. // Expand brcond's setcc into its constituent parts and create a BR_CC
  3227. // Node.
  3228. Tmp1 = Node->getOperand(0);
  3229. Tmp2 = Node->getOperand(1);
  3230. if (Tmp2.getOpcode() == ISD::SETCC &&
  3231. TLI.isOperationLegalOrCustom(ISD::BR_CC,
  3232. Tmp2.getOperand(0).getValueType())) {
  3233. Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, Tmp2.getOperand(2),
  3234. Tmp2.getOperand(0), Tmp2.getOperand(1),
  3235. Node->getOperand(2));
  3236. } else {
  3237. // We test only the i1 bit. Skip the AND if UNDEF or another AND.
  3238. if (Tmp2.isUndef() ||
  3239. (Tmp2.getOpcode() == ISD::AND &&
  3240. isa<ConstantSDNode>(Tmp2.getOperand(1)) &&
  3241. cast<ConstantSDNode>(Tmp2.getOperand(1))->getZExtValue() == 1))
  3242. Tmp3 = Tmp2;
  3243. else
  3244. Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
  3245. DAG.getConstant(1, dl, Tmp2.getValueType()));
  3246. Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
  3247. DAG.getCondCode(ISD::SETNE), Tmp3,
  3248. DAG.getConstant(0, dl, Tmp3.getValueType()),
  3249. Node->getOperand(2));
  3250. }
  3251. Results.push_back(Tmp1);
  3252. break;
  3253. case ISD::SETCC:
  3254. case ISD::STRICT_FSETCC:
  3255. case ISD::STRICT_FSETCCS: {
  3256. bool IsStrict = Node->getOpcode() != ISD::SETCC;
  3257. bool IsSignaling = Node->getOpcode() == ISD::STRICT_FSETCCS;
  3258. SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
  3259. unsigned Offset = IsStrict ? 1 : 0;
  3260. Tmp1 = Node->getOperand(0 + Offset);
  3261. Tmp2 = Node->getOperand(1 + Offset);
  3262. Tmp3 = Node->getOperand(2 + Offset);
  3263. bool Legalized =
  3264. TLI.LegalizeSetCCCondCode(DAG, Node->getValueType(0), Tmp1, Tmp2, Tmp3,
  3265. NeedInvert, dl, Chain, IsSignaling);
  3266. if (Legalized) {
  3267. // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
  3268. // condition code, create a new SETCC node.
  3269. if (Tmp3.getNode()) {
  3270. if (IsStrict) {
  3271. Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getVTList(),
  3272. {Chain, Tmp1, Tmp2, Tmp3}, Node->getFlags());
  3273. Chain = Tmp1.getValue(1);
  3274. } else {
  3275. Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1,
  3276. Tmp2, Tmp3, Node->getFlags());
  3277. }
  3278. }
  3279. // If we expanded the SETCC by inverting the condition code, then wrap
  3280. // the existing SETCC in a NOT to restore the intended condition.
  3281. if (NeedInvert)
  3282. Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
  3283. Results.push_back(Tmp1);
  3284. if (IsStrict)
  3285. Results.push_back(Chain);
  3286. break;
  3287. }
  3288. // FIXME: It seems Legalized is false iff CCCode is Legal. I don't
  3289. // understand if this code is useful for strict nodes.
  3290. assert(!IsStrict && "Don't know how to expand for strict nodes.");
  3291. // Otherwise, SETCC for the given comparison type must be completely
  3292. // illegal; expand it into a SELECT_CC.
  3293. EVT VT = Node->getValueType(0);
  3294. int TrueValue;
  3295. switch (TLI.getBooleanContents(Tmp1.getValueType())) {
  3296. case TargetLowering::ZeroOrOneBooleanContent:
  3297. case TargetLowering::UndefinedBooleanContent:
  3298. TrueValue = 1;
  3299. break;
  3300. case TargetLowering::ZeroOrNegativeOneBooleanContent:
  3301. TrueValue = -1;
  3302. break;
  3303. }
  3304. Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
  3305. DAG.getConstant(TrueValue, dl, VT),
  3306. DAG.getConstant(0, dl, VT),
  3307. Tmp3);
  3308. Tmp1->setFlags(Node->getFlags());
  3309. Results.push_back(Tmp1);
  3310. break;
  3311. }
  3312. case ISD::SELECT_CC: {
  3313. // TODO: need to add STRICT_SELECT_CC and STRICT_SELECT_CCS
  3314. Tmp1 = Node->getOperand(0); // LHS
  3315. Tmp2 = Node->getOperand(1); // RHS
  3316. Tmp3 = Node->getOperand(2); // True
  3317. Tmp4 = Node->getOperand(3); // False
  3318. EVT VT = Node->getValueType(0);
  3319. SDValue Chain;
  3320. SDValue CC = Node->getOperand(4);
  3321. ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
  3322. if (TLI.isCondCodeLegalOrCustom(CCOp, Tmp1.getSimpleValueType())) {
  3323. // If the condition code is legal, then we need to expand this
  3324. // node using SETCC and SELECT.
  3325. EVT CmpVT = Tmp1.getValueType();
  3326. assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
  3327. "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
  3328. "expanded.");
  3329. EVT CCVT = getSetCCResultType(CmpVT);
  3330. SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC, Node->getFlags());
  3331. Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
  3332. break;
  3333. }
  3334. // SELECT_CC is legal, so the condition code must not be.
  3335. bool Legalized = false;
  3336. // Try to legalize by inverting the condition. This is for targets that
  3337. // might support an ordered version of a condition, but not the unordered
  3338. // version (or vice versa).
  3339. ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, Tmp1.getValueType());
  3340. if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) {
  3341. // Use the new condition code and swap true and false
  3342. Legalized = true;
  3343. Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
  3344. Tmp1->setFlags(Node->getFlags());
  3345. } else {
  3346. // If The inverse is not legal, then try to swap the arguments using
  3347. // the inverse condition code.
  3348. ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
  3349. if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) {
  3350. // The swapped inverse condition is legal, so swap true and false,
  3351. // lhs and rhs.
  3352. Legalized = true;
  3353. Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
  3354. Tmp1->setFlags(Node->getFlags());
  3355. }
  3356. }
  3357. if (!Legalized) {
  3358. Legalized = TLI.LegalizeSetCCCondCode(
  3359. DAG, getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC,
  3360. NeedInvert, dl, Chain);
  3361. assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
  3362. // If we expanded the SETCC by inverting the condition code, then swap
  3363. // the True/False operands to match.
  3364. if (NeedInvert)
  3365. std::swap(Tmp3, Tmp4);
  3366. // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
  3367. // condition code, create a new SELECT_CC node.
  3368. if (CC.getNode()) {
  3369. Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
  3370. Tmp1, Tmp2, Tmp3, Tmp4, CC);
  3371. } else {
  3372. Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
  3373. CC = DAG.getCondCode(ISD::SETNE);
  3374. Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
  3375. Tmp2, Tmp3, Tmp4, CC);
  3376. }
  3377. Tmp1->setFlags(Node->getFlags());
  3378. }
  3379. Results.push_back(Tmp1);
  3380. break;
  3381. }
  3382. case ISD::BR_CC: {
  3383. // TODO: need to add STRICT_BR_CC and STRICT_BR_CCS
  3384. SDValue Chain;
  3385. Tmp1 = Node->getOperand(0); // Chain
  3386. Tmp2 = Node->getOperand(2); // LHS
  3387. Tmp3 = Node->getOperand(3); // RHS
  3388. Tmp4 = Node->getOperand(1); // CC
  3389. bool Legalized =
  3390. TLI.LegalizeSetCCCondCode(DAG, getSetCCResultType(Tmp2.getValueType()),
  3391. Tmp2, Tmp3, Tmp4, NeedInvert, dl, Chain);
  3392. (void)Legalized;
  3393. assert(Legalized && "Can't legalize BR_CC with legal condition!");
  3394. // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
  3395. // node.
  3396. if (Tmp4.getNode()) {
  3397. assert(!NeedInvert && "Don't know how to invert BR_CC!");
  3398. Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
  3399. Tmp4, Tmp2, Tmp3, Node->getOperand(4));
  3400. } else {
  3401. Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
  3402. Tmp4 = DAG.getCondCode(NeedInvert ? ISD::SETEQ : ISD::SETNE);
  3403. Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
  3404. Tmp2, Tmp3, Node->getOperand(4));
  3405. }
  3406. Results.push_back(Tmp1);
  3407. break;
  3408. }
  3409. case ISD::BUILD_VECTOR:
  3410. Results.push_back(ExpandBUILD_VECTOR(Node));
  3411. break;
  3412. case ISD::SPLAT_VECTOR:
  3413. Results.push_back(ExpandSPLAT_VECTOR(Node));
  3414. break;
  3415. case ISD::SRA:
  3416. case ISD::SRL:
  3417. case ISD::SHL: {
  3418. // Scalarize vector SRA/SRL/SHL.
  3419. EVT VT = Node->getValueType(0);
  3420. assert(VT.isVector() && "Unable to legalize non-vector shift");
  3421. assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
  3422. unsigned NumElem = VT.getVectorNumElements();
  3423. SmallVector<SDValue, 8> Scalars;
  3424. for (unsigned Idx = 0; Idx < NumElem; Idx++) {
  3425. SDValue Ex =
  3426. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(),
  3427. Node->getOperand(0), DAG.getVectorIdxConstant(Idx, dl));
  3428. SDValue Sh =
  3429. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(),
  3430. Node->getOperand(1), DAG.getVectorIdxConstant(Idx, dl));
  3431. Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
  3432. VT.getScalarType(), Ex, Sh));
  3433. }
  3434. SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars);
  3435. Results.push_back(Result);
  3436. break;
  3437. }
  3438. case ISD::VECREDUCE_FADD:
  3439. case ISD::VECREDUCE_FMUL:
  3440. case ISD::VECREDUCE_ADD:
  3441. case ISD::VECREDUCE_MUL:
  3442. case ISD::VECREDUCE_AND:
  3443. case ISD::VECREDUCE_OR:
  3444. case ISD::VECREDUCE_XOR:
  3445. case ISD::VECREDUCE_SMAX:
  3446. case ISD::VECREDUCE_SMIN:
  3447. case ISD::VECREDUCE_UMAX:
  3448. case ISD::VECREDUCE_UMIN:
  3449. case ISD::VECREDUCE_FMAX:
  3450. case ISD::VECREDUCE_FMIN:
  3451. Results.push_back(TLI.expandVecReduce(Node, DAG));
  3452. break;
  3453. case ISD::GLOBAL_OFFSET_TABLE:
  3454. case ISD::GlobalAddress:
  3455. case ISD::GlobalTLSAddress:
  3456. case ISD::ExternalSymbol:
  3457. case ISD::ConstantPool:
  3458. case ISD::JumpTable:
  3459. case ISD::INTRINSIC_W_CHAIN:
  3460. case ISD::INTRINSIC_WO_CHAIN:
  3461. case ISD::INTRINSIC_VOID:
  3462. // FIXME: Custom lowering for these operations shouldn't return null!
  3463. // Return true so that we don't call ConvertNodeToLibcall which also won't
  3464. // do anything.
  3465. return true;
  3466. }
  3467. if (!TLI.isStrictFPEnabled() && Results.empty() && Node->isStrictFPOpcode()) {
  3468. // FIXME: We were asked to expand a strict floating-point operation,
  3469. // but there is currently no expansion implemented that would preserve
  3470. // the "strict" properties. For now, we just fall back to the non-strict
  3471. // version if that is legal on the target. The actual mutation of the
  3472. // operation will happen in SelectionDAGISel::DoInstructionSelection.
  3473. switch (Node->getOpcode()) {
  3474. default:
  3475. if (TLI.getStrictFPOperationAction(Node->getOpcode(),
  3476. Node->getValueType(0))
  3477. == TargetLowering::Legal)
  3478. return true;
  3479. break;
  3480. case ISD::STRICT_FSUB: {
  3481. if (TLI.getStrictFPOperationAction(
  3482. ISD::STRICT_FSUB, Node->getValueType(0)) == TargetLowering::Legal)
  3483. return true;
  3484. if (TLI.getStrictFPOperationAction(
  3485. ISD::STRICT_FADD, Node->getValueType(0)) != TargetLowering::Legal)
  3486. break;
  3487. EVT VT = Node->getValueType(0);
  3488. const SDNodeFlags Flags = Node->getFlags();
  3489. SDValue Neg = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(2), Flags);
  3490. SDValue Fadd = DAG.getNode(ISD::STRICT_FADD, dl, Node->getVTList(),
  3491. {Node->getOperand(0), Node->getOperand(1), Neg},
  3492. Flags);
  3493. Results.push_back(Fadd);
  3494. Results.push_back(Fadd.getValue(1));
  3495. break;
  3496. }
  3497. case ISD::STRICT_SINT_TO_FP:
  3498. case ISD::STRICT_UINT_TO_FP:
  3499. case ISD::STRICT_LRINT:
  3500. case ISD::STRICT_LLRINT:
  3501. case ISD::STRICT_LROUND:
  3502. case ISD::STRICT_LLROUND:
  3503. // These are registered by the operand type instead of the value
  3504. // type. Reflect that here.
  3505. if (TLI.getStrictFPOperationAction(Node->getOpcode(),
  3506. Node->getOperand(1).getValueType())
  3507. == TargetLowering::Legal)
  3508. return true;
  3509. break;
  3510. }
  3511. }
  3512. // Replace the original node with the legalized result.
  3513. if (Results.empty()) {
  3514. LLVM_DEBUG(dbgs() << "Cannot expand node\n");
  3515. return false;
  3516. }
  3517. LLVM_DEBUG(dbgs() << "Successfully expanded node\n");
  3518. ReplaceNode(Node, Results.data());
  3519. return true;
  3520. }
  3521. void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
  3522. LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n");
  3523. SmallVector<SDValue, 8> Results;
  3524. SDLoc dl(Node);
  3525. // FIXME: Check flags on the node to see if we can use a finite call.
  3526. unsigned Opc = Node->getOpcode();
  3527. switch (Opc) {
  3528. case ISD::ATOMIC_FENCE: {
  3529. // If the target didn't lower this, lower it to '__sync_synchronize()' call
  3530. // FIXME: handle "fence singlethread" more efficiently.
  3531. TargetLowering::ArgListTy Args;
  3532. TargetLowering::CallLoweringInfo CLI(DAG);
  3533. CLI.setDebugLoc(dl)
  3534. .setChain(Node->getOperand(0))
  3535. .setLibCallee(
  3536. CallingConv::C, Type::getVoidTy(*DAG.getContext()),
  3537. DAG.getExternalSymbol("__sync_synchronize",
  3538. TLI.getPointerTy(DAG.getDataLayout())),
  3539. std::move(Args));
  3540. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  3541. Results.push_back(CallResult.second);
  3542. break;
  3543. }
  3544. // By default, atomic intrinsics are marked Legal and lowered. Targets
  3545. // which don't support them directly, however, may want libcalls, in which
  3546. // case they mark them Expand, and we get here.
  3547. case ISD::ATOMIC_SWAP:
  3548. case ISD::ATOMIC_LOAD_ADD:
  3549. case ISD::ATOMIC_LOAD_SUB:
  3550. case ISD::ATOMIC_LOAD_AND:
  3551. case ISD::ATOMIC_LOAD_CLR:
  3552. case ISD::ATOMIC_LOAD_OR:
  3553. case ISD::ATOMIC_LOAD_XOR:
  3554. case ISD::ATOMIC_LOAD_NAND:
  3555. case ISD::ATOMIC_LOAD_MIN:
  3556. case ISD::ATOMIC_LOAD_MAX:
  3557. case ISD::ATOMIC_LOAD_UMIN:
  3558. case ISD::ATOMIC_LOAD_UMAX:
  3559. case ISD::ATOMIC_CMP_SWAP: {
  3560. MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
  3561. AtomicOrdering Order = cast<AtomicSDNode>(Node)->getMergedOrdering();
  3562. RTLIB::Libcall LC = RTLIB::getOUTLINE_ATOMIC(Opc, Order, VT);
  3563. EVT RetVT = Node->getValueType(0);
  3564. TargetLowering::MakeLibCallOptions CallOptions;
  3565. SmallVector<SDValue, 4> Ops;
  3566. if (TLI.getLibcallName(LC)) {
  3567. // If outline atomic available, prepare its arguments and expand.
  3568. Ops.append(Node->op_begin() + 2, Node->op_end());
  3569. Ops.push_back(Node->getOperand(1));
  3570. } else {
  3571. LC = RTLIB::getSYNC(Opc, VT);
  3572. assert(LC != RTLIB::UNKNOWN_LIBCALL &&
  3573. "Unexpected atomic op or value type!");
  3574. // Arguments for expansion to sync libcall
  3575. Ops.append(Node->op_begin() + 1, Node->op_end());
  3576. }
  3577. std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT,
  3578. Ops, CallOptions,
  3579. SDLoc(Node),
  3580. Node->getOperand(0));
  3581. Results.push_back(Tmp.first);
  3582. Results.push_back(Tmp.second);
  3583. break;
  3584. }
  3585. case ISD::TRAP: {
  3586. // If this operation is not supported, lower it to 'abort()' call
  3587. TargetLowering::ArgListTy Args;
  3588. TargetLowering::CallLoweringInfo CLI(DAG);
  3589. CLI.setDebugLoc(dl)
  3590. .setChain(Node->getOperand(0))
  3591. .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
  3592. DAG.getExternalSymbol(
  3593. "abort", TLI.getPointerTy(DAG.getDataLayout())),
  3594. std::move(Args));
  3595. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  3596. Results.push_back(CallResult.second);
  3597. break;
  3598. }
  3599. case ISD::FMINNUM:
  3600. case ISD::STRICT_FMINNUM:
  3601. ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64,
  3602. RTLIB::FMIN_F80, RTLIB::FMIN_F128,
  3603. RTLIB::FMIN_PPCF128, Results);
  3604. break;
  3605. case ISD::FMAXNUM:
  3606. case ISD::STRICT_FMAXNUM:
  3607. ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64,
  3608. RTLIB::FMAX_F80, RTLIB::FMAX_F128,
  3609. RTLIB::FMAX_PPCF128, Results);
  3610. break;
  3611. case ISD::FSQRT:
  3612. case ISD::STRICT_FSQRT:
  3613. ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
  3614. RTLIB::SQRT_F80, RTLIB::SQRT_F128,
  3615. RTLIB::SQRT_PPCF128, Results);
  3616. break;
  3617. case ISD::FCBRT:
  3618. ExpandFPLibCall(Node, RTLIB::CBRT_F32, RTLIB::CBRT_F64,
  3619. RTLIB::CBRT_F80, RTLIB::CBRT_F128,
  3620. RTLIB::CBRT_PPCF128, Results);
  3621. break;
  3622. case ISD::FSIN:
  3623. case ISD::STRICT_FSIN:
  3624. ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
  3625. RTLIB::SIN_F80, RTLIB::SIN_F128,
  3626. RTLIB::SIN_PPCF128, Results);
  3627. break;
  3628. case ISD::FCOS:
  3629. case ISD::STRICT_FCOS:
  3630. ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
  3631. RTLIB::COS_F80, RTLIB::COS_F128,
  3632. RTLIB::COS_PPCF128, Results);
  3633. break;
  3634. case ISD::FSINCOS:
  3635. // Expand into sincos libcall.
  3636. ExpandSinCosLibCall(Node, Results);
  3637. break;
  3638. case ISD::FLOG:
  3639. case ISD::STRICT_FLOG:
  3640. ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64, RTLIB::LOG_F80,
  3641. RTLIB::LOG_F128, RTLIB::LOG_PPCF128, Results);
  3642. break;
  3643. case ISD::FLOG2:
  3644. case ISD::STRICT_FLOG2:
  3645. ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64, RTLIB::LOG2_F80,
  3646. RTLIB::LOG2_F128, RTLIB::LOG2_PPCF128, Results);
  3647. break;
  3648. case ISD::FLOG10:
  3649. case ISD::STRICT_FLOG10:
  3650. ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64, RTLIB::LOG10_F80,
  3651. RTLIB::LOG10_F128, RTLIB::LOG10_PPCF128, Results);
  3652. break;
  3653. case ISD::FEXP:
  3654. case ISD::STRICT_FEXP:
  3655. ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64, RTLIB::EXP_F80,
  3656. RTLIB::EXP_F128, RTLIB::EXP_PPCF128, Results);
  3657. break;
  3658. case ISD::FEXP2:
  3659. case ISD::STRICT_FEXP2:
  3660. ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64, RTLIB::EXP2_F80,
  3661. RTLIB::EXP2_F128, RTLIB::EXP2_PPCF128, Results);
  3662. break;
  3663. case ISD::FTRUNC:
  3664. case ISD::STRICT_FTRUNC:
  3665. ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
  3666. RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
  3667. RTLIB::TRUNC_PPCF128, Results);
  3668. break;
  3669. case ISD::FFLOOR:
  3670. case ISD::STRICT_FFLOOR:
  3671. ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
  3672. RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
  3673. RTLIB::FLOOR_PPCF128, Results);
  3674. break;
  3675. case ISD::FCEIL:
  3676. case ISD::STRICT_FCEIL:
  3677. ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
  3678. RTLIB::CEIL_F80, RTLIB::CEIL_F128,
  3679. RTLIB::CEIL_PPCF128, Results);
  3680. break;
  3681. case ISD::FRINT:
  3682. case ISD::STRICT_FRINT:
  3683. ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
  3684. RTLIB::RINT_F80, RTLIB::RINT_F128,
  3685. RTLIB::RINT_PPCF128, Results);
  3686. break;
  3687. case ISD::FNEARBYINT:
  3688. case ISD::STRICT_FNEARBYINT:
  3689. ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
  3690. RTLIB::NEARBYINT_F64,
  3691. RTLIB::NEARBYINT_F80,
  3692. RTLIB::NEARBYINT_F128,
  3693. RTLIB::NEARBYINT_PPCF128, Results);
  3694. break;
  3695. case ISD::FROUND:
  3696. case ISD::STRICT_FROUND:
  3697. ExpandFPLibCall(Node, RTLIB::ROUND_F32,
  3698. RTLIB::ROUND_F64,
  3699. RTLIB::ROUND_F80,
  3700. RTLIB::ROUND_F128,
  3701. RTLIB::ROUND_PPCF128, Results);
  3702. break;
  3703. case ISD::FROUNDEVEN:
  3704. case ISD::STRICT_FROUNDEVEN:
  3705. ExpandFPLibCall(Node, RTLIB::ROUNDEVEN_F32,
  3706. RTLIB::ROUNDEVEN_F64,
  3707. RTLIB::ROUNDEVEN_F80,
  3708. RTLIB::ROUNDEVEN_F128,
  3709. RTLIB::ROUNDEVEN_PPCF128, Results);
  3710. break;
  3711. case ISD::FPOWI:
  3712. case ISD::STRICT_FPOWI: {
  3713. RTLIB::Libcall LC = RTLIB::getPOWI(Node->getSimpleValueType(0));
  3714. assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fpowi.");
  3715. if (!TLI.getLibcallName(LC)) {
  3716. // Some targets don't have a powi libcall; use pow instead.
  3717. SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node),
  3718. Node->getValueType(0),
  3719. Node->getOperand(1));
  3720. Results.push_back(DAG.getNode(ISD::FPOW, SDLoc(Node),
  3721. Node->getValueType(0), Node->getOperand(0),
  3722. Exponent));
  3723. break;
  3724. }
  3725. unsigned Offset = Node->isStrictFPOpcode() ? 1 : 0;
  3726. bool ExponentHasSizeOfInt =
  3727. DAG.getLibInfo().getIntSize() ==
  3728. Node->getOperand(1 + Offset).getValueType().getSizeInBits();
  3729. if (!ExponentHasSizeOfInt) {
  3730. // If the exponent does not match with sizeof(int) a libcall to
  3731. // RTLIB::POWI would use the wrong type for the argument.
  3732. DAG.getContext()->emitError("POWI exponent does not match sizeof(int)");
  3733. Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
  3734. break;
  3735. }
  3736. ExpandFPLibCall(Node, LC, Results);
  3737. break;
  3738. }
  3739. case ISD::FPOW:
  3740. case ISD::STRICT_FPOW:
  3741. ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
  3742. RTLIB::POW_F128, RTLIB::POW_PPCF128, Results);
  3743. break;
  3744. case ISD::LROUND:
  3745. case ISD::STRICT_LROUND:
  3746. ExpandArgFPLibCall(Node, RTLIB::LROUND_F32,
  3747. RTLIB::LROUND_F64, RTLIB::LROUND_F80,
  3748. RTLIB::LROUND_F128,
  3749. RTLIB::LROUND_PPCF128, Results);
  3750. break;
  3751. case ISD::LLROUND:
  3752. case ISD::STRICT_LLROUND:
  3753. ExpandArgFPLibCall(Node, RTLIB::LLROUND_F32,
  3754. RTLIB::LLROUND_F64, RTLIB::LLROUND_F80,
  3755. RTLIB::LLROUND_F128,
  3756. RTLIB::LLROUND_PPCF128, Results);
  3757. break;
  3758. case ISD::LRINT:
  3759. case ISD::STRICT_LRINT:
  3760. ExpandArgFPLibCall(Node, RTLIB::LRINT_F32,
  3761. RTLIB::LRINT_F64, RTLIB::LRINT_F80,
  3762. RTLIB::LRINT_F128,
  3763. RTLIB::LRINT_PPCF128, Results);
  3764. break;
  3765. case ISD::LLRINT:
  3766. case ISD::STRICT_LLRINT:
  3767. ExpandArgFPLibCall(Node, RTLIB::LLRINT_F32,
  3768. RTLIB::LLRINT_F64, RTLIB::LLRINT_F80,
  3769. RTLIB::LLRINT_F128,
  3770. RTLIB::LLRINT_PPCF128, Results);
  3771. break;
  3772. case ISD::FDIV:
  3773. case ISD::STRICT_FDIV:
  3774. ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
  3775. RTLIB::DIV_F80, RTLIB::DIV_F128,
  3776. RTLIB::DIV_PPCF128, Results);
  3777. break;
  3778. case ISD::FREM:
  3779. case ISD::STRICT_FREM:
  3780. ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
  3781. RTLIB::REM_F80, RTLIB::REM_F128,
  3782. RTLIB::REM_PPCF128, Results);
  3783. break;
  3784. case ISD::FMA:
  3785. case ISD::STRICT_FMA:
  3786. ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
  3787. RTLIB::FMA_F80, RTLIB::FMA_F128,
  3788. RTLIB::FMA_PPCF128, Results);
  3789. break;
  3790. case ISD::FADD:
  3791. case ISD::STRICT_FADD:
  3792. ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64,
  3793. RTLIB::ADD_F80, RTLIB::ADD_F128,
  3794. RTLIB::ADD_PPCF128, Results);
  3795. break;
  3796. case ISD::FMUL:
  3797. case ISD::STRICT_FMUL:
  3798. ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64,
  3799. RTLIB::MUL_F80, RTLIB::MUL_F128,
  3800. RTLIB::MUL_PPCF128, Results);
  3801. break;
  3802. case ISD::FP16_TO_FP:
  3803. if (Node->getValueType(0) == MVT::f32) {
  3804. Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
  3805. }
  3806. break;
  3807. case ISD::STRICT_FP16_TO_FP: {
  3808. if (Node->getValueType(0) == MVT::f32) {
  3809. TargetLowering::MakeLibCallOptions CallOptions;
  3810. std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
  3811. DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Node->getOperand(1), CallOptions,
  3812. SDLoc(Node), Node->getOperand(0));
  3813. Results.push_back(Tmp.first);
  3814. Results.push_back(Tmp.second);
  3815. }
  3816. break;
  3817. }
  3818. case ISD::FP_TO_FP16: {
  3819. RTLIB::Libcall LC =
  3820. RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
  3821. assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
  3822. Results.push_back(ExpandLibCall(LC, Node, false));
  3823. break;
  3824. }
  3825. case ISD::STRICT_SINT_TO_FP:
  3826. case ISD::STRICT_UINT_TO_FP:
  3827. case ISD::SINT_TO_FP:
  3828. case ISD::UINT_TO_FP: {
  3829. // TODO - Common the code with DAGTypeLegalizer::SoftenFloatRes_XINT_TO_FP
  3830. bool IsStrict = Node->isStrictFPOpcode();
  3831. bool Signed = Node->getOpcode() == ISD::SINT_TO_FP ||
  3832. Node->getOpcode() == ISD::STRICT_SINT_TO_FP;
  3833. EVT SVT = Node->getOperand(IsStrict ? 1 : 0).getValueType();
  3834. EVT RVT = Node->getValueType(0);
  3835. EVT NVT = EVT();
  3836. SDLoc dl(Node);
  3837. // Even if the input is legal, no libcall may exactly match, eg. we don't
  3838. // have i1 -> fp conversions. So, it needs to be promoted to a larger type,
  3839. // eg: i13 -> fp. Then, look for an appropriate libcall.
  3840. RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
  3841. for (unsigned t = MVT::FIRST_INTEGER_VALUETYPE;
  3842. t <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL;
  3843. ++t) {
  3844. NVT = (MVT::SimpleValueType)t;
  3845. // The source needs to big enough to hold the operand.
  3846. if (NVT.bitsGE(SVT))
  3847. LC = Signed ? RTLIB::getSINTTOFP(NVT, RVT)
  3848. : RTLIB::getUINTTOFP(NVT, RVT);
  3849. }
  3850. assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
  3851. SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
  3852. // Sign/zero extend the argument if the libcall takes a larger type.
  3853. SDValue Op = DAG.getNode(Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, dl,
  3854. NVT, Node->getOperand(IsStrict ? 1 : 0));
  3855. TargetLowering::MakeLibCallOptions CallOptions;
  3856. CallOptions.setSExt(Signed);
  3857. std::pair<SDValue, SDValue> Tmp =
  3858. TLI.makeLibCall(DAG, LC, RVT, Op, CallOptions, dl, Chain);
  3859. Results.push_back(Tmp.first);
  3860. if (IsStrict)
  3861. Results.push_back(Tmp.second);
  3862. break;
  3863. }
  3864. case ISD::FP_TO_SINT:
  3865. case ISD::FP_TO_UINT:
  3866. case ISD::STRICT_FP_TO_SINT:
  3867. case ISD::STRICT_FP_TO_UINT: {
  3868. // TODO - Common the code with DAGTypeLegalizer::SoftenFloatOp_FP_TO_XINT.
  3869. bool IsStrict = Node->isStrictFPOpcode();
  3870. bool Signed = Node->getOpcode() == ISD::FP_TO_SINT ||
  3871. Node->getOpcode() == ISD::STRICT_FP_TO_SINT;
  3872. SDValue Op = Node->getOperand(IsStrict ? 1 : 0);
  3873. EVT SVT = Op.getValueType();
  3874. EVT RVT = Node->getValueType(0);
  3875. EVT NVT = EVT();
  3876. SDLoc dl(Node);
  3877. // Even if the result is legal, no libcall may exactly match, eg. we don't
  3878. // have fp -> i1 conversions. So, it needs to be promoted to a larger type,
  3879. // eg: fp -> i32. Then, look for an appropriate libcall.
  3880. RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
  3881. for (unsigned IntVT = MVT::FIRST_INTEGER_VALUETYPE;
  3882. IntVT <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL;
  3883. ++IntVT) {
  3884. NVT = (MVT::SimpleValueType)IntVT;
  3885. // The type needs to big enough to hold the result.
  3886. if (NVT.bitsGE(RVT))
  3887. LC = Signed ? RTLIB::getFPTOSINT(SVT, NVT)
  3888. : RTLIB::getFPTOUINT(SVT, NVT);
  3889. }
  3890. assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
  3891. SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
  3892. TargetLowering::MakeLibCallOptions CallOptions;
  3893. std::pair<SDValue, SDValue> Tmp =
  3894. TLI.makeLibCall(DAG, LC, NVT, Op, CallOptions, dl, Chain);
  3895. // Truncate the result if the libcall returns a larger type.
  3896. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, RVT, Tmp.first));
  3897. if (IsStrict)
  3898. Results.push_back(Tmp.second);
  3899. break;
  3900. }
  3901. case ISD::FP_ROUND:
  3902. case ISD::STRICT_FP_ROUND: {
  3903. // X = FP_ROUND(Y, TRUNC)
  3904. // TRUNC is a flag, which is always an integer that is zero or one.
  3905. // If TRUNC is 0, this is a normal rounding, if it is 1, this FP_ROUND
  3906. // is known to not change the value of Y.
  3907. // We can only expand it into libcall if the TRUNC is 0.
  3908. bool IsStrict = Node->isStrictFPOpcode();
  3909. SDValue Op = Node->getOperand(IsStrict ? 1 : 0);
  3910. SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
  3911. EVT VT = Node->getValueType(0);
  3912. assert(cast<ConstantSDNode>(Node->getOperand(IsStrict ? 2 : 1))->isZero() &&
  3913. "Unable to expand as libcall if it is not normal rounding");
  3914. RTLIB::Libcall LC = RTLIB::getFPROUND(Op.getValueType(), VT);
  3915. assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
  3916. TargetLowering::MakeLibCallOptions CallOptions;
  3917. std::pair<SDValue, SDValue> Tmp =
  3918. TLI.makeLibCall(DAG, LC, VT, Op, CallOptions, SDLoc(Node), Chain);
  3919. Results.push_back(Tmp.first);
  3920. if (IsStrict)
  3921. Results.push_back(Tmp.second);
  3922. break;
  3923. }
  3924. case ISD::FP_EXTEND: {
  3925. Results.push_back(
  3926. ExpandLibCall(RTLIB::getFPEXT(Node->getOperand(0).getValueType(),
  3927. Node->getValueType(0)),
  3928. Node, false));
  3929. break;
  3930. }
  3931. case ISD::STRICT_FP_EXTEND:
  3932. case ISD::STRICT_FP_TO_FP16: {
  3933. RTLIB::Libcall LC =
  3934. Node->getOpcode() == ISD::STRICT_FP_TO_FP16
  3935. ? RTLIB::getFPROUND(Node->getOperand(1).getValueType(), MVT::f16)
  3936. : RTLIB::getFPEXT(Node->getOperand(1).getValueType(),
  3937. Node->getValueType(0));
  3938. assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
  3939. TargetLowering::MakeLibCallOptions CallOptions;
  3940. std::pair<SDValue, SDValue> Tmp =
  3941. TLI.makeLibCall(DAG, LC, Node->getValueType(0), Node->getOperand(1),
  3942. CallOptions, SDLoc(Node), Node->getOperand(0));
  3943. Results.push_back(Tmp.first);
  3944. Results.push_back(Tmp.second);
  3945. break;
  3946. }
  3947. case ISD::FSUB:
  3948. case ISD::STRICT_FSUB:
  3949. ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64,
  3950. RTLIB::SUB_F80, RTLIB::SUB_F128,
  3951. RTLIB::SUB_PPCF128, Results);
  3952. break;
  3953. case ISD::SREM:
  3954. Results.push_back(ExpandIntLibCall(Node, true,
  3955. RTLIB::SREM_I8,
  3956. RTLIB::SREM_I16, RTLIB::SREM_I32,
  3957. RTLIB::SREM_I64, RTLIB::SREM_I128));
  3958. break;
  3959. case ISD::UREM:
  3960. Results.push_back(ExpandIntLibCall(Node, false,
  3961. RTLIB::UREM_I8,
  3962. RTLIB::UREM_I16, RTLIB::UREM_I32,
  3963. RTLIB::UREM_I64, RTLIB::UREM_I128));
  3964. break;
  3965. case ISD::SDIV:
  3966. Results.push_back(ExpandIntLibCall(Node, true,
  3967. RTLIB::SDIV_I8,
  3968. RTLIB::SDIV_I16, RTLIB::SDIV_I32,
  3969. RTLIB::SDIV_I64, RTLIB::SDIV_I128));
  3970. break;
  3971. case ISD::UDIV:
  3972. Results.push_back(ExpandIntLibCall(Node, false,
  3973. RTLIB::UDIV_I8,
  3974. RTLIB::UDIV_I16, RTLIB::UDIV_I32,
  3975. RTLIB::UDIV_I64, RTLIB::UDIV_I128));
  3976. break;
  3977. case ISD::SDIVREM:
  3978. case ISD::UDIVREM:
  3979. // Expand into divrem libcall
  3980. ExpandDivRemLibCall(Node, Results);
  3981. break;
  3982. case ISD::MUL:
  3983. Results.push_back(ExpandIntLibCall(Node, false,
  3984. RTLIB::MUL_I8,
  3985. RTLIB::MUL_I16, RTLIB::MUL_I32,
  3986. RTLIB::MUL_I64, RTLIB::MUL_I128));
  3987. break;
  3988. case ISD::CTLZ_ZERO_UNDEF:
  3989. switch (Node->getSimpleValueType(0).SimpleTy) {
  3990. default:
  3991. llvm_unreachable("LibCall explicitly requested, but not available");
  3992. case MVT::i32:
  3993. Results.push_back(ExpandLibCall(RTLIB::CTLZ_I32, Node, false));
  3994. break;
  3995. case MVT::i64:
  3996. Results.push_back(ExpandLibCall(RTLIB::CTLZ_I64, Node, false));
  3997. break;
  3998. case MVT::i128:
  3999. Results.push_back(ExpandLibCall(RTLIB::CTLZ_I128, Node, false));
  4000. break;
  4001. }
  4002. break;
  4003. }
  4004. // Replace the original node with the legalized result.
  4005. if (!Results.empty()) {
  4006. LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n");
  4007. ReplaceNode(Node, Results.data());
  4008. } else
  4009. LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n");
  4010. }
  4011. // Determine the vector type to use in place of an original scalar element when
  4012. // promoting equally sized vectors.
  4013. static MVT getPromotedVectorElementType(const TargetLowering &TLI,
  4014. MVT EltVT, MVT NewEltVT) {
  4015. unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
  4016. MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
  4017. assert(TLI.isTypeLegal(MidVT) && "unexpected");
  4018. return MidVT;
  4019. }
  4020. void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
  4021. LLVM_DEBUG(dbgs() << "Trying to promote node\n");
  4022. SmallVector<SDValue, 8> Results;
  4023. MVT OVT = Node->getSimpleValueType(0);
  4024. if (Node->getOpcode() == ISD::UINT_TO_FP ||
  4025. Node->getOpcode() == ISD::SINT_TO_FP ||
  4026. Node->getOpcode() == ISD::SETCC ||
  4027. Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
  4028. Node->getOpcode() == ISD::INSERT_VECTOR_ELT) {
  4029. OVT = Node->getOperand(0).getSimpleValueType();
  4030. }
  4031. if (Node->getOpcode() == ISD::STRICT_UINT_TO_FP ||
  4032. Node->getOpcode() == ISD::STRICT_SINT_TO_FP ||
  4033. Node->getOpcode() == ISD::STRICT_FSETCC ||
  4034. Node->getOpcode() == ISD::STRICT_FSETCCS)
  4035. OVT = Node->getOperand(1).getSimpleValueType();
  4036. if (Node->getOpcode() == ISD::BR_CC ||
  4037. Node->getOpcode() == ISD::SELECT_CC)
  4038. OVT = Node->getOperand(2).getSimpleValueType();
  4039. MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
  4040. SDLoc dl(Node);
  4041. SDValue Tmp1, Tmp2, Tmp3, Tmp4;
  4042. switch (Node->getOpcode()) {
  4043. case ISD::CTTZ:
  4044. case ISD::CTTZ_ZERO_UNDEF:
  4045. case ISD::CTLZ:
  4046. case ISD::CTLZ_ZERO_UNDEF:
  4047. case ISD::CTPOP:
  4048. // Zero extend the argument unless its cttz, then use any_extend.
  4049. if (Node->getOpcode() == ISD::CTTZ ||
  4050. Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF)
  4051. Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
  4052. else
  4053. Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
  4054. if (Node->getOpcode() == ISD::CTTZ) {
  4055. // The count is the same in the promoted type except if the original
  4056. // value was zero. This can be handled by setting the bit just off
  4057. // the top of the original type.
  4058. auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(),
  4059. OVT.getSizeInBits());
  4060. Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1,
  4061. DAG.getConstant(TopBit, dl, NVT));
  4062. }
  4063. // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
  4064. // already the correct result.
  4065. Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
  4066. if (Node->getOpcode() == ISD::CTLZ ||
  4067. Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
  4068. // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
  4069. Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
  4070. DAG.getConstant(NVT.getSizeInBits() -
  4071. OVT.getSizeInBits(), dl, NVT));
  4072. }
  4073. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
  4074. break;
  4075. case ISD::BITREVERSE:
  4076. case ISD::BSWAP: {
  4077. unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
  4078. Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
  4079. Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
  4080. Tmp1 = DAG.getNode(
  4081. ISD::SRL, dl, NVT, Tmp1,
  4082. DAG.getConstant(DiffBits, dl,
  4083. TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
  4084. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
  4085. break;
  4086. }
  4087. case ISD::FP_TO_UINT:
  4088. case ISD::STRICT_FP_TO_UINT:
  4089. case ISD::FP_TO_SINT:
  4090. case ISD::STRICT_FP_TO_SINT:
  4091. PromoteLegalFP_TO_INT(Node, dl, Results);
  4092. break;
  4093. case ISD::FP_TO_UINT_SAT:
  4094. case ISD::FP_TO_SINT_SAT:
  4095. Results.push_back(PromoteLegalFP_TO_INT_SAT(Node, dl));
  4096. break;
  4097. case ISD::UINT_TO_FP:
  4098. case ISD::STRICT_UINT_TO_FP:
  4099. case ISD::SINT_TO_FP:
  4100. case ISD::STRICT_SINT_TO_FP:
  4101. PromoteLegalINT_TO_FP(Node, dl, Results);
  4102. break;
  4103. case ISD::VAARG: {
  4104. SDValue Chain = Node->getOperand(0); // Get the chain.
  4105. SDValue Ptr = Node->getOperand(1); // Get the pointer.
  4106. unsigned TruncOp;
  4107. if (OVT.isVector()) {
  4108. TruncOp = ISD::BITCAST;
  4109. } else {
  4110. assert(OVT.isInteger()
  4111. && "VAARG promotion is supported only for vectors or integer types");
  4112. TruncOp = ISD::TRUNCATE;
  4113. }
  4114. // Perform the larger operation, then convert back
  4115. Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
  4116. Node->getConstantOperandVal(3));
  4117. Chain = Tmp1.getValue(1);
  4118. Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
  4119. // Modified the chain result - switch anything that used the old chain to
  4120. // use the new one.
  4121. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
  4122. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
  4123. if (UpdatedNodes) {
  4124. UpdatedNodes->insert(Tmp2.getNode());
  4125. UpdatedNodes->insert(Chain.getNode());
  4126. }
  4127. ReplacedNode(Node);
  4128. break;
  4129. }
  4130. case ISD::MUL:
  4131. case ISD::SDIV:
  4132. case ISD::SREM:
  4133. case ISD::UDIV:
  4134. case ISD::UREM:
  4135. case ISD::AND:
  4136. case ISD::OR:
  4137. case ISD::XOR: {
  4138. unsigned ExtOp, TruncOp;
  4139. if (OVT.isVector()) {
  4140. ExtOp = ISD::BITCAST;
  4141. TruncOp = ISD::BITCAST;
  4142. } else {
  4143. assert(OVT.isInteger() && "Cannot promote logic operation");
  4144. switch (Node->getOpcode()) {
  4145. default:
  4146. ExtOp = ISD::ANY_EXTEND;
  4147. break;
  4148. case ISD::SDIV:
  4149. case ISD::SREM:
  4150. ExtOp = ISD::SIGN_EXTEND;
  4151. break;
  4152. case ISD::UDIV:
  4153. case ISD::UREM:
  4154. ExtOp = ISD::ZERO_EXTEND;
  4155. break;
  4156. }
  4157. TruncOp = ISD::TRUNCATE;
  4158. }
  4159. // Promote each of the values to the new type.
  4160. Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
  4161. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
  4162. // Perform the larger operation, then convert back
  4163. Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
  4164. Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
  4165. break;
  4166. }
  4167. case ISD::UMUL_LOHI:
  4168. case ISD::SMUL_LOHI: {
  4169. // Promote to a multiply in a wider integer type.
  4170. unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND
  4171. : ISD::SIGN_EXTEND;
  4172. Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
  4173. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
  4174. Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2);
  4175. auto &DL = DAG.getDataLayout();
  4176. unsigned OriginalSize = OVT.getScalarSizeInBits();
  4177. Tmp2 = DAG.getNode(
  4178. ISD::SRL, dl, NVT, Tmp1,
  4179. DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT)));
  4180. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
  4181. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
  4182. break;
  4183. }
  4184. case ISD::SELECT: {
  4185. unsigned ExtOp, TruncOp;
  4186. if (Node->getValueType(0).isVector() ||
  4187. Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
  4188. ExtOp = ISD::BITCAST;
  4189. TruncOp = ISD::BITCAST;
  4190. } else if (Node->getValueType(0).isInteger()) {
  4191. ExtOp = ISD::ANY_EXTEND;
  4192. TruncOp = ISD::TRUNCATE;
  4193. } else {
  4194. ExtOp = ISD::FP_EXTEND;
  4195. TruncOp = ISD::FP_ROUND;
  4196. }
  4197. Tmp1 = Node->getOperand(0);
  4198. // Promote each of the values to the new type.
  4199. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
  4200. Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
  4201. // Perform the larger operation, then round down.
  4202. Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
  4203. Tmp1->setFlags(Node->getFlags());
  4204. if (TruncOp != ISD::FP_ROUND)
  4205. Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
  4206. else
  4207. Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
  4208. DAG.getIntPtrConstant(0, dl));
  4209. Results.push_back(Tmp1);
  4210. break;
  4211. }
  4212. case ISD::VECTOR_SHUFFLE: {
  4213. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
  4214. // Cast the two input vectors.
  4215. Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
  4216. Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
  4217. // Convert the shuffle mask to the right # elements.
  4218. Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
  4219. Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
  4220. Results.push_back(Tmp1);
  4221. break;
  4222. }
  4223. case ISD::VECTOR_SPLICE: {
  4224. Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
  4225. Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(1));
  4226. Tmp3 = DAG.getNode(ISD::VECTOR_SPLICE, dl, NVT, Tmp1, Tmp2,
  4227. Node->getOperand(2));
  4228. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp3));
  4229. break;
  4230. }
  4231. case ISD::SELECT_CC: {
  4232. SDValue Cond = Node->getOperand(4);
  4233. ISD::CondCode CCCode = cast<CondCodeSDNode>(Cond)->get();
  4234. // Type of the comparison operands.
  4235. MVT CVT = Node->getSimpleValueType(0);
  4236. assert(CVT == OVT && "not handled");
  4237. unsigned ExtOp = ISD::FP_EXTEND;
  4238. if (NVT.isInteger()) {
  4239. ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  4240. }
  4241. // Promote the comparison operands, if needed.
  4242. if (TLI.isCondCodeLegal(CCCode, CVT)) {
  4243. Tmp1 = Node->getOperand(0);
  4244. Tmp2 = Node->getOperand(1);
  4245. } else {
  4246. Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
  4247. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
  4248. }
  4249. // Cast the true/false operands.
  4250. Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
  4251. Tmp4 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
  4252. Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, NVT, {Tmp1, Tmp2, Tmp3, Tmp4, Cond},
  4253. Node->getFlags());
  4254. // Cast the result back to the original type.
  4255. if (ExtOp != ISD::FP_EXTEND)
  4256. Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1);
  4257. else
  4258. Tmp1 = DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp1,
  4259. DAG.getIntPtrConstant(0, dl));
  4260. Results.push_back(Tmp1);
  4261. break;
  4262. }
  4263. case ISD::SETCC:
  4264. case ISD::STRICT_FSETCC:
  4265. case ISD::STRICT_FSETCCS: {
  4266. unsigned ExtOp = ISD::FP_EXTEND;
  4267. if (NVT.isInteger()) {
  4268. ISD::CondCode CCCode = cast<CondCodeSDNode>(Node->getOperand(2))->get();
  4269. ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  4270. }
  4271. if (Node->isStrictFPOpcode()) {
  4272. SDValue InChain = Node->getOperand(0);
  4273. std::tie(Tmp1, std::ignore) =
  4274. DAG.getStrictFPExtendOrRound(Node->getOperand(1), InChain, dl, NVT);
  4275. std::tie(Tmp2, std::ignore) =
  4276. DAG.getStrictFPExtendOrRound(Node->getOperand(2), InChain, dl, NVT);
  4277. SmallVector<SDValue, 2> TmpChains = {Tmp1.getValue(1), Tmp2.getValue(1)};
  4278. SDValue OutChain = DAG.getTokenFactor(dl, TmpChains);
  4279. SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
  4280. Results.push_back(DAG.getNode(Node->getOpcode(), dl, VTs,
  4281. {OutChain, Tmp1, Tmp2, Node->getOperand(3)},
  4282. Node->getFlags()));
  4283. Results.push_back(Results.back().getValue(1));
  4284. break;
  4285. }
  4286. Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
  4287. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
  4288. Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), Tmp1,
  4289. Tmp2, Node->getOperand(2), Node->getFlags()));
  4290. break;
  4291. }
  4292. case ISD::BR_CC: {
  4293. unsigned ExtOp = ISD::FP_EXTEND;
  4294. if (NVT.isInteger()) {
  4295. ISD::CondCode CCCode =
  4296. cast<CondCodeSDNode>(Node->getOperand(1))->get();
  4297. ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  4298. }
  4299. Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
  4300. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
  4301. Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
  4302. Node->getOperand(0), Node->getOperand(1),
  4303. Tmp1, Tmp2, Node->getOperand(4)));
  4304. break;
  4305. }
  4306. case ISD::FADD:
  4307. case ISD::FSUB:
  4308. case ISD::FMUL:
  4309. case ISD::FDIV:
  4310. case ISD::FREM:
  4311. case ISD::FMINNUM:
  4312. case ISD::FMAXNUM:
  4313. case ISD::FPOW:
  4314. Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
  4315. Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
  4316. Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
  4317. Node->getFlags());
  4318. Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
  4319. Tmp3, DAG.getIntPtrConstant(0, dl)));
  4320. break;
  4321. case ISD::STRICT_FREM:
  4322. case ISD::STRICT_FPOW:
  4323. Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
  4324. {Node->getOperand(0), Node->getOperand(1)});
  4325. Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
  4326. {Node->getOperand(0), Node->getOperand(2)});
  4327. Tmp3 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1),
  4328. Tmp2.getValue(1));
  4329. Tmp1 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
  4330. {Tmp3, Tmp1, Tmp2});
  4331. Tmp1 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
  4332. {Tmp1.getValue(1), Tmp1, DAG.getIntPtrConstant(0, dl)});
  4333. Results.push_back(Tmp1);
  4334. Results.push_back(Tmp1.getValue(1));
  4335. break;
  4336. case ISD::FMA:
  4337. Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
  4338. Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
  4339. Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
  4340. Results.push_back(
  4341. DAG.getNode(ISD::FP_ROUND, dl, OVT,
  4342. DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
  4343. DAG.getIntPtrConstant(0, dl)));
  4344. break;
  4345. case ISD::FCOPYSIGN:
  4346. case ISD::FPOWI: {
  4347. Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
  4348. Tmp2 = Node->getOperand(1);
  4349. Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
  4350. // fcopysign doesn't change anything but the sign bit, so
  4351. // (fp_round (fcopysign (fpext a), b))
  4352. // is as precise as
  4353. // (fp_round (fpext a))
  4354. // which is a no-op. Mark it as a TRUNCating FP_ROUND.
  4355. const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
  4356. Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
  4357. Tmp3, DAG.getIntPtrConstant(isTrunc, dl)));
  4358. break;
  4359. }
  4360. case ISD::FFLOOR:
  4361. case ISD::FCEIL:
  4362. case ISD::FRINT:
  4363. case ISD::FNEARBYINT:
  4364. case ISD::FROUND:
  4365. case ISD::FROUNDEVEN:
  4366. case ISD::FTRUNC:
  4367. case ISD::FNEG:
  4368. case ISD::FSQRT:
  4369. case ISD::FSIN:
  4370. case ISD::FCOS:
  4371. case ISD::FLOG:
  4372. case ISD::FLOG2:
  4373. case ISD::FLOG10:
  4374. case ISD::FABS:
  4375. case ISD::FEXP:
  4376. case ISD::FEXP2:
  4377. Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
  4378. Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
  4379. Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
  4380. Tmp2, DAG.getIntPtrConstant(0, dl)));
  4381. break;
  4382. case ISD::STRICT_FFLOOR:
  4383. case ISD::STRICT_FCEIL:
  4384. case ISD::STRICT_FROUND:
  4385. case ISD::STRICT_FSIN:
  4386. case ISD::STRICT_FCOS:
  4387. case ISD::STRICT_FLOG:
  4388. case ISD::STRICT_FLOG10:
  4389. case ISD::STRICT_FEXP:
  4390. Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
  4391. {Node->getOperand(0), Node->getOperand(1)});
  4392. Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
  4393. {Tmp1.getValue(1), Tmp1});
  4394. Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
  4395. {Tmp2.getValue(1), Tmp2, DAG.getIntPtrConstant(0, dl)});
  4396. Results.push_back(Tmp3);
  4397. Results.push_back(Tmp3.getValue(1));
  4398. break;
  4399. case ISD::BUILD_VECTOR: {
  4400. MVT EltVT = OVT.getVectorElementType();
  4401. MVT NewEltVT = NVT.getVectorElementType();
  4402. // Handle bitcasts to a different vector type with the same total bit size
  4403. //
  4404. // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
  4405. // =>
  4406. // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
  4407. assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
  4408. "Invalid promote type for build_vector");
  4409. assert(NewEltVT.bitsLT(EltVT) && "not handled");
  4410. MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
  4411. SmallVector<SDValue, 8> NewOps;
  4412. for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
  4413. SDValue Op = Node->getOperand(I);
  4414. NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
  4415. }
  4416. SDLoc SL(Node);
  4417. SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps);
  4418. SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
  4419. Results.push_back(CvtVec);
  4420. break;
  4421. }
  4422. case ISD::EXTRACT_VECTOR_ELT: {
  4423. MVT EltVT = OVT.getVectorElementType();
  4424. MVT NewEltVT = NVT.getVectorElementType();
  4425. // Handle bitcasts to a different vector type with the same total bit size.
  4426. //
  4427. // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
  4428. // =>
  4429. // v4i32:castx = bitcast x:v2i64
  4430. //
  4431. // i64 = bitcast
  4432. // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
  4433. // (i32 (extract_vector_elt castx, (2 * y + 1)))
  4434. //
  4435. assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
  4436. "Invalid promote type for extract_vector_elt");
  4437. assert(NewEltVT.bitsLT(EltVT) && "not handled");
  4438. MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
  4439. unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
  4440. SDValue Idx = Node->getOperand(1);
  4441. EVT IdxVT = Idx.getValueType();
  4442. SDLoc SL(Node);
  4443. SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
  4444. SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
  4445. SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
  4446. SmallVector<SDValue, 8> NewOps;
  4447. for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
  4448. SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
  4449. SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
  4450. SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
  4451. CastVec, TmpIdx);
  4452. NewOps.push_back(Elt);
  4453. }
  4454. SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps);
  4455. Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
  4456. break;
  4457. }
  4458. case ISD::INSERT_VECTOR_ELT: {
  4459. MVT EltVT = OVT.getVectorElementType();
  4460. MVT NewEltVT = NVT.getVectorElementType();
  4461. // Handle bitcasts to a different vector type with the same total bit size
  4462. //
  4463. // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
  4464. // =>
  4465. // v4i32:castx = bitcast x:v2i64
  4466. // v2i32:casty = bitcast y:i64
  4467. //
  4468. // v2i64 = bitcast
  4469. // (v4i32 insert_vector_elt
  4470. // (v4i32 insert_vector_elt v4i32:castx,
  4471. // (extract_vector_elt casty, 0), 2 * z),
  4472. // (extract_vector_elt casty, 1), (2 * z + 1))
  4473. assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
  4474. "Invalid promote type for insert_vector_elt");
  4475. assert(NewEltVT.bitsLT(EltVT) && "not handled");
  4476. MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
  4477. unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
  4478. SDValue Val = Node->getOperand(1);
  4479. SDValue Idx = Node->getOperand(2);
  4480. EVT IdxVT = Idx.getValueType();
  4481. SDLoc SL(Node);
  4482. SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
  4483. SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
  4484. SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
  4485. SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
  4486. SDValue NewVec = CastVec;
  4487. for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
  4488. SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
  4489. SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
  4490. SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
  4491. CastVal, IdxOffset);
  4492. NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
  4493. NewVec, Elt, InEltIdx);
  4494. }
  4495. Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
  4496. break;
  4497. }
  4498. case ISD::SCALAR_TO_VECTOR: {
  4499. MVT EltVT = OVT.getVectorElementType();
  4500. MVT NewEltVT = NVT.getVectorElementType();
  4501. // Handle bitcasts to different vector type with the same total bit size.
  4502. //
  4503. // e.g. v2i64 = scalar_to_vector x:i64
  4504. // =>
  4505. // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
  4506. //
  4507. MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
  4508. SDValue Val = Node->getOperand(0);
  4509. SDLoc SL(Node);
  4510. SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
  4511. SDValue Undef = DAG.getUNDEF(MidVT);
  4512. SmallVector<SDValue, 8> NewElts;
  4513. NewElts.push_back(CastVal);
  4514. for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
  4515. NewElts.push_back(Undef);
  4516. SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
  4517. SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
  4518. Results.push_back(CvtVec);
  4519. break;
  4520. }
  4521. case ISD::ATOMIC_SWAP: {
  4522. AtomicSDNode *AM = cast<AtomicSDNode>(Node);
  4523. SDLoc SL(Node);
  4524. SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal());
  4525. assert(NVT.getSizeInBits() == OVT.getSizeInBits() &&
  4526. "unexpected promotion type");
  4527. assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() &&
  4528. "unexpected atomic_swap with illegal type");
  4529. SDValue NewAtomic
  4530. = DAG.getAtomic(ISD::ATOMIC_SWAP, SL, NVT,
  4531. DAG.getVTList(NVT, MVT::Other),
  4532. { AM->getChain(), AM->getBasePtr(), CastVal },
  4533. AM->getMemOperand());
  4534. Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic));
  4535. Results.push_back(NewAtomic.getValue(1));
  4536. break;
  4537. }
  4538. }
  4539. // Replace the original node with the legalized result.
  4540. if (!Results.empty()) {
  4541. LLVM_DEBUG(dbgs() << "Successfully promoted node\n");
  4542. ReplaceNode(Node, Results.data());
  4543. } else
  4544. LLVM_DEBUG(dbgs() << "Could not promote node\n");
  4545. }
  4546. /// This is the entry point for the file.
  4547. void SelectionDAG::Legalize() {
  4548. AssignTopologicalOrder();
  4549. SmallPtrSet<SDNode *, 16> LegalizedNodes;
  4550. // Use a delete listener to remove nodes which were deleted during
  4551. // legalization from LegalizeNodes. This is needed to handle the situation
  4552. // where a new node is allocated by the object pool to the same address of a
  4553. // previously deleted node.
  4554. DAGNodeDeletedListener DeleteListener(
  4555. *this,
  4556. [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); });
  4557. SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
  4558. // Visit all the nodes. We start in topological order, so that we see
  4559. // nodes with their original operands intact. Legalization can produce
  4560. // new nodes which may themselves need to be legalized. Iterate until all
  4561. // nodes have been legalized.
  4562. while (true) {
  4563. bool AnyLegalized = false;
  4564. for (auto NI = allnodes_end(); NI != allnodes_begin();) {
  4565. --NI;
  4566. SDNode *N = &*NI;
  4567. if (N->use_empty() && N != getRoot().getNode()) {
  4568. ++NI;
  4569. DeleteNode(N);
  4570. continue;
  4571. }
  4572. if (LegalizedNodes.insert(N).second) {
  4573. AnyLegalized = true;
  4574. Legalizer.LegalizeOp(N);
  4575. if (N->use_empty() && N != getRoot().getNode()) {
  4576. ++NI;
  4577. DeleteNode(N);
  4578. }
  4579. }
  4580. }
  4581. if (!AnyLegalized)
  4582. break;
  4583. }
  4584. // Remove dead nodes now.
  4585. RemoveDeadNodes();
  4586. }
  4587. bool SelectionDAG::LegalizeOp(SDNode *N,
  4588. SmallSetVector<SDNode *, 16> &UpdatedNodes) {
  4589. SmallPtrSet<SDNode *, 16> LegalizedNodes;
  4590. SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
  4591. // Directly insert the node in question, and legalize it. This will recurse
  4592. // as needed through operands.
  4593. LegalizedNodes.insert(N);
  4594. Legalizer.LegalizeOp(N);
  4595. return LegalizedNodes.count(N);
  4596. }