X86FastISel.cpp 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015
  1. //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
  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 defines the X86-specific support for the FastISel class. Much
  10. // of the target-specific code is generated by tablegen in the file
  11. // X86GenFastISel.inc, which is #included here.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "X86.h"
  15. #include "X86CallingConv.h"
  16. #include "X86InstrBuilder.h"
  17. #include "X86InstrInfo.h"
  18. #include "X86MachineFunctionInfo.h"
  19. #include "X86RegisterInfo.h"
  20. #include "X86Subtarget.h"
  21. #include "X86TargetMachine.h"
  22. #include "llvm/Analysis/BranchProbabilityInfo.h"
  23. #include "llvm/CodeGen/FastISel.h"
  24. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  25. #include "llvm/CodeGen/MachineConstantPool.h"
  26. #include "llvm/CodeGen/MachineFrameInfo.h"
  27. #include "llvm/CodeGen/MachineRegisterInfo.h"
  28. #include "llvm/IR/CallingConv.h"
  29. #include "llvm/IR/DebugInfo.h"
  30. #include "llvm/IR/DerivedTypes.h"
  31. #include "llvm/IR/GetElementPtrTypeIterator.h"
  32. #include "llvm/IR/GlobalAlias.h"
  33. #include "llvm/IR/GlobalVariable.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/IntrinsicInst.h"
  36. #include "llvm/IR/IntrinsicsX86.h"
  37. #include "llvm/IR/Operator.h"
  38. #include "llvm/MC/MCAsmInfo.h"
  39. #include "llvm/MC/MCSymbol.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Target/TargetOptions.h"
  42. using namespace llvm;
  43. namespace {
  44. class X86FastISel final : public FastISel {
  45. /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
  46. /// make the right decision when generating code for different targets.
  47. const X86Subtarget *Subtarget;
  48. public:
  49. explicit X86FastISel(FunctionLoweringInfo &funcInfo,
  50. const TargetLibraryInfo *libInfo)
  51. : FastISel(funcInfo, libInfo) {
  52. Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
  53. }
  54. bool fastSelectInstruction(const Instruction *I) override;
  55. /// The specified machine instr operand is a vreg, and that
  56. /// vreg is being provided by the specified load instruction. If possible,
  57. /// try to fold the load as an operand to the instruction, returning true if
  58. /// possible.
  59. bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
  60. const LoadInst *LI) override;
  61. bool fastLowerArguments() override;
  62. bool fastLowerCall(CallLoweringInfo &CLI) override;
  63. bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
  64. #include "X86GenFastISel.inc"
  65. private:
  66. bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
  67. const DebugLoc &DL);
  68. bool X86FastEmitLoad(MVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
  69. unsigned &ResultReg, unsigned Alignment = 1);
  70. bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
  71. MachineMemOperand *MMO = nullptr, bool Aligned = false);
  72. bool X86FastEmitStore(EVT VT, unsigned ValReg, X86AddressMode &AM,
  73. MachineMemOperand *MMO = nullptr, bool Aligned = false);
  74. bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
  75. unsigned &ResultReg);
  76. bool X86SelectAddress(const Value *V, X86AddressMode &AM);
  77. bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
  78. bool X86SelectLoad(const Instruction *I);
  79. bool X86SelectStore(const Instruction *I);
  80. bool X86SelectRet(const Instruction *I);
  81. bool X86SelectCmp(const Instruction *I);
  82. bool X86SelectZExt(const Instruction *I);
  83. bool X86SelectSExt(const Instruction *I);
  84. bool X86SelectBranch(const Instruction *I);
  85. bool X86SelectShift(const Instruction *I);
  86. bool X86SelectDivRem(const Instruction *I);
  87. bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
  88. bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
  89. bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
  90. bool X86SelectSelect(const Instruction *I);
  91. bool X86SelectTrunc(const Instruction *I);
  92. bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
  93. const TargetRegisterClass *RC);
  94. bool X86SelectFPExt(const Instruction *I);
  95. bool X86SelectFPTrunc(const Instruction *I);
  96. bool X86SelectSIToFP(const Instruction *I);
  97. bool X86SelectUIToFP(const Instruction *I);
  98. bool X86SelectIntToFP(const Instruction *I, bool IsSigned);
  99. const X86InstrInfo *getInstrInfo() const {
  100. return Subtarget->getInstrInfo();
  101. }
  102. const X86TargetMachine *getTargetMachine() const {
  103. return static_cast<const X86TargetMachine *>(&TM);
  104. }
  105. bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
  106. unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
  107. unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
  108. unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
  109. unsigned fastMaterializeConstant(const Constant *C) override;
  110. unsigned fastMaterializeAlloca(const AllocaInst *C) override;
  111. unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
  112. /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
  113. /// computed in an SSE register, not on the X87 floating point stack.
  114. bool isScalarFPTypeInSSEReg(EVT VT) const {
  115. return (VT == MVT::f64 && Subtarget->hasSSE2()) ||
  116. (VT == MVT::f32 && Subtarget->hasSSE1()) || VT == MVT::f16;
  117. }
  118. bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
  119. bool IsMemcpySmall(uint64_t Len);
  120. bool TryEmitSmallMemcpy(X86AddressMode DestAM,
  121. X86AddressMode SrcAM, uint64_t Len);
  122. bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
  123. const Value *Cond);
  124. const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
  125. X86AddressMode &AM);
  126. unsigned fastEmitInst_rrrr(unsigned MachineInstOpcode,
  127. const TargetRegisterClass *RC, unsigned Op0,
  128. unsigned Op1, unsigned Op2, unsigned Op3);
  129. };
  130. } // end anonymous namespace.
  131. static std::pair<unsigned, bool>
  132. getX86SSEConditionCode(CmpInst::Predicate Predicate) {
  133. unsigned CC;
  134. bool NeedSwap = false;
  135. // SSE Condition code mapping:
  136. // 0 - EQ
  137. // 1 - LT
  138. // 2 - LE
  139. // 3 - UNORD
  140. // 4 - NEQ
  141. // 5 - NLT
  142. // 6 - NLE
  143. // 7 - ORD
  144. switch (Predicate) {
  145. default: llvm_unreachable("Unexpected predicate");
  146. case CmpInst::FCMP_OEQ: CC = 0; break;
  147. case CmpInst::FCMP_OGT: NeedSwap = true; [[fallthrough]];
  148. case CmpInst::FCMP_OLT: CC = 1; break;
  149. case CmpInst::FCMP_OGE: NeedSwap = true; [[fallthrough]];
  150. case CmpInst::FCMP_OLE: CC = 2; break;
  151. case CmpInst::FCMP_UNO: CC = 3; break;
  152. case CmpInst::FCMP_UNE: CC = 4; break;
  153. case CmpInst::FCMP_ULE: NeedSwap = true; [[fallthrough]];
  154. case CmpInst::FCMP_UGE: CC = 5; break;
  155. case CmpInst::FCMP_ULT: NeedSwap = true; [[fallthrough]];
  156. case CmpInst::FCMP_UGT: CC = 6; break;
  157. case CmpInst::FCMP_ORD: CC = 7; break;
  158. case CmpInst::FCMP_UEQ: CC = 8; break;
  159. case CmpInst::FCMP_ONE: CC = 12; break;
  160. }
  161. return std::make_pair(CC, NeedSwap);
  162. }
  163. /// Adds a complex addressing mode to the given machine instr builder.
  164. /// Note, this will constrain the index register. If its not possible to
  165. /// constrain the given index register, then a new one will be created. The
  166. /// IndexReg field of the addressing mode will be updated to match in this case.
  167. const MachineInstrBuilder &
  168. X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
  169. X86AddressMode &AM) {
  170. // First constrain the index register. It needs to be a GR64_NOSP.
  171. AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
  172. MIB->getNumOperands() +
  173. X86::AddrIndexReg);
  174. return ::addFullAddress(MIB, AM);
  175. }
  176. /// Check if it is possible to fold the condition from the XALU intrinsic
  177. /// into the user. The condition code will only be updated on success.
  178. bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
  179. const Value *Cond) {
  180. if (!isa<ExtractValueInst>(Cond))
  181. return false;
  182. const auto *EV = cast<ExtractValueInst>(Cond);
  183. if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
  184. return false;
  185. const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
  186. MVT RetVT;
  187. const Function *Callee = II->getCalledFunction();
  188. Type *RetTy =
  189. cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
  190. if (!isTypeLegal(RetTy, RetVT))
  191. return false;
  192. if (RetVT != MVT::i32 && RetVT != MVT::i64)
  193. return false;
  194. X86::CondCode TmpCC;
  195. switch (II->getIntrinsicID()) {
  196. default: return false;
  197. case Intrinsic::sadd_with_overflow:
  198. case Intrinsic::ssub_with_overflow:
  199. case Intrinsic::smul_with_overflow:
  200. case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
  201. case Intrinsic::uadd_with_overflow:
  202. case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
  203. }
  204. // Check if both instructions are in the same basic block.
  205. if (II->getParent() != I->getParent())
  206. return false;
  207. // Make sure nothing is in the way
  208. BasicBlock::const_iterator Start(I);
  209. BasicBlock::const_iterator End(II);
  210. for (auto Itr = std::prev(Start); Itr != End; --Itr) {
  211. // We only expect extractvalue instructions between the intrinsic and the
  212. // instruction to be selected.
  213. if (!isa<ExtractValueInst>(Itr))
  214. return false;
  215. // Check that the extractvalue operand comes from the intrinsic.
  216. const auto *EVI = cast<ExtractValueInst>(Itr);
  217. if (EVI->getAggregateOperand() != II)
  218. return false;
  219. }
  220. // Make sure no potentially eflags clobbering phi moves can be inserted in
  221. // between.
  222. auto HasPhis = [](const BasicBlock *Succ) { return !Succ->phis().empty(); };
  223. if (I->isTerminator() && llvm::any_of(successors(I), HasPhis))
  224. return false;
  225. // Make sure there are no potentially eflags clobbering constant
  226. // materializations in between.
  227. if (llvm::any_of(I->operands(), [](Value *V) { return isa<Constant>(V); }))
  228. return false;
  229. CC = TmpCC;
  230. return true;
  231. }
  232. bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
  233. EVT evt = TLI.getValueType(DL, Ty, /*AllowUnknown=*/true);
  234. if (evt == MVT::Other || !evt.isSimple())
  235. // Unhandled type. Halt "fast" selection and bail.
  236. return false;
  237. VT = evt.getSimpleVT();
  238. // For now, require SSE/SSE2 for performing floating-point operations,
  239. // since x87 requires additional work.
  240. if (VT == MVT::f64 && !Subtarget->hasSSE2())
  241. return false;
  242. if (VT == MVT::f32 && !Subtarget->hasSSE1())
  243. return false;
  244. // Similarly, no f80 support yet.
  245. if (VT == MVT::f80)
  246. return false;
  247. // We only handle legal types. For example, on x86-32 the instruction
  248. // selector contains all of the 64-bit instructions from x86-64,
  249. // under the assumption that i64 won't be used if the target doesn't
  250. // support it.
  251. return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
  252. }
  253. /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
  254. /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
  255. /// Return true and the result register by reference if it is possible.
  256. bool X86FastISel::X86FastEmitLoad(MVT VT, X86AddressMode &AM,
  257. MachineMemOperand *MMO, unsigned &ResultReg,
  258. unsigned Alignment) {
  259. bool HasSSE1 = Subtarget->hasSSE1();
  260. bool HasSSE2 = Subtarget->hasSSE2();
  261. bool HasSSE41 = Subtarget->hasSSE41();
  262. bool HasAVX = Subtarget->hasAVX();
  263. bool HasAVX2 = Subtarget->hasAVX2();
  264. bool HasAVX512 = Subtarget->hasAVX512();
  265. bool HasVLX = Subtarget->hasVLX();
  266. bool IsNonTemporal = MMO && MMO->isNonTemporal();
  267. // Treat i1 loads the same as i8 loads. Masking will be done when storing.
  268. if (VT == MVT::i1)
  269. VT = MVT::i8;
  270. // Get opcode and regclass of the output for the given load instruction.
  271. unsigned Opc = 0;
  272. switch (VT.SimpleTy) {
  273. default: return false;
  274. case MVT::i8:
  275. Opc = X86::MOV8rm;
  276. break;
  277. case MVT::i16:
  278. Opc = X86::MOV16rm;
  279. break;
  280. case MVT::i32:
  281. Opc = X86::MOV32rm;
  282. break;
  283. case MVT::i64:
  284. // Must be in x86-64 mode.
  285. Opc = X86::MOV64rm;
  286. break;
  287. case MVT::f32:
  288. Opc = HasAVX512 ? X86::VMOVSSZrm_alt
  289. : HasAVX ? X86::VMOVSSrm_alt
  290. : HasSSE1 ? X86::MOVSSrm_alt
  291. : X86::LD_Fp32m;
  292. break;
  293. case MVT::f64:
  294. Opc = HasAVX512 ? X86::VMOVSDZrm_alt
  295. : HasAVX ? X86::VMOVSDrm_alt
  296. : HasSSE2 ? X86::MOVSDrm_alt
  297. : X86::LD_Fp64m;
  298. break;
  299. case MVT::f80:
  300. // No f80 support yet.
  301. return false;
  302. case MVT::v4f32:
  303. if (IsNonTemporal && Alignment >= 16 && HasSSE41)
  304. Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
  305. HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
  306. else if (Alignment >= 16)
  307. Opc = HasVLX ? X86::VMOVAPSZ128rm :
  308. HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
  309. else
  310. Opc = HasVLX ? X86::VMOVUPSZ128rm :
  311. HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
  312. break;
  313. case MVT::v2f64:
  314. if (IsNonTemporal && Alignment >= 16 && HasSSE41)
  315. Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
  316. HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
  317. else if (Alignment >= 16)
  318. Opc = HasVLX ? X86::VMOVAPDZ128rm :
  319. HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
  320. else
  321. Opc = HasVLX ? X86::VMOVUPDZ128rm :
  322. HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
  323. break;
  324. case MVT::v4i32:
  325. case MVT::v2i64:
  326. case MVT::v8i16:
  327. case MVT::v16i8:
  328. if (IsNonTemporal && Alignment >= 16 && HasSSE41)
  329. Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
  330. HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
  331. else if (Alignment >= 16)
  332. Opc = HasVLX ? X86::VMOVDQA64Z128rm :
  333. HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
  334. else
  335. Opc = HasVLX ? X86::VMOVDQU64Z128rm :
  336. HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
  337. break;
  338. case MVT::v8f32:
  339. assert(HasAVX);
  340. if (IsNonTemporal && Alignment >= 32 && HasAVX2)
  341. Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
  342. else if (IsNonTemporal && Alignment >= 16)
  343. return false; // Force split for X86::VMOVNTDQArm
  344. else if (Alignment >= 32)
  345. Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
  346. else
  347. Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
  348. break;
  349. case MVT::v4f64:
  350. assert(HasAVX);
  351. if (IsNonTemporal && Alignment >= 32 && HasAVX2)
  352. Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
  353. else if (IsNonTemporal && Alignment >= 16)
  354. return false; // Force split for X86::VMOVNTDQArm
  355. else if (Alignment >= 32)
  356. Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
  357. else
  358. Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
  359. break;
  360. case MVT::v8i32:
  361. case MVT::v4i64:
  362. case MVT::v16i16:
  363. case MVT::v32i8:
  364. assert(HasAVX);
  365. if (IsNonTemporal && Alignment >= 32 && HasAVX2)
  366. Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
  367. else if (IsNonTemporal && Alignment >= 16)
  368. return false; // Force split for X86::VMOVNTDQArm
  369. else if (Alignment >= 32)
  370. Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
  371. else
  372. Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
  373. break;
  374. case MVT::v16f32:
  375. assert(HasAVX512);
  376. if (IsNonTemporal && Alignment >= 64)
  377. Opc = X86::VMOVNTDQAZrm;
  378. else
  379. Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
  380. break;
  381. case MVT::v8f64:
  382. assert(HasAVX512);
  383. if (IsNonTemporal && Alignment >= 64)
  384. Opc = X86::VMOVNTDQAZrm;
  385. else
  386. Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
  387. break;
  388. case MVT::v8i64:
  389. case MVT::v16i32:
  390. case MVT::v32i16:
  391. case MVT::v64i8:
  392. assert(HasAVX512);
  393. // Note: There are a lot more choices based on type with AVX-512, but
  394. // there's really no advantage when the load isn't masked.
  395. if (IsNonTemporal && Alignment >= 64)
  396. Opc = X86::VMOVNTDQAZrm;
  397. else
  398. Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
  399. break;
  400. }
  401. const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
  402. ResultReg = createResultReg(RC);
  403. MachineInstrBuilder MIB =
  404. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), ResultReg);
  405. addFullAddress(MIB, AM);
  406. if (MMO)
  407. MIB->addMemOperand(*FuncInfo.MF, MMO);
  408. return true;
  409. }
  410. /// X86FastEmitStore - Emit a machine instruction to store a value Val of
  411. /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
  412. /// and a displacement offset, or a GlobalAddress,
  413. /// i.e. V. Return true if it is possible.
  414. bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, X86AddressMode &AM,
  415. MachineMemOperand *MMO, bool Aligned) {
  416. bool HasSSE1 = Subtarget->hasSSE1();
  417. bool HasSSE2 = Subtarget->hasSSE2();
  418. bool HasSSE4A = Subtarget->hasSSE4A();
  419. bool HasAVX = Subtarget->hasAVX();
  420. bool HasAVX512 = Subtarget->hasAVX512();
  421. bool HasVLX = Subtarget->hasVLX();
  422. bool IsNonTemporal = MMO && MMO->isNonTemporal();
  423. // Get opcode and regclass of the output for the given store instruction.
  424. unsigned Opc = 0;
  425. switch (VT.getSimpleVT().SimpleTy) {
  426. case MVT::f80: // No f80 support yet.
  427. default: return false;
  428. case MVT::i1: {
  429. // Mask out all but lowest bit.
  430. Register AndResult = createResultReg(&X86::GR8RegClass);
  431. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  432. TII.get(X86::AND8ri), AndResult)
  433. .addReg(ValReg).addImm(1);
  434. ValReg = AndResult;
  435. [[fallthrough]]; // handle i1 as i8.
  436. }
  437. case MVT::i8: Opc = X86::MOV8mr; break;
  438. case MVT::i16: Opc = X86::MOV16mr; break;
  439. case MVT::i32:
  440. Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
  441. break;
  442. case MVT::i64:
  443. // Must be in x86-64 mode.
  444. Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
  445. break;
  446. case MVT::f32:
  447. if (HasSSE1) {
  448. if (IsNonTemporal && HasSSE4A)
  449. Opc = X86::MOVNTSS;
  450. else
  451. Opc = HasAVX512 ? X86::VMOVSSZmr :
  452. HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
  453. } else
  454. Opc = X86::ST_Fp32m;
  455. break;
  456. case MVT::f64:
  457. if (HasSSE2) {
  458. if (IsNonTemporal && HasSSE4A)
  459. Opc = X86::MOVNTSD;
  460. else
  461. Opc = HasAVX512 ? X86::VMOVSDZmr :
  462. HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
  463. } else
  464. Opc = X86::ST_Fp64m;
  465. break;
  466. case MVT::x86mmx:
  467. Opc = (IsNonTemporal && HasSSE1) ? X86::MMX_MOVNTQmr : X86::MMX_MOVQ64mr;
  468. break;
  469. case MVT::v4f32:
  470. if (Aligned) {
  471. if (IsNonTemporal)
  472. Opc = HasVLX ? X86::VMOVNTPSZ128mr :
  473. HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
  474. else
  475. Opc = HasVLX ? X86::VMOVAPSZ128mr :
  476. HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
  477. } else
  478. Opc = HasVLX ? X86::VMOVUPSZ128mr :
  479. HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
  480. break;
  481. case MVT::v2f64:
  482. if (Aligned) {
  483. if (IsNonTemporal)
  484. Opc = HasVLX ? X86::VMOVNTPDZ128mr :
  485. HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
  486. else
  487. Opc = HasVLX ? X86::VMOVAPDZ128mr :
  488. HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
  489. } else
  490. Opc = HasVLX ? X86::VMOVUPDZ128mr :
  491. HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
  492. break;
  493. case MVT::v4i32:
  494. case MVT::v2i64:
  495. case MVT::v8i16:
  496. case MVT::v16i8:
  497. if (Aligned) {
  498. if (IsNonTemporal)
  499. Opc = HasVLX ? X86::VMOVNTDQZ128mr :
  500. HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
  501. else
  502. Opc = HasVLX ? X86::VMOVDQA64Z128mr :
  503. HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
  504. } else
  505. Opc = HasVLX ? X86::VMOVDQU64Z128mr :
  506. HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
  507. break;
  508. case MVT::v8f32:
  509. assert(HasAVX);
  510. if (Aligned) {
  511. if (IsNonTemporal)
  512. Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
  513. else
  514. Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
  515. } else
  516. Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
  517. break;
  518. case MVT::v4f64:
  519. assert(HasAVX);
  520. if (Aligned) {
  521. if (IsNonTemporal)
  522. Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
  523. else
  524. Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
  525. } else
  526. Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
  527. break;
  528. case MVT::v8i32:
  529. case MVT::v4i64:
  530. case MVT::v16i16:
  531. case MVT::v32i8:
  532. assert(HasAVX);
  533. if (Aligned) {
  534. if (IsNonTemporal)
  535. Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
  536. else
  537. Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
  538. } else
  539. Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
  540. break;
  541. case MVT::v16f32:
  542. assert(HasAVX512);
  543. if (Aligned)
  544. Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
  545. else
  546. Opc = X86::VMOVUPSZmr;
  547. break;
  548. case MVT::v8f64:
  549. assert(HasAVX512);
  550. if (Aligned) {
  551. Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
  552. } else
  553. Opc = X86::VMOVUPDZmr;
  554. break;
  555. case MVT::v8i64:
  556. case MVT::v16i32:
  557. case MVT::v32i16:
  558. case MVT::v64i8:
  559. assert(HasAVX512);
  560. // Note: There are a lot more choices based on type with AVX-512, but
  561. // there's really no advantage when the store isn't masked.
  562. if (Aligned)
  563. Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
  564. else
  565. Opc = X86::VMOVDQU64Zmr;
  566. break;
  567. }
  568. const MCInstrDesc &Desc = TII.get(Opc);
  569. // Some of the instructions in the previous switch use FR128 instead
  570. // of FR32 for ValReg. Make sure the register we feed the instruction
  571. // matches its register class constraints.
  572. // Note: This is fine to do a copy from FR32 to FR128, this is the
  573. // same registers behind the scene and actually why it did not trigger
  574. // any bugs before.
  575. ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
  576. MachineInstrBuilder MIB =
  577. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, Desc);
  578. addFullAddress(MIB, AM).addReg(ValReg);
  579. if (MMO)
  580. MIB->addMemOperand(*FuncInfo.MF, MMO);
  581. return true;
  582. }
  583. bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
  584. X86AddressMode &AM,
  585. MachineMemOperand *MMO, bool Aligned) {
  586. // Handle 'null' like i32/i64 0.
  587. if (isa<ConstantPointerNull>(Val))
  588. Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
  589. // If this is a store of a simple constant, fold the constant into the store.
  590. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
  591. unsigned Opc = 0;
  592. bool Signed = true;
  593. switch (VT.getSimpleVT().SimpleTy) {
  594. default: break;
  595. case MVT::i1:
  596. Signed = false;
  597. [[fallthrough]]; // Handle as i8.
  598. case MVT::i8: Opc = X86::MOV8mi; break;
  599. case MVT::i16: Opc = X86::MOV16mi; break;
  600. case MVT::i32: Opc = X86::MOV32mi; break;
  601. case MVT::i64:
  602. // Must be a 32-bit sign extended value.
  603. if (isInt<32>(CI->getSExtValue()))
  604. Opc = X86::MOV64mi32;
  605. break;
  606. }
  607. if (Opc) {
  608. MachineInstrBuilder MIB =
  609. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc));
  610. addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
  611. : CI->getZExtValue());
  612. if (MMO)
  613. MIB->addMemOperand(*FuncInfo.MF, MMO);
  614. return true;
  615. }
  616. }
  617. Register ValReg = getRegForValue(Val);
  618. if (ValReg == 0)
  619. return false;
  620. return X86FastEmitStore(VT, ValReg, AM, MMO, Aligned);
  621. }
  622. /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
  623. /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
  624. /// ISD::SIGN_EXTEND).
  625. bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
  626. unsigned Src, EVT SrcVT,
  627. unsigned &ResultReg) {
  628. unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
  629. if (RR == 0)
  630. return false;
  631. ResultReg = RR;
  632. return true;
  633. }
  634. bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
  635. // Handle constant address.
  636. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  637. // Can't handle alternate code models yet.
  638. if (TM.getCodeModel() != CodeModel::Small)
  639. return false;
  640. // Can't handle TLS yet.
  641. if (GV->isThreadLocal())
  642. return false;
  643. // Can't handle !absolute_symbol references yet.
  644. if (GV->isAbsoluteSymbolRef())
  645. return false;
  646. // RIP-relative addresses can't have additional register operands, so if
  647. // we've already folded stuff into the addressing mode, just force the
  648. // global value into its own register, which we can use as the basereg.
  649. if (!Subtarget->isPICStyleRIPRel() ||
  650. (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
  651. // Okay, we've committed to selecting this global. Set up the address.
  652. AM.GV = GV;
  653. // Allow the subtarget to classify the global.
  654. unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
  655. // If this reference is relative to the pic base, set it now.
  656. if (isGlobalRelativeToPICBase(GVFlags)) {
  657. // FIXME: How do we know Base.Reg is free??
  658. AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
  659. }
  660. // Unless the ABI requires an extra load, return a direct reference to
  661. // the global.
  662. if (!isGlobalStubReference(GVFlags)) {
  663. if (Subtarget->isPICStyleRIPRel()) {
  664. // Use rip-relative addressing if we can. Above we verified that the
  665. // base and index registers are unused.
  666. assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
  667. AM.Base.Reg = X86::RIP;
  668. }
  669. AM.GVOpFlags = GVFlags;
  670. return true;
  671. }
  672. // Ok, we need to do a load from a stub. If we've already loaded from
  673. // this stub, reuse the loaded pointer, otherwise emit the load now.
  674. DenseMap<const Value *, Register>::iterator I = LocalValueMap.find(V);
  675. Register LoadReg;
  676. if (I != LocalValueMap.end() && I->second) {
  677. LoadReg = I->second;
  678. } else {
  679. // Issue load from stub.
  680. unsigned Opc = 0;
  681. const TargetRegisterClass *RC = nullptr;
  682. X86AddressMode StubAM;
  683. StubAM.Base.Reg = AM.Base.Reg;
  684. StubAM.GV = GV;
  685. StubAM.GVOpFlags = GVFlags;
  686. // Prepare for inserting code in the local-value area.
  687. SavePoint SaveInsertPt = enterLocalValueArea();
  688. if (TLI.getPointerTy(DL) == MVT::i64) {
  689. Opc = X86::MOV64rm;
  690. RC = &X86::GR64RegClass;
  691. } else {
  692. Opc = X86::MOV32rm;
  693. RC = &X86::GR32RegClass;
  694. }
  695. if (Subtarget->isPICStyleRIPRel() || GVFlags == X86II::MO_GOTPCREL ||
  696. GVFlags == X86II::MO_GOTPCREL_NORELAX)
  697. StubAM.Base.Reg = X86::RIP;
  698. LoadReg = createResultReg(RC);
  699. MachineInstrBuilder LoadMI =
  700. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), LoadReg);
  701. addFullAddress(LoadMI, StubAM);
  702. // Ok, back to normal mode.
  703. leaveLocalValueArea(SaveInsertPt);
  704. // Prevent loading GV stub multiple times in same MBB.
  705. LocalValueMap[V] = LoadReg;
  706. }
  707. // Now construct the final address. Note that the Disp, Scale,
  708. // and Index values may already be set here.
  709. AM.Base.Reg = LoadReg;
  710. AM.GV = nullptr;
  711. return true;
  712. }
  713. }
  714. // If all else fails, try to materialize the value in a register.
  715. if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
  716. if (AM.Base.Reg == 0) {
  717. AM.Base.Reg = getRegForValue(V);
  718. return AM.Base.Reg != 0;
  719. }
  720. if (AM.IndexReg == 0) {
  721. assert(AM.Scale == 1 && "Scale with no index!");
  722. AM.IndexReg = getRegForValue(V);
  723. return AM.IndexReg != 0;
  724. }
  725. }
  726. return false;
  727. }
  728. /// X86SelectAddress - Attempt to fill in an address from the given value.
  729. ///
  730. bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
  731. SmallVector<const Value *, 32> GEPs;
  732. redo_gep:
  733. const User *U = nullptr;
  734. unsigned Opcode = Instruction::UserOp1;
  735. if (const Instruction *I = dyn_cast<Instruction>(V)) {
  736. // Don't walk into other basic blocks; it's possible we haven't
  737. // visited them yet, so the instructions may not yet be assigned
  738. // virtual registers.
  739. if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
  740. FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
  741. Opcode = I->getOpcode();
  742. U = I;
  743. }
  744. } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
  745. Opcode = C->getOpcode();
  746. U = C;
  747. }
  748. if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
  749. if (Ty->getAddressSpace() > 255)
  750. // Fast instruction selection doesn't support the special
  751. // address spaces.
  752. return false;
  753. switch (Opcode) {
  754. default: break;
  755. case Instruction::BitCast:
  756. // Look past bitcasts.
  757. return X86SelectAddress(U->getOperand(0), AM);
  758. case Instruction::IntToPtr:
  759. // Look past no-op inttoptrs.
  760. if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
  761. TLI.getPointerTy(DL))
  762. return X86SelectAddress(U->getOperand(0), AM);
  763. break;
  764. case Instruction::PtrToInt:
  765. // Look past no-op ptrtoints.
  766. if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
  767. return X86SelectAddress(U->getOperand(0), AM);
  768. break;
  769. case Instruction::Alloca: {
  770. // Do static allocas.
  771. const AllocaInst *A = cast<AllocaInst>(V);
  772. DenseMap<const AllocaInst *, int>::iterator SI =
  773. FuncInfo.StaticAllocaMap.find(A);
  774. if (SI != FuncInfo.StaticAllocaMap.end()) {
  775. AM.BaseType = X86AddressMode::FrameIndexBase;
  776. AM.Base.FrameIndex = SI->second;
  777. return true;
  778. }
  779. break;
  780. }
  781. case Instruction::Add: {
  782. // Adds of constants are common and easy enough.
  783. if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
  784. uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
  785. // They have to fit in the 32-bit signed displacement field though.
  786. if (isInt<32>(Disp)) {
  787. AM.Disp = (uint32_t)Disp;
  788. return X86SelectAddress(U->getOperand(0), AM);
  789. }
  790. }
  791. break;
  792. }
  793. case Instruction::GetElementPtr: {
  794. X86AddressMode SavedAM = AM;
  795. // Pattern-match simple GEPs.
  796. uint64_t Disp = (int32_t)AM.Disp;
  797. unsigned IndexReg = AM.IndexReg;
  798. unsigned Scale = AM.Scale;
  799. gep_type_iterator GTI = gep_type_begin(U);
  800. // Iterate through the indices, folding what we can. Constants can be
  801. // folded, and one dynamic index can be handled, if the scale is supported.
  802. for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
  803. i != e; ++i, ++GTI) {
  804. const Value *Op = *i;
  805. if (StructType *STy = GTI.getStructTypeOrNull()) {
  806. const StructLayout *SL = DL.getStructLayout(STy);
  807. Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
  808. continue;
  809. }
  810. // A array/variable index is always of the form i*S where S is the
  811. // constant scale size. See if we can push the scale into immediates.
  812. uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
  813. for (;;) {
  814. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
  815. // Constant-offset addressing.
  816. Disp += CI->getSExtValue() * S;
  817. break;
  818. }
  819. if (canFoldAddIntoGEP(U, Op)) {
  820. // A compatible add with a constant operand. Fold the constant.
  821. ConstantInt *CI =
  822. cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
  823. Disp += CI->getSExtValue() * S;
  824. // Iterate on the other operand.
  825. Op = cast<AddOperator>(Op)->getOperand(0);
  826. continue;
  827. }
  828. if (IndexReg == 0 &&
  829. (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
  830. (S == 1 || S == 2 || S == 4 || S == 8)) {
  831. // Scaled-index addressing.
  832. Scale = S;
  833. IndexReg = getRegForGEPIndex(Op);
  834. if (IndexReg == 0)
  835. return false;
  836. break;
  837. }
  838. // Unsupported.
  839. goto unsupported_gep;
  840. }
  841. }
  842. // Check for displacement overflow.
  843. if (!isInt<32>(Disp))
  844. break;
  845. AM.IndexReg = IndexReg;
  846. AM.Scale = Scale;
  847. AM.Disp = (uint32_t)Disp;
  848. GEPs.push_back(V);
  849. if (const GetElementPtrInst *GEP =
  850. dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
  851. // Ok, the GEP indices were covered by constant-offset and scaled-index
  852. // addressing. Update the address state and move on to examining the base.
  853. V = GEP;
  854. goto redo_gep;
  855. } else if (X86SelectAddress(U->getOperand(0), AM)) {
  856. return true;
  857. }
  858. // If we couldn't merge the gep value into this addr mode, revert back to
  859. // our address and just match the value instead of completely failing.
  860. AM = SavedAM;
  861. for (const Value *I : reverse(GEPs))
  862. if (handleConstantAddresses(I, AM))
  863. return true;
  864. return false;
  865. unsupported_gep:
  866. // Ok, the GEP indices weren't all covered.
  867. break;
  868. }
  869. }
  870. return handleConstantAddresses(V, AM);
  871. }
  872. /// X86SelectCallAddress - Attempt to fill in an address from the given value.
  873. ///
  874. bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
  875. const User *U = nullptr;
  876. unsigned Opcode = Instruction::UserOp1;
  877. const Instruction *I = dyn_cast<Instruction>(V);
  878. // Record if the value is defined in the same basic block.
  879. //
  880. // This information is crucial to know whether or not folding an
  881. // operand is valid.
  882. // Indeed, FastISel generates or reuses a virtual register for all
  883. // operands of all instructions it selects. Obviously, the definition and
  884. // its uses must use the same virtual register otherwise the produced
  885. // code is incorrect.
  886. // Before instruction selection, FunctionLoweringInfo::set sets the virtual
  887. // registers for values that are alive across basic blocks. This ensures
  888. // that the values are consistently set between across basic block, even
  889. // if different instruction selection mechanisms are used (e.g., a mix of
  890. // SDISel and FastISel).
  891. // For values local to a basic block, the instruction selection process
  892. // generates these virtual registers with whatever method is appropriate
  893. // for its needs. In particular, FastISel and SDISel do not share the way
  894. // local virtual registers are set.
  895. // Therefore, this is impossible (or at least unsafe) to share values
  896. // between basic blocks unless they use the same instruction selection
  897. // method, which is not guarantee for X86.
  898. // Moreover, things like hasOneUse could not be used accurately, if we
  899. // allow to reference values across basic blocks whereas they are not
  900. // alive across basic blocks initially.
  901. bool InMBB = true;
  902. if (I) {
  903. Opcode = I->getOpcode();
  904. U = I;
  905. InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
  906. } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
  907. Opcode = C->getOpcode();
  908. U = C;
  909. }
  910. switch (Opcode) {
  911. default: break;
  912. case Instruction::BitCast:
  913. // Look past bitcasts if its operand is in the same BB.
  914. if (InMBB)
  915. return X86SelectCallAddress(U->getOperand(0), AM);
  916. break;
  917. case Instruction::IntToPtr:
  918. // Look past no-op inttoptrs if its operand is in the same BB.
  919. if (InMBB &&
  920. TLI.getValueType(DL, U->getOperand(0)->getType()) ==
  921. TLI.getPointerTy(DL))
  922. return X86SelectCallAddress(U->getOperand(0), AM);
  923. break;
  924. case Instruction::PtrToInt:
  925. // Look past no-op ptrtoints if its operand is in the same BB.
  926. if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
  927. return X86SelectCallAddress(U->getOperand(0), AM);
  928. break;
  929. }
  930. // Handle constant address.
  931. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  932. // Can't handle alternate code models yet.
  933. if (TM.getCodeModel() != CodeModel::Small)
  934. return false;
  935. // RIP-relative addresses can't have additional register operands.
  936. if (Subtarget->isPICStyleRIPRel() &&
  937. (AM.Base.Reg != 0 || AM.IndexReg != 0))
  938. return false;
  939. // Can't handle TLS.
  940. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
  941. if (GVar->isThreadLocal())
  942. return false;
  943. // Okay, we've committed to selecting this global. Set up the basic address.
  944. AM.GV = GV;
  945. // Return a direct reference to the global. Fastisel can handle calls to
  946. // functions that require loads, such as dllimport and nonlazybind
  947. // functions.
  948. if (Subtarget->isPICStyleRIPRel()) {
  949. // Use rip-relative addressing if we can. Above we verified that the
  950. // base and index registers are unused.
  951. assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
  952. AM.Base.Reg = X86::RIP;
  953. } else {
  954. AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
  955. }
  956. return true;
  957. }
  958. // If all else fails, try to materialize the value in a register.
  959. if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
  960. auto GetCallRegForValue = [this](const Value *V) {
  961. Register Reg = getRegForValue(V);
  962. // In 64-bit mode, we need a 64-bit register even if pointers are 32 bits.
  963. if (Reg && Subtarget->isTarget64BitILP32()) {
  964. Register CopyReg = createResultReg(&X86::GR32RegClass);
  965. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV32rr),
  966. CopyReg)
  967. .addReg(Reg);
  968. Register ExtReg = createResultReg(&X86::GR64RegClass);
  969. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  970. TII.get(TargetOpcode::SUBREG_TO_REG), ExtReg)
  971. .addImm(0)
  972. .addReg(CopyReg)
  973. .addImm(X86::sub_32bit);
  974. Reg = ExtReg;
  975. }
  976. return Reg;
  977. };
  978. if (AM.Base.Reg == 0) {
  979. AM.Base.Reg = GetCallRegForValue(V);
  980. return AM.Base.Reg != 0;
  981. }
  982. if (AM.IndexReg == 0) {
  983. assert(AM.Scale == 1 && "Scale with no index!");
  984. AM.IndexReg = GetCallRegForValue(V);
  985. return AM.IndexReg != 0;
  986. }
  987. }
  988. return false;
  989. }
  990. /// X86SelectStore - Select and emit code to implement store instructions.
  991. bool X86FastISel::X86SelectStore(const Instruction *I) {
  992. // Atomic stores need special handling.
  993. const StoreInst *S = cast<StoreInst>(I);
  994. if (S->isAtomic())
  995. return false;
  996. const Value *PtrV = I->getOperand(1);
  997. if (TLI.supportSwiftError()) {
  998. // Swifterror values can come from either a function parameter with
  999. // swifterror attribute or an alloca with swifterror attribute.
  1000. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  1001. if (Arg->hasSwiftErrorAttr())
  1002. return false;
  1003. }
  1004. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  1005. if (Alloca->isSwiftError())
  1006. return false;
  1007. }
  1008. }
  1009. const Value *Val = S->getValueOperand();
  1010. const Value *Ptr = S->getPointerOperand();
  1011. MVT VT;
  1012. if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
  1013. return false;
  1014. Align Alignment = S->getAlign();
  1015. Align ABIAlignment = DL.getABITypeAlign(Val->getType());
  1016. bool Aligned = Alignment >= ABIAlignment;
  1017. X86AddressMode AM;
  1018. if (!X86SelectAddress(Ptr, AM))
  1019. return false;
  1020. return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
  1021. }
  1022. /// X86SelectRet - Select and emit code to implement ret instructions.
  1023. bool X86FastISel::X86SelectRet(const Instruction *I) {
  1024. const ReturnInst *Ret = cast<ReturnInst>(I);
  1025. const Function &F = *I->getParent()->getParent();
  1026. const X86MachineFunctionInfo *X86MFInfo =
  1027. FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
  1028. if (!FuncInfo.CanLowerReturn)
  1029. return false;
  1030. if (TLI.supportSwiftError() &&
  1031. F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  1032. return false;
  1033. if (TLI.supportSplitCSR(FuncInfo.MF))
  1034. return false;
  1035. CallingConv::ID CC = F.getCallingConv();
  1036. if (CC != CallingConv::C &&
  1037. CC != CallingConv::Fast &&
  1038. CC != CallingConv::Tail &&
  1039. CC != CallingConv::SwiftTail &&
  1040. CC != CallingConv::X86_FastCall &&
  1041. CC != CallingConv::X86_StdCall &&
  1042. CC != CallingConv::X86_ThisCall &&
  1043. CC != CallingConv::X86_64_SysV &&
  1044. CC != CallingConv::Win64)
  1045. return false;
  1046. // Don't handle popping bytes if they don't fit the ret's immediate.
  1047. if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
  1048. return false;
  1049. // fastcc with -tailcallopt is intended to provide a guaranteed
  1050. // tail call optimization. Fastisel doesn't know how to do that.
  1051. if ((CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) ||
  1052. CC == CallingConv::Tail || CC == CallingConv::SwiftTail)
  1053. return false;
  1054. // Let SDISel handle vararg functions.
  1055. if (F.isVarArg())
  1056. return false;
  1057. // Build a list of return value registers.
  1058. SmallVector<unsigned, 4> RetRegs;
  1059. if (Ret->getNumOperands() > 0) {
  1060. SmallVector<ISD::OutputArg, 4> Outs;
  1061. GetReturnInfo(CC, F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
  1062. // Analyze operands of the call, assigning locations to each operand.
  1063. SmallVector<CCValAssign, 16> ValLocs;
  1064. CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
  1065. CCInfo.AnalyzeReturn(Outs, RetCC_X86);
  1066. const Value *RV = Ret->getOperand(0);
  1067. Register Reg = getRegForValue(RV);
  1068. if (Reg == 0)
  1069. return false;
  1070. // Only handle a single return value for now.
  1071. if (ValLocs.size() != 1)
  1072. return false;
  1073. CCValAssign &VA = ValLocs[0];
  1074. // Don't bother handling odd stuff for now.
  1075. if (VA.getLocInfo() != CCValAssign::Full)
  1076. return false;
  1077. // Only handle register returns for now.
  1078. if (!VA.isRegLoc())
  1079. return false;
  1080. // The calling-convention tables for x87 returns don't tell
  1081. // the whole story.
  1082. if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
  1083. return false;
  1084. unsigned SrcReg = Reg + VA.getValNo();
  1085. EVT SrcVT = TLI.getValueType(DL, RV->getType());
  1086. EVT DstVT = VA.getValVT();
  1087. // Special handling for extended integers.
  1088. if (SrcVT != DstVT) {
  1089. if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
  1090. return false;
  1091. if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
  1092. return false;
  1093. assert(DstVT == MVT::i32 && "X86 should always ext to i32");
  1094. if (SrcVT == MVT::i1) {
  1095. if (Outs[0].Flags.isSExt())
  1096. return false;
  1097. // TODO
  1098. SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg);
  1099. SrcVT = MVT::i8;
  1100. }
  1101. unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
  1102. ISD::SIGN_EXTEND;
  1103. // TODO
  1104. SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op, SrcReg);
  1105. }
  1106. // Make the copy.
  1107. Register DstReg = VA.getLocReg();
  1108. const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
  1109. // Avoid a cross-class copy. This is very unlikely.
  1110. if (!SrcRC->contains(DstReg))
  1111. return false;
  1112. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1113. TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
  1114. // Add register to return instruction.
  1115. RetRegs.push_back(VA.getLocReg());
  1116. }
  1117. // Swift calling convention does not require we copy the sret argument
  1118. // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
  1119. // All x86 ABIs require that for returning structs by value we copy
  1120. // the sret argument into %rax/%eax (depending on ABI) for the return.
  1121. // We saved the argument into a virtual register in the entry block,
  1122. // so now we copy the value out and into %rax/%eax.
  1123. if (F.hasStructRetAttr() && CC != CallingConv::Swift &&
  1124. CC != CallingConv::SwiftTail) {
  1125. Register Reg = X86MFInfo->getSRetReturnReg();
  1126. assert(Reg &&
  1127. "SRetReturnReg should have been set in LowerFormalArguments()!");
  1128. unsigned RetReg = Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
  1129. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1130. TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
  1131. RetRegs.push_back(RetReg);
  1132. }
  1133. // Now emit the RET.
  1134. MachineInstrBuilder MIB;
  1135. if (X86MFInfo->getBytesToPopOnReturn()) {
  1136. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1137. TII.get(Subtarget->is64Bit() ? X86::RETI64 : X86::RETI32))
  1138. .addImm(X86MFInfo->getBytesToPopOnReturn());
  1139. } else {
  1140. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1141. TII.get(Subtarget->is64Bit() ? X86::RET64 : X86::RET32));
  1142. }
  1143. for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
  1144. MIB.addReg(RetRegs[i], RegState::Implicit);
  1145. return true;
  1146. }
  1147. /// X86SelectLoad - Select and emit code to implement load instructions.
  1148. ///
  1149. bool X86FastISel::X86SelectLoad(const Instruction *I) {
  1150. const LoadInst *LI = cast<LoadInst>(I);
  1151. // Atomic loads need special handling.
  1152. if (LI->isAtomic())
  1153. return false;
  1154. const Value *SV = I->getOperand(0);
  1155. if (TLI.supportSwiftError()) {
  1156. // Swifterror values can come from either a function parameter with
  1157. // swifterror attribute or an alloca with swifterror attribute.
  1158. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  1159. if (Arg->hasSwiftErrorAttr())
  1160. return false;
  1161. }
  1162. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  1163. if (Alloca->isSwiftError())
  1164. return false;
  1165. }
  1166. }
  1167. MVT VT;
  1168. if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
  1169. return false;
  1170. const Value *Ptr = LI->getPointerOperand();
  1171. X86AddressMode AM;
  1172. if (!X86SelectAddress(Ptr, AM))
  1173. return false;
  1174. unsigned ResultReg = 0;
  1175. if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
  1176. LI->getAlign().value()))
  1177. return false;
  1178. updateValueMap(I, ResultReg);
  1179. return true;
  1180. }
  1181. static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
  1182. bool HasAVX512 = Subtarget->hasAVX512();
  1183. bool HasAVX = Subtarget->hasAVX();
  1184. bool HasSSE1 = Subtarget->hasSSE1();
  1185. bool HasSSE2 = Subtarget->hasSSE2();
  1186. switch (VT.getSimpleVT().SimpleTy) {
  1187. default: return 0;
  1188. case MVT::i8: return X86::CMP8rr;
  1189. case MVT::i16: return X86::CMP16rr;
  1190. case MVT::i32: return X86::CMP32rr;
  1191. case MVT::i64: return X86::CMP64rr;
  1192. case MVT::f32:
  1193. return HasAVX512 ? X86::VUCOMISSZrr
  1194. : HasAVX ? X86::VUCOMISSrr
  1195. : HasSSE1 ? X86::UCOMISSrr
  1196. : 0;
  1197. case MVT::f64:
  1198. return HasAVX512 ? X86::VUCOMISDZrr
  1199. : HasAVX ? X86::VUCOMISDrr
  1200. : HasSSE2 ? X86::UCOMISDrr
  1201. : 0;
  1202. }
  1203. }
  1204. /// If we have a comparison with RHS as the RHS of the comparison, return an
  1205. /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
  1206. static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
  1207. int64_t Val = RHSC->getSExtValue();
  1208. switch (VT.getSimpleVT().SimpleTy) {
  1209. // Otherwise, we can't fold the immediate into this comparison.
  1210. default:
  1211. return 0;
  1212. case MVT::i8:
  1213. return X86::CMP8ri;
  1214. case MVT::i16:
  1215. if (isInt<8>(Val))
  1216. return X86::CMP16ri8;
  1217. return X86::CMP16ri;
  1218. case MVT::i32:
  1219. if (isInt<8>(Val))
  1220. return X86::CMP32ri8;
  1221. return X86::CMP32ri;
  1222. case MVT::i64:
  1223. if (isInt<8>(Val))
  1224. return X86::CMP64ri8;
  1225. // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
  1226. // field.
  1227. if (isInt<32>(Val))
  1228. return X86::CMP64ri32;
  1229. return 0;
  1230. }
  1231. }
  1232. bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
  1233. const DebugLoc &CurMIMD) {
  1234. Register Op0Reg = getRegForValue(Op0);
  1235. if (Op0Reg == 0) return false;
  1236. // Handle 'null' like i32/i64 0.
  1237. if (isa<ConstantPointerNull>(Op1))
  1238. Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
  1239. // We have two options: compare with register or immediate. If the RHS of
  1240. // the compare is an immediate that we can fold into this compare, use
  1241. // CMPri, otherwise use CMPrr.
  1242. if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
  1243. if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
  1244. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurMIMD, TII.get(CompareImmOpc))
  1245. .addReg(Op0Reg)
  1246. .addImm(Op1C->getSExtValue());
  1247. return true;
  1248. }
  1249. }
  1250. unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
  1251. if (CompareOpc == 0) return false;
  1252. Register Op1Reg = getRegForValue(Op1);
  1253. if (Op1Reg == 0) return false;
  1254. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurMIMD, TII.get(CompareOpc))
  1255. .addReg(Op0Reg)
  1256. .addReg(Op1Reg);
  1257. return true;
  1258. }
  1259. bool X86FastISel::X86SelectCmp(const Instruction *I) {
  1260. const CmpInst *CI = cast<CmpInst>(I);
  1261. MVT VT;
  1262. if (!isTypeLegal(I->getOperand(0)->getType(), VT))
  1263. return false;
  1264. // Below code only works for scalars.
  1265. if (VT.isVector())
  1266. return false;
  1267. // Try to optimize or fold the cmp.
  1268. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  1269. unsigned ResultReg = 0;
  1270. switch (Predicate) {
  1271. default: break;
  1272. case CmpInst::FCMP_FALSE: {
  1273. ResultReg = createResultReg(&X86::GR32RegClass);
  1274. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV32r0),
  1275. ResultReg);
  1276. ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, X86::sub_8bit);
  1277. if (!ResultReg)
  1278. return false;
  1279. break;
  1280. }
  1281. case CmpInst::FCMP_TRUE: {
  1282. ResultReg = createResultReg(&X86::GR8RegClass);
  1283. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV8ri),
  1284. ResultReg).addImm(1);
  1285. break;
  1286. }
  1287. }
  1288. if (ResultReg) {
  1289. updateValueMap(I, ResultReg);
  1290. return true;
  1291. }
  1292. const Value *LHS = CI->getOperand(0);
  1293. const Value *RHS = CI->getOperand(1);
  1294. // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
  1295. // We don't have to materialize a zero constant for this case and can just use
  1296. // %x again on the RHS.
  1297. if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
  1298. const auto *RHSC = dyn_cast<ConstantFP>(RHS);
  1299. if (RHSC && RHSC->isNullValue())
  1300. RHS = LHS;
  1301. }
  1302. // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
  1303. static const uint16_t SETFOpcTable[2][3] = {
  1304. { X86::COND_E, X86::COND_NP, X86::AND8rr },
  1305. { X86::COND_NE, X86::COND_P, X86::OR8rr }
  1306. };
  1307. const uint16_t *SETFOpc = nullptr;
  1308. switch (Predicate) {
  1309. default: break;
  1310. case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
  1311. case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
  1312. }
  1313. ResultReg = createResultReg(&X86::GR8RegClass);
  1314. if (SETFOpc) {
  1315. if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
  1316. return false;
  1317. Register FlagReg1 = createResultReg(&X86::GR8RegClass);
  1318. Register FlagReg2 = createResultReg(&X86::GR8RegClass);
  1319. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::SETCCr),
  1320. FlagReg1).addImm(SETFOpc[0]);
  1321. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::SETCCr),
  1322. FlagReg2).addImm(SETFOpc[1]);
  1323. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(SETFOpc[2]),
  1324. ResultReg).addReg(FlagReg1).addReg(FlagReg2);
  1325. updateValueMap(I, ResultReg);
  1326. return true;
  1327. }
  1328. X86::CondCode CC;
  1329. bool SwapArgs;
  1330. std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
  1331. assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
  1332. if (SwapArgs)
  1333. std::swap(LHS, RHS);
  1334. // Emit a compare of LHS/RHS.
  1335. if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
  1336. return false;
  1337. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::SETCCr),
  1338. ResultReg).addImm(CC);
  1339. updateValueMap(I, ResultReg);
  1340. return true;
  1341. }
  1342. bool X86FastISel::X86SelectZExt(const Instruction *I) {
  1343. EVT DstVT = TLI.getValueType(DL, I->getType());
  1344. if (!TLI.isTypeLegal(DstVT))
  1345. return false;
  1346. Register ResultReg = getRegForValue(I->getOperand(0));
  1347. if (ResultReg == 0)
  1348. return false;
  1349. // Handle zero-extension from i1 to i8, which is common.
  1350. MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
  1351. if (SrcVT == MVT::i1) {
  1352. // Set the high bits to zero.
  1353. ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg);
  1354. SrcVT = MVT::i8;
  1355. if (ResultReg == 0)
  1356. return false;
  1357. }
  1358. if (DstVT == MVT::i64) {
  1359. // Handle extension to 64-bits via sub-register shenanigans.
  1360. unsigned MovInst;
  1361. switch (SrcVT.SimpleTy) {
  1362. case MVT::i8: MovInst = X86::MOVZX32rr8; break;
  1363. case MVT::i16: MovInst = X86::MOVZX32rr16; break;
  1364. case MVT::i32: MovInst = X86::MOV32rr; break;
  1365. default: llvm_unreachable("Unexpected zext to i64 source type");
  1366. }
  1367. Register Result32 = createResultReg(&X86::GR32RegClass);
  1368. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(MovInst), Result32)
  1369. .addReg(ResultReg);
  1370. ResultReg = createResultReg(&X86::GR64RegClass);
  1371. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::SUBREG_TO_REG),
  1372. ResultReg)
  1373. .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
  1374. } else if (DstVT == MVT::i16) {
  1375. // i8->i16 doesn't exist in the autogenerated isel table. Need to zero
  1376. // extend to 32-bits and then extract down to 16-bits.
  1377. Register Result32 = createResultReg(&X86::GR32RegClass);
  1378. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOVZX32rr8),
  1379. Result32).addReg(ResultReg);
  1380. ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, X86::sub_16bit);
  1381. } else if (DstVT != MVT::i8) {
  1382. ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
  1383. ResultReg);
  1384. if (ResultReg == 0)
  1385. return false;
  1386. }
  1387. updateValueMap(I, ResultReg);
  1388. return true;
  1389. }
  1390. bool X86FastISel::X86SelectSExt(const Instruction *I) {
  1391. EVT DstVT = TLI.getValueType(DL, I->getType());
  1392. if (!TLI.isTypeLegal(DstVT))
  1393. return false;
  1394. Register ResultReg = getRegForValue(I->getOperand(0));
  1395. if (ResultReg == 0)
  1396. return false;
  1397. // Handle sign-extension from i1 to i8.
  1398. MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
  1399. if (SrcVT == MVT::i1) {
  1400. // Set the high bits to zero.
  1401. Register ZExtReg = fastEmitZExtFromI1(MVT::i8, ResultReg);
  1402. if (ZExtReg == 0)
  1403. return false;
  1404. // Negate the result to make an 8-bit sign extended value.
  1405. ResultReg = createResultReg(&X86::GR8RegClass);
  1406. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::NEG8r),
  1407. ResultReg).addReg(ZExtReg);
  1408. SrcVT = MVT::i8;
  1409. }
  1410. if (DstVT == MVT::i16) {
  1411. // i8->i16 doesn't exist in the autogenerated isel table. Need to sign
  1412. // extend to 32-bits and then extract down to 16-bits.
  1413. Register Result32 = createResultReg(&X86::GR32RegClass);
  1414. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOVSX32rr8),
  1415. Result32).addReg(ResultReg);
  1416. ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, X86::sub_16bit);
  1417. } else if (DstVT != MVT::i8) {
  1418. ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::SIGN_EXTEND,
  1419. ResultReg);
  1420. if (ResultReg == 0)
  1421. return false;
  1422. }
  1423. updateValueMap(I, ResultReg);
  1424. return true;
  1425. }
  1426. bool X86FastISel::X86SelectBranch(const Instruction *I) {
  1427. // Unconditional branches are selected by tablegen-generated code.
  1428. // Handle a conditional branch.
  1429. const BranchInst *BI = cast<BranchInst>(I);
  1430. MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
  1431. MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
  1432. // Fold the common case of a conditional branch with a comparison
  1433. // in the same block (values defined on other blocks may not have
  1434. // initialized registers).
  1435. X86::CondCode CC;
  1436. if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
  1437. if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
  1438. EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
  1439. // Try to optimize or fold the cmp.
  1440. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  1441. switch (Predicate) {
  1442. default: break;
  1443. case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, MIMD.getDL()); return true;
  1444. case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, MIMD.getDL()); return true;
  1445. }
  1446. const Value *CmpLHS = CI->getOperand(0);
  1447. const Value *CmpRHS = CI->getOperand(1);
  1448. // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
  1449. // 0.0.
  1450. // We don't have to materialize a zero constant for this case and can just
  1451. // use %x again on the RHS.
  1452. if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
  1453. const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
  1454. if (CmpRHSC && CmpRHSC->isNullValue())
  1455. CmpRHS = CmpLHS;
  1456. }
  1457. // Try to take advantage of fallthrough opportunities.
  1458. if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
  1459. std::swap(TrueMBB, FalseMBB);
  1460. Predicate = CmpInst::getInversePredicate(Predicate);
  1461. }
  1462. // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
  1463. // code check. Instead two branch instructions are required to check all
  1464. // the flags. First we change the predicate to a supported condition code,
  1465. // which will be the first branch. Later one we will emit the second
  1466. // branch.
  1467. bool NeedExtraBranch = false;
  1468. switch (Predicate) {
  1469. default: break;
  1470. case CmpInst::FCMP_OEQ:
  1471. std::swap(TrueMBB, FalseMBB);
  1472. [[fallthrough]];
  1473. case CmpInst::FCMP_UNE:
  1474. NeedExtraBranch = true;
  1475. Predicate = CmpInst::FCMP_ONE;
  1476. break;
  1477. }
  1478. bool SwapArgs;
  1479. std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
  1480. assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
  1481. if (SwapArgs)
  1482. std::swap(CmpLHS, CmpRHS);
  1483. // Emit a compare of the LHS and RHS, setting the flags.
  1484. if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
  1485. return false;
  1486. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
  1487. .addMBB(TrueMBB).addImm(CC);
  1488. // X86 requires a second branch to handle UNE (and OEQ, which is mapped
  1489. // to UNE above).
  1490. if (NeedExtraBranch) {
  1491. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
  1492. .addMBB(TrueMBB).addImm(X86::COND_P);
  1493. }
  1494. finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
  1495. return true;
  1496. }
  1497. } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
  1498. // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
  1499. // typically happen for _Bool and C++ bools.
  1500. MVT SourceVT;
  1501. if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
  1502. isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
  1503. unsigned TestOpc = 0;
  1504. switch (SourceVT.SimpleTy) {
  1505. default: break;
  1506. case MVT::i8: TestOpc = X86::TEST8ri; break;
  1507. case MVT::i16: TestOpc = X86::TEST16ri; break;
  1508. case MVT::i32: TestOpc = X86::TEST32ri; break;
  1509. case MVT::i64: TestOpc = X86::TEST64ri32; break;
  1510. }
  1511. if (TestOpc) {
  1512. Register OpReg = getRegForValue(TI->getOperand(0));
  1513. if (OpReg == 0) return false;
  1514. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TestOpc))
  1515. .addReg(OpReg).addImm(1);
  1516. unsigned JmpCond = X86::COND_NE;
  1517. if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
  1518. std::swap(TrueMBB, FalseMBB);
  1519. JmpCond = X86::COND_E;
  1520. }
  1521. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
  1522. .addMBB(TrueMBB).addImm(JmpCond);
  1523. finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
  1524. return true;
  1525. }
  1526. }
  1527. } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
  1528. // Fake request the condition, otherwise the intrinsic might be completely
  1529. // optimized away.
  1530. Register TmpReg = getRegForValue(BI->getCondition());
  1531. if (TmpReg == 0)
  1532. return false;
  1533. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
  1534. .addMBB(TrueMBB).addImm(CC);
  1535. finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
  1536. return true;
  1537. }
  1538. // Otherwise do a clumsy setcc and re-test it.
  1539. // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
  1540. // in an explicit cast, so make sure to handle that correctly.
  1541. Register OpReg = getRegForValue(BI->getCondition());
  1542. if (OpReg == 0) return false;
  1543. // In case OpReg is a K register, COPY to a GPR
  1544. if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
  1545. unsigned KOpReg = OpReg;
  1546. OpReg = createResultReg(&X86::GR32RegClass);
  1547. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1548. TII.get(TargetOpcode::COPY), OpReg)
  1549. .addReg(KOpReg);
  1550. OpReg = fastEmitInst_extractsubreg(MVT::i8, OpReg, X86::sub_8bit);
  1551. }
  1552. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::TEST8ri))
  1553. .addReg(OpReg)
  1554. .addImm(1);
  1555. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
  1556. .addMBB(TrueMBB).addImm(X86::COND_NE);
  1557. finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
  1558. return true;
  1559. }
  1560. bool X86FastISel::X86SelectShift(const Instruction *I) {
  1561. unsigned CReg = 0, OpReg = 0;
  1562. const TargetRegisterClass *RC = nullptr;
  1563. if (I->getType()->isIntegerTy(8)) {
  1564. CReg = X86::CL;
  1565. RC = &X86::GR8RegClass;
  1566. switch (I->getOpcode()) {
  1567. case Instruction::LShr: OpReg = X86::SHR8rCL; break;
  1568. case Instruction::AShr: OpReg = X86::SAR8rCL; break;
  1569. case Instruction::Shl: OpReg = X86::SHL8rCL; break;
  1570. default: return false;
  1571. }
  1572. } else if (I->getType()->isIntegerTy(16)) {
  1573. CReg = X86::CX;
  1574. RC = &X86::GR16RegClass;
  1575. switch (I->getOpcode()) {
  1576. default: llvm_unreachable("Unexpected shift opcode");
  1577. case Instruction::LShr: OpReg = X86::SHR16rCL; break;
  1578. case Instruction::AShr: OpReg = X86::SAR16rCL; break;
  1579. case Instruction::Shl: OpReg = X86::SHL16rCL; break;
  1580. }
  1581. } else if (I->getType()->isIntegerTy(32)) {
  1582. CReg = X86::ECX;
  1583. RC = &X86::GR32RegClass;
  1584. switch (I->getOpcode()) {
  1585. default: llvm_unreachable("Unexpected shift opcode");
  1586. case Instruction::LShr: OpReg = X86::SHR32rCL; break;
  1587. case Instruction::AShr: OpReg = X86::SAR32rCL; break;
  1588. case Instruction::Shl: OpReg = X86::SHL32rCL; break;
  1589. }
  1590. } else if (I->getType()->isIntegerTy(64)) {
  1591. CReg = X86::RCX;
  1592. RC = &X86::GR64RegClass;
  1593. switch (I->getOpcode()) {
  1594. default: llvm_unreachable("Unexpected shift opcode");
  1595. case Instruction::LShr: OpReg = X86::SHR64rCL; break;
  1596. case Instruction::AShr: OpReg = X86::SAR64rCL; break;
  1597. case Instruction::Shl: OpReg = X86::SHL64rCL; break;
  1598. }
  1599. } else {
  1600. return false;
  1601. }
  1602. MVT VT;
  1603. if (!isTypeLegal(I->getType(), VT))
  1604. return false;
  1605. Register Op0Reg = getRegForValue(I->getOperand(0));
  1606. if (Op0Reg == 0) return false;
  1607. Register Op1Reg = getRegForValue(I->getOperand(1));
  1608. if (Op1Reg == 0) return false;
  1609. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
  1610. CReg).addReg(Op1Reg);
  1611. // The shift instruction uses X86::CL. If we defined a super-register
  1612. // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
  1613. if (CReg != X86::CL)
  1614. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1615. TII.get(TargetOpcode::KILL), X86::CL)
  1616. .addReg(CReg, RegState::Kill);
  1617. Register ResultReg = createResultReg(RC);
  1618. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(OpReg), ResultReg)
  1619. .addReg(Op0Reg);
  1620. updateValueMap(I, ResultReg);
  1621. return true;
  1622. }
  1623. bool X86FastISel::X86SelectDivRem(const Instruction *I) {
  1624. const static unsigned NumTypes = 4; // i8, i16, i32, i64
  1625. const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
  1626. const static bool S = true; // IsSigned
  1627. const static bool U = false; // !IsSigned
  1628. const static unsigned Copy = TargetOpcode::COPY;
  1629. // For the X86 DIV/IDIV instruction, in most cases the dividend
  1630. // (numerator) must be in a specific register pair highreg:lowreg,
  1631. // producing the quotient in lowreg and the remainder in highreg.
  1632. // For most data types, to set up the instruction, the dividend is
  1633. // copied into lowreg, and lowreg is sign-extended or zero-extended
  1634. // into highreg. The exception is i8, where the dividend is defined
  1635. // as a single register rather than a register pair, and we
  1636. // therefore directly sign-extend or zero-extend the dividend into
  1637. // lowreg, instead of copying, and ignore the highreg.
  1638. const static struct DivRemEntry {
  1639. // The following portion depends only on the data type.
  1640. const TargetRegisterClass *RC;
  1641. unsigned LowInReg; // low part of the register pair
  1642. unsigned HighInReg; // high part of the register pair
  1643. // The following portion depends on both the data type and the operation.
  1644. struct DivRemResult {
  1645. unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
  1646. unsigned OpSignExtend; // Opcode for sign-extending lowreg into
  1647. // highreg, or copying a zero into highreg.
  1648. unsigned OpCopy; // Opcode for copying dividend into lowreg, or
  1649. // zero/sign-extending into lowreg for i8.
  1650. unsigned DivRemResultReg; // Register containing the desired result.
  1651. bool IsOpSigned; // Whether to use signed or unsigned form.
  1652. } ResultTable[NumOps];
  1653. } OpTable[NumTypes] = {
  1654. { &X86::GR8RegClass, X86::AX, 0, {
  1655. { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
  1656. { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
  1657. { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
  1658. { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
  1659. }
  1660. }, // i8
  1661. { &X86::GR16RegClass, X86::AX, X86::DX, {
  1662. { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
  1663. { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
  1664. { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
  1665. { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
  1666. }
  1667. }, // i16
  1668. { &X86::GR32RegClass, X86::EAX, X86::EDX, {
  1669. { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
  1670. { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
  1671. { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
  1672. { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
  1673. }
  1674. }, // i32
  1675. { &X86::GR64RegClass, X86::RAX, X86::RDX, {
  1676. { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
  1677. { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
  1678. { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
  1679. { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
  1680. }
  1681. }, // i64
  1682. };
  1683. MVT VT;
  1684. if (!isTypeLegal(I->getType(), VT))
  1685. return false;
  1686. unsigned TypeIndex, OpIndex;
  1687. switch (VT.SimpleTy) {
  1688. default: return false;
  1689. case MVT::i8: TypeIndex = 0; break;
  1690. case MVT::i16: TypeIndex = 1; break;
  1691. case MVT::i32: TypeIndex = 2; break;
  1692. case MVT::i64: TypeIndex = 3;
  1693. if (!Subtarget->is64Bit())
  1694. return false;
  1695. break;
  1696. }
  1697. switch (I->getOpcode()) {
  1698. default: llvm_unreachable("Unexpected div/rem opcode");
  1699. case Instruction::SDiv: OpIndex = 0; break;
  1700. case Instruction::SRem: OpIndex = 1; break;
  1701. case Instruction::UDiv: OpIndex = 2; break;
  1702. case Instruction::URem: OpIndex = 3; break;
  1703. }
  1704. const DivRemEntry &TypeEntry = OpTable[TypeIndex];
  1705. const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
  1706. Register Op0Reg = getRegForValue(I->getOperand(0));
  1707. if (Op0Reg == 0)
  1708. return false;
  1709. Register Op1Reg = getRegForValue(I->getOperand(1));
  1710. if (Op1Reg == 0)
  1711. return false;
  1712. // Move op0 into low-order input register.
  1713. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1714. TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
  1715. // Zero-extend or sign-extend into high-order input register.
  1716. if (OpEntry.OpSignExtend) {
  1717. if (OpEntry.IsOpSigned)
  1718. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1719. TII.get(OpEntry.OpSignExtend));
  1720. else {
  1721. Register Zero32 = createResultReg(&X86::GR32RegClass);
  1722. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1723. TII.get(X86::MOV32r0), Zero32);
  1724. // Copy the zero into the appropriate sub/super/identical physical
  1725. // register. Unfortunately the operations needed are not uniform enough
  1726. // to fit neatly into the table above.
  1727. if (VT == MVT::i16) {
  1728. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1729. TII.get(Copy), TypeEntry.HighInReg)
  1730. .addReg(Zero32, 0, X86::sub_16bit);
  1731. } else if (VT == MVT::i32) {
  1732. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1733. TII.get(Copy), TypeEntry.HighInReg)
  1734. .addReg(Zero32);
  1735. } else if (VT == MVT::i64) {
  1736. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1737. TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
  1738. .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
  1739. }
  1740. }
  1741. }
  1742. // Generate the DIV/IDIV instruction.
  1743. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1744. TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
  1745. // For i8 remainder, we can't reference ah directly, as we'll end
  1746. // up with bogus copies like %r9b = COPY %ah. Reference ax
  1747. // instead to prevent ah references in a rex instruction.
  1748. //
  1749. // The current assumption of the fast register allocator is that isel
  1750. // won't generate explicit references to the GR8_NOREX registers. If
  1751. // the allocator and/or the backend get enhanced to be more robust in
  1752. // that regard, this can be, and should be, removed.
  1753. unsigned ResultReg = 0;
  1754. if ((I->getOpcode() == Instruction::SRem ||
  1755. I->getOpcode() == Instruction::URem) &&
  1756. OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
  1757. Register SourceSuperReg = createResultReg(&X86::GR16RegClass);
  1758. Register ResultSuperReg = createResultReg(&X86::GR16RegClass);
  1759. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1760. TII.get(Copy), SourceSuperReg).addReg(X86::AX);
  1761. // Shift AX right by 8 bits instead of using AH.
  1762. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::SHR16ri),
  1763. ResultSuperReg).addReg(SourceSuperReg).addImm(8);
  1764. // Now reference the 8-bit subreg of the result.
  1765. ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
  1766. X86::sub_8bit);
  1767. }
  1768. // Copy the result out of the physreg if we haven't already.
  1769. if (!ResultReg) {
  1770. ResultReg = createResultReg(TypeEntry.RC);
  1771. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Copy), ResultReg)
  1772. .addReg(OpEntry.DivRemResultReg);
  1773. }
  1774. updateValueMap(I, ResultReg);
  1775. return true;
  1776. }
  1777. /// Emit a conditional move instruction (if the are supported) to lower
  1778. /// the select.
  1779. bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
  1780. // Check if the subtarget supports these instructions.
  1781. if (!Subtarget->canUseCMOV())
  1782. return false;
  1783. // FIXME: Add support for i8.
  1784. if (RetVT < MVT::i16 || RetVT > MVT::i64)
  1785. return false;
  1786. const Value *Cond = I->getOperand(0);
  1787. const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
  1788. bool NeedTest = true;
  1789. X86::CondCode CC = X86::COND_NE;
  1790. // Optimize conditions coming from a compare if both instructions are in the
  1791. // same basic block (values defined in other basic blocks may not have
  1792. // initialized registers).
  1793. const auto *CI = dyn_cast<CmpInst>(Cond);
  1794. if (CI && (CI->getParent() == I->getParent())) {
  1795. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  1796. // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
  1797. static const uint16_t SETFOpcTable[2][3] = {
  1798. { X86::COND_NP, X86::COND_E, X86::TEST8rr },
  1799. { X86::COND_P, X86::COND_NE, X86::OR8rr }
  1800. };
  1801. const uint16_t *SETFOpc = nullptr;
  1802. switch (Predicate) {
  1803. default: break;
  1804. case CmpInst::FCMP_OEQ:
  1805. SETFOpc = &SETFOpcTable[0][0];
  1806. Predicate = CmpInst::ICMP_NE;
  1807. break;
  1808. case CmpInst::FCMP_UNE:
  1809. SETFOpc = &SETFOpcTable[1][0];
  1810. Predicate = CmpInst::ICMP_NE;
  1811. break;
  1812. }
  1813. bool NeedSwap;
  1814. std::tie(CC, NeedSwap) = X86::getX86ConditionCode(Predicate);
  1815. assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
  1816. const Value *CmpLHS = CI->getOperand(0);
  1817. const Value *CmpRHS = CI->getOperand(1);
  1818. if (NeedSwap)
  1819. std::swap(CmpLHS, CmpRHS);
  1820. EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
  1821. // Emit a compare of the LHS and RHS, setting the flags.
  1822. if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
  1823. return false;
  1824. if (SETFOpc) {
  1825. Register FlagReg1 = createResultReg(&X86::GR8RegClass);
  1826. Register FlagReg2 = createResultReg(&X86::GR8RegClass);
  1827. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::SETCCr),
  1828. FlagReg1).addImm(SETFOpc[0]);
  1829. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::SETCCr),
  1830. FlagReg2).addImm(SETFOpc[1]);
  1831. auto const &II = TII.get(SETFOpc[2]);
  1832. if (II.getNumDefs()) {
  1833. Register TmpReg = createResultReg(&X86::GR8RegClass);
  1834. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, TmpReg)
  1835. .addReg(FlagReg2).addReg(FlagReg1);
  1836. } else {
  1837. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
  1838. .addReg(FlagReg2).addReg(FlagReg1);
  1839. }
  1840. }
  1841. NeedTest = false;
  1842. } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
  1843. // Fake request the condition, otherwise the intrinsic might be completely
  1844. // optimized away.
  1845. Register TmpReg = getRegForValue(Cond);
  1846. if (TmpReg == 0)
  1847. return false;
  1848. NeedTest = false;
  1849. }
  1850. if (NeedTest) {
  1851. // Selects operate on i1, however, CondReg is 8 bits width and may contain
  1852. // garbage. Indeed, only the less significant bit is supposed to be
  1853. // accurate. If we read more than the lsb, we may see non-zero values
  1854. // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
  1855. // the select. This is achieved by performing TEST against 1.
  1856. Register CondReg = getRegForValue(Cond);
  1857. if (CondReg == 0)
  1858. return false;
  1859. // In case OpReg is a K register, COPY to a GPR
  1860. if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
  1861. unsigned KCondReg = CondReg;
  1862. CondReg = createResultReg(&X86::GR32RegClass);
  1863. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1864. TII.get(TargetOpcode::COPY), CondReg)
  1865. .addReg(KCondReg);
  1866. CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, X86::sub_8bit);
  1867. }
  1868. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::TEST8ri))
  1869. .addReg(CondReg)
  1870. .addImm(1);
  1871. }
  1872. const Value *LHS = I->getOperand(1);
  1873. const Value *RHS = I->getOperand(2);
  1874. Register RHSReg = getRegForValue(RHS);
  1875. Register LHSReg = getRegForValue(LHS);
  1876. if (!LHSReg || !RHSReg)
  1877. return false;
  1878. const TargetRegisterInfo &TRI = *Subtarget->getRegisterInfo();
  1879. unsigned Opc = X86::getCMovOpcode(TRI.getRegSizeInBits(*RC)/8);
  1880. Register ResultReg = fastEmitInst_rri(Opc, RC, RHSReg, LHSReg, CC);
  1881. updateValueMap(I, ResultReg);
  1882. return true;
  1883. }
  1884. /// Emit SSE or AVX instructions to lower the select.
  1885. ///
  1886. /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
  1887. /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
  1888. /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
  1889. bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
  1890. // Optimize conditions coming from a compare if both instructions are in the
  1891. // same basic block (values defined in other basic blocks may not have
  1892. // initialized registers).
  1893. const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
  1894. if (!CI || (CI->getParent() != I->getParent()))
  1895. return false;
  1896. if (I->getType() != CI->getOperand(0)->getType() ||
  1897. !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
  1898. (Subtarget->hasSSE2() && RetVT == MVT::f64)))
  1899. return false;
  1900. const Value *CmpLHS = CI->getOperand(0);
  1901. const Value *CmpRHS = CI->getOperand(1);
  1902. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  1903. // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
  1904. // We don't have to materialize a zero constant for this case and can just use
  1905. // %x again on the RHS.
  1906. if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
  1907. const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
  1908. if (CmpRHSC && CmpRHSC->isNullValue())
  1909. CmpRHS = CmpLHS;
  1910. }
  1911. unsigned CC;
  1912. bool NeedSwap;
  1913. std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
  1914. if (CC > 7 && !Subtarget->hasAVX())
  1915. return false;
  1916. if (NeedSwap)
  1917. std::swap(CmpLHS, CmpRHS);
  1918. const Value *LHS = I->getOperand(1);
  1919. const Value *RHS = I->getOperand(2);
  1920. Register LHSReg = getRegForValue(LHS);
  1921. Register RHSReg = getRegForValue(RHS);
  1922. Register CmpLHSReg = getRegForValue(CmpLHS);
  1923. Register CmpRHSReg = getRegForValue(CmpRHS);
  1924. if (!LHSReg || !RHSReg || !CmpLHSReg || !CmpRHSReg)
  1925. return false;
  1926. const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
  1927. unsigned ResultReg;
  1928. if (Subtarget->hasAVX512()) {
  1929. // If we have AVX512 we can use a mask compare and masked movss/sd.
  1930. const TargetRegisterClass *VR128X = &X86::VR128XRegClass;
  1931. const TargetRegisterClass *VK1 = &X86::VK1RegClass;
  1932. unsigned CmpOpcode =
  1933. (RetVT == MVT::f32) ? X86::VCMPSSZrr : X86::VCMPSDZrr;
  1934. Register CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpRHSReg,
  1935. CC);
  1936. // Need an IMPLICIT_DEF for the input that is used to generate the upper
  1937. // bits of the result register since its not based on any of the inputs.
  1938. Register ImplicitDefReg = createResultReg(VR128X);
  1939. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1940. TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
  1941. // Place RHSReg is the passthru of the masked movss/sd operation and put
  1942. // LHS in the input. The mask input comes from the compare.
  1943. unsigned MovOpcode =
  1944. (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk;
  1945. unsigned MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, CmpReg,
  1946. ImplicitDefReg, LHSReg);
  1947. ResultReg = createResultReg(RC);
  1948. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1949. TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg);
  1950. } else if (Subtarget->hasAVX()) {
  1951. const TargetRegisterClass *VR128 = &X86::VR128RegClass;
  1952. // If we have AVX, create 1 blendv instead of 3 logic instructions.
  1953. // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
  1954. // uses XMM0 as the selection register. That may need just as many
  1955. // instructions as the AND/ANDN/OR sequence due to register moves, so
  1956. // don't bother.
  1957. unsigned CmpOpcode =
  1958. (RetVT == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
  1959. unsigned BlendOpcode =
  1960. (RetVT == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
  1961. Register CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpRHSReg,
  1962. CC);
  1963. Register VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, LHSReg,
  1964. CmpReg);
  1965. ResultReg = createResultReg(RC);
  1966. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1967. TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
  1968. } else {
  1969. // Choose the SSE instruction sequence based on data type (float or double).
  1970. static const uint16_t OpcTable[2][4] = {
  1971. { X86::CMPSSrr, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr },
  1972. { X86::CMPSDrr, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr }
  1973. };
  1974. const uint16_t *Opc = nullptr;
  1975. switch (RetVT.SimpleTy) {
  1976. default: return false;
  1977. case MVT::f32: Opc = &OpcTable[0][0]; break;
  1978. case MVT::f64: Opc = &OpcTable[1][0]; break;
  1979. }
  1980. const TargetRegisterClass *VR128 = &X86::VR128RegClass;
  1981. Register CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpRHSReg, CC);
  1982. Register AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, LHSReg);
  1983. Register AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, RHSReg);
  1984. Register OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, AndReg);
  1985. ResultReg = createResultReg(RC);
  1986. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  1987. TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg);
  1988. }
  1989. updateValueMap(I, ResultReg);
  1990. return true;
  1991. }
  1992. bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
  1993. // These are pseudo CMOV instructions and will be later expanded into control-
  1994. // flow.
  1995. unsigned Opc;
  1996. switch (RetVT.SimpleTy) {
  1997. default: return false;
  1998. case MVT::i8: Opc = X86::CMOV_GR8; break;
  1999. case MVT::i16: Opc = X86::CMOV_GR16; break;
  2000. case MVT::i32: Opc = X86::CMOV_GR32; break;
  2001. case MVT::f16:
  2002. Opc = Subtarget->hasAVX512() ? X86::CMOV_FR16X : X86::CMOV_FR16; break;
  2003. case MVT::f32:
  2004. Opc = Subtarget->hasAVX512() ? X86::CMOV_FR32X : X86::CMOV_FR32; break;
  2005. case MVT::f64:
  2006. Opc = Subtarget->hasAVX512() ? X86::CMOV_FR64X : X86::CMOV_FR64; break;
  2007. }
  2008. const Value *Cond = I->getOperand(0);
  2009. X86::CondCode CC = X86::COND_NE;
  2010. // Optimize conditions coming from a compare if both instructions are in the
  2011. // same basic block (values defined in other basic blocks may not have
  2012. // initialized registers).
  2013. const auto *CI = dyn_cast<CmpInst>(Cond);
  2014. if (CI && (CI->getParent() == I->getParent())) {
  2015. bool NeedSwap;
  2016. std::tie(CC, NeedSwap) = X86::getX86ConditionCode(CI->getPredicate());
  2017. if (CC > X86::LAST_VALID_COND)
  2018. return false;
  2019. const Value *CmpLHS = CI->getOperand(0);
  2020. const Value *CmpRHS = CI->getOperand(1);
  2021. if (NeedSwap)
  2022. std::swap(CmpLHS, CmpRHS);
  2023. EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
  2024. if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
  2025. return false;
  2026. } else {
  2027. Register CondReg = getRegForValue(Cond);
  2028. if (CondReg == 0)
  2029. return false;
  2030. // In case OpReg is a K register, COPY to a GPR
  2031. if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
  2032. unsigned KCondReg = CondReg;
  2033. CondReg = createResultReg(&X86::GR32RegClass);
  2034. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2035. TII.get(TargetOpcode::COPY), CondReg)
  2036. .addReg(KCondReg);
  2037. CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, X86::sub_8bit);
  2038. }
  2039. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::TEST8ri))
  2040. .addReg(CondReg)
  2041. .addImm(1);
  2042. }
  2043. const Value *LHS = I->getOperand(1);
  2044. const Value *RHS = I->getOperand(2);
  2045. Register LHSReg = getRegForValue(LHS);
  2046. Register RHSReg = getRegForValue(RHS);
  2047. if (!LHSReg || !RHSReg)
  2048. return false;
  2049. const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
  2050. Register ResultReg =
  2051. fastEmitInst_rri(Opc, RC, RHSReg, LHSReg, CC);
  2052. updateValueMap(I, ResultReg);
  2053. return true;
  2054. }
  2055. bool X86FastISel::X86SelectSelect(const Instruction *I) {
  2056. MVT RetVT;
  2057. if (!isTypeLegal(I->getType(), RetVT))
  2058. return false;
  2059. // Check if we can fold the select.
  2060. if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
  2061. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  2062. const Value *Opnd = nullptr;
  2063. switch (Predicate) {
  2064. default: break;
  2065. case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
  2066. case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
  2067. }
  2068. // No need for a select anymore - this is an unconditional move.
  2069. if (Opnd) {
  2070. Register OpReg = getRegForValue(Opnd);
  2071. if (OpReg == 0)
  2072. return false;
  2073. const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
  2074. Register ResultReg = createResultReg(RC);
  2075. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2076. TII.get(TargetOpcode::COPY), ResultReg)
  2077. .addReg(OpReg);
  2078. updateValueMap(I, ResultReg);
  2079. return true;
  2080. }
  2081. }
  2082. // First try to use real conditional move instructions.
  2083. if (X86FastEmitCMoveSelect(RetVT, I))
  2084. return true;
  2085. // Try to use a sequence of SSE instructions to simulate a conditional move.
  2086. if (X86FastEmitSSESelect(RetVT, I))
  2087. return true;
  2088. // Fall-back to pseudo conditional move instructions, which will be later
  2089. // converted to control-flow.
  2090. if (X86FastEmitPseudoSelect(RetVT, I))
  2091. return true;
  2092. return false;
  2093. }
  2094. // Common code for X86SelectSIToFP and X86SelectUIToFP.
  2095. bool X86FastISel::X86SelectIntToFP(const Instruction *I, bool IsSigned) {
  2096. // The target-independent selection algorithm in FastISel already knows how
  2097. // to select a SINT_TO_FP if the target is SSE but not AVX.
  2098. // Early exit if the subtarget doesn't have AVX.
  2099. // Unsigned conversion requires avx512.
  2100. bool HasAVX512 = Subtarget->hasAVX512();
  2101. if (!Subtarget->hasAVX() || (!IsSigned && !HasAVX512))
  2102. return false;
  2103. // TODO: We could sign extend narrower types.
  2104. MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
  2105. if (SrcVT != MVT::i32 && SrcVT != MVT::i64)
  2106. return false;
  2107. // Select integer to float/double conversion.
  2108. Register OpReg = getRegForValue(I->getOperand(0));
  2109. if (OpReg == 0)
  2110. return false;
  2111. unsigned Opcode;
  2112. static const uint16_t SCvtOpc[2][2][2] = {
  2113. { { X86::VCVTSI2SSrr, X86::VCVTSI642SSrr },
  2114. { X86::VCVTSI2SDrr, X86::VCVTSI642SDrr } },
  2115. { { X86::VCVTSI2SSZrr, X86::VCVTSI642SSZrr },
  2116. { X86::VCVTSI2SDZrr, X86::VCVTSI642SDZrr } },
  2117. };
  2118. static const uint16_t UCvtOpc[2][2] = {
  2119. { X86::VCVTUSI2SSZrr, X86::VCVTUSI642SSZrr },
  2120. { X86::VCVTUSI2SDZrr, X86::VCVTUSI642SDZrr },
  2121. };
  2122. bool Is64Bit = SrcVT == MVT::i64;
  2123. if (I->getType()->isDoubleTy()) {
  2124. // s/uitofp int -> double
  2125. Opcode = IsSigned ? SCvtOpc[HasAVX512][1][Is64Bit] : UCvtOpc[1][Is64Bit];
  2126. } else if (I->getType()->isFloatTy()) {
  2127. // s/uitofp int -> float
  2128. Opcode = IsSigned ? SCvtOpc[HasAVX512][0][Is64Bit] : UCvtOpc[0][Is64Bit];
  2129. } else
  2130. return false;
  2131. MVT DstVT = TLI.getValueType(DL, I->getType()).getSimpleVT();
  2132. const TargetRegisterClass *RC = TLI.getRegClassFor(DstVT);
  2133. Register ImplicitDefReg = createResultReg(RC);
  2134. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2135. TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
  2136. Register ResultReg = fastEmitInst_rr(Opcode, RC, ImplicitDefReg, OpReg);
  2137. updateValueMap(I, ResultReg);
  2138. return true;
  2139. }
  2140. bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
  2141. return X86SelectIntToFP(I, /*IsSigned*/true);
  2142. }
  2143. bool X86FastISel::X86SelectUIToFP(const Instruction *I) {
  2144. return X86SelectIntToFP(I, /*IsSigned*/false);
  2145. }
  2146. // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
  2147. bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
  2148. unsigned TargetOpc,
  2149. const TargetRegisterClass *RC) {
  2150. assert((I->getOpcode() == Instruction::FPExt ||
  2151. I->getOpcode() == Instruction::FPTrunc) &&
  2152. "Instruction must be an FPExt or FPTrunc!");
  2153. bool HasAVX = Subtarget->hasAVX();
  2154. Register OpReg = getRegForValue(I->getOperand(0));
  2155. if (OpReg == 0)
  2156. return false;
  2157. unsigned ImplicitDefReg;
  2158. if (HasAVX) {
  2159. ImplicitDefReg = createResultReg(RC);
  2160. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2161. TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
  2162. }
  2163. Register ResultReg = createResultReg(RC);
  2164. MachineInstrBuilder MIB;
  2165. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpc),
  2166. ResultReg);
  2167. if (HasAVX)
  2168. MIB.addReg(ImplicitDefReg);
  2169. MIB.addReg(OpReg);
  2170. updateValueMap(I, ResultReg);
  2171. return true;
  2172. }
  2173. bool X86FastISel::X86SelectFPExt(const Instruction *I) {
  2174. if (Subtarget->hasSSE2() && I->getType()->isDoubleTy() &&
  2175. I->getOperand(0)->getType()->isFloatTy()) {
  2176. bool HasAVX512 = Subtarget->hasAVX512();
  2177. // fpext from float to double.
  2178. unsigned Opc =
  2179. HasAVX512 ? X86::VCVTSS2SDZrr
  2180. : Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
  2181. return X86SelectFPExtOrFPTrunc(I, Opc, TLI.getRegClassFor(MVT::f64));
  2182. }
  2183. return false;
  2184. }
  2185. bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
  2186. if (Subtarget->hasSSE2() && I->getType()->isFloatTy() &&
  2187. I->getOperand(0)->getType()->isDoubleTy()) {
  2188. bool HasAVX512 = Subtarget->hasAVX512();
  2189. // fptrunc from double to float.
  2190. unsigned Opc =
  2191. HasAVX512 ? X86::VCVTSD2SSZrr
  2192. : Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
  2193. return X86SelectFPExtOrFPTrunc(I, Opc, TLI.getRegClassFor(MVT::f32));
  2194. }
  2195. return false;
  2196. }
  2197. bool X86FastISel::X86SelectTrunc(const Instruction *I) {
  2198. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  2199. EVT DstVT = TLI.getValueType(DL, I->getType());
  2200. // This code only handles truncation to byte.
  2201. if (DstVT != MVT::i8 && DstVT != MVT::i1)
  2202. return false;
  2203. if (!TLI.isTypeLegal(SrcVT))
  2204. return false;
  2205. Register InputReg = getRegForValue(I->getOperand(0));
  2206. if (!InputReg)
  2207. // Unhandled operand. Halt "fast" selection and bail.
  2208. return false;
  2209. if (SrcVT == MVT::i8) {
  2210. // Truncate from i8 to i1; no code needed.
  2211. updateValueMap(I, InputReg);
  2212. return true;
  2213. }
  2214. // Issue an extract_subreg.
  2215. Register ResultReg = fastEmitInst_extractsubreg(MVT::i8, InputReg,
  2216. X86::sub_8bit);
  2217. if (!ResultReg)
  2218. return false;
  2219. updateValueMap(I, ResultReg);
  2220. return true;
  2221. }
  2222. bool X86FastISel::IsMemcpySmall(uint64_t Len) {
  2223. return Len <= (Subtarget->is64Bit() ? 32 : 16);
  2224. }
  2225. bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
  2226. X86AddressMode SrcAM, uint64_t Len) {
  2227. // Make sure we don't bloat code by inlining very large memcpy's.
  2228. if (!IsMemcpySmall(Len))
  2229. return false;
  2230. bool i64Legal = Subtarget->is64Bit();
  2231. // We don't care about alignment here since we just emit integer accesses.
  2232. while (Len) {
  2233. MVT VT;
  2234. if (Len >= 8 && i64Legal)
  2235. VT = MVT::i64;
  2236. else if (Len >= 4)
  2237. VT = MVT::i32;
  2238. else if (Len >= 2)
  2239. VT = MVT::i16;
  2240. else
  2241. VT = MVT::i8;
  2242. unsigned Reg;
  2243. bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
  2244. RV &= X86FastEmitStore(VT, Reg, DestAM);
  2245. assert(RV && "Failed to emit load or store??");
  2246. (void)RV;
  2247. unsigned Size = VT.getSizeInBits()/8;
  2248. Len -= Size;
  2249. DestAM.Disp += Size;
  2250. SrcAM.Disp += Size;
  2251. }
  2252. return true;
  2253. }
  2254. bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
  2255. // FIXME: Handle more intrinsics.
  2256. switch (II->getIntrinsicID()) {
  2257. default: return false;
  2258. case Intrinsic::convert_from_fp16:
  2259. case Intrinsic::convert_to_fp16: {
  2260. if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
  2261. return false;
  2262. const Value *Op = II->getArgOperand(0);
  2263. Register InputReg = getRegForValue(Op);
  2264. if (InputReg == 0)
  2265. return false;
  2266. // F16C only allows converting from float to half and from half to float.
  2267. bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
  2268. if (IsFloatToHalf) {
  2269. if (!Op->getType()->isFloatTy())
  2270. return false;
  2271. } else {
  2272. if (!II->getType()->isFloatTy())
  2273. return false;
  2274. }
  2275. unsigned ResultReg = 0;
  2276. const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
  2277. if (IsFloatToHalf) {
  2278. // 'InputReg' is implicitly promoted from register class FR32 to
  2279. // register class VR128 by method 'constrainOperandRegClass' which is
  2280. // directly called by 'fastEmitInst_ri'.
  2281. // Instruction VCVTPS2PHrr takes an extra immediate operand which is
  2282. // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
  2283. // It's consistent with the other FP instructions, which are usually
  2284. // controlled by MXCSR.
  2285. unsigned Opc = Subtarget->hasVLX() ? X86::VCVTPS2PHZ128rr
  2286. : X86::VCVTPS2PHrr;
  2287. InputReg = fastEmitInst_ri(Opc, RC, InputReg, 4);
  2288. // Move the lower 32-bits of ResultReg to another register of class GR32.
  2289. Opc = Subtarget->hasAVX512() ? X86::VMOVPDI2DIZrr
  2290. : X86::VMOVPDI2DIrr;
  2291. ResultReg = createResultReg(&X86::GR32RegClass);
  2292. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), ResultReg)
  2293. .addReg(InputReg, RegState::Kill);
  2294. // The result value is in the lower 16-bits of ResultReg.
  2295. unsigned RegIdx = X86::sub_16bit;
  2296. ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, RegIdx);
  2297. } else {
  2298. assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
  2299. // Explicitly zero-extend the input to 32-bit.
  2300. InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::ZERO_EXTEND, InputReg);
  2301. // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
  2302. InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
  2303. InputReg);
  2304. unsigned Opc = Subtarget->hasVLX() ? X86::VCVTPH2PSZ128rr
  2305. : X86::VCVTPH2PSrr;
  2306. InputReg = fastEmitInst_r(Opc, RC, InputReg);
  2307. // The result value is in the lower 32-bits of ResultReg.
  2308. // Emit an explicit copy from register class VR128 to register class FR32.
  2309. ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
  2310. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2311. TII.get(TargetOpcode::COPY), ResultReg)
  2312. .addReg(InputReg, RegState::Kill);
  2313. }
  2314. updateValueMap(II, ResultReg);
  2315. return true;
  2316. }
  2317. case Intrinsic::frameaddress: {
  2318. MachineFunction *MF = FuncInfo.MF;
  2319. if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
  2320. return false;
  2321. Type *RetTy = II->getCalledFunction()->getReturnType();
  2322. MVT VT;
  2323. if (!isTypeLegal(RetTy, VT))
  2324. return false;
  2325. unsigned Opc;
  2326. const TargetRegisterClass *RC = nullptr;
  2327. switch (VT.SimpleTy) {
  2328. default: llvm_unreachable("Invalid result type for frameaddress.");
  2329. case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
  2330. case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
  2331. }
  2332. // This needs to be set before we call getPtrSizedFrameRegister, otherwise
  2333. // we get the wrong frame register.
  2334. MachineFrameInfo &MFI = MF->getFrameInfo();
  2335. MFI.setFrameAddressIsTaken(true);
  2336. const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
  2337. unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
  2338. assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
  2339. (FrameReg == X86::EBP && VT == MVT::i32)) &&
  2340. "Invalid Frame Register!");
  2341. // Always make a copy of the frame register to a vreg first, so that we
  2342. // never directly reference the frame register (the TwoAddressInstruction-
  2343. // Pass doesn't like that).
  2344. Register SrcReg = createResultReg(RC);
  2345. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2346. TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
  2347. // Now recursively load from the frame address.
  2348. // movq (%rbp), %rax
  2349. // movq (%rax), %rax
  2350. // movq (%rax), %rax
  2351. // ...
  2352. unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
  2353. while (Depth--) {
  2354. Register DestReg = createResultReg(RC);
  2355. addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2356. TII.get(Opc), DestReg), SrcReg);
  2357. SrcReg = DestReg;
  2358. }
  2359. updateValueMap(II, SrcReg);
  2360. return true;
  2361. }
  2362. case Intrinsic::memcpy: {
  2363. const MemCpyInst *MCI = cast<MemCpyInst>(II);
  2364. // Don't handle volatile or variable length memcpys.
  2365. if (MCI->isVolatile())
  2366. return false;
  2367. if (isa<ConstantInt>(MCI->getLength())) {
  2368. // Small memcpy's are common enough that we want to do them
  2369. // without a call if possible.
  2370. uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
  2371. if (IsMemcpySmall(Len)) {
  2372. X86AddressMode DestAM, SrcAM;
  2373. if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
  2374. !X86SelectAddress(MCI->getRawSource(), SrcAM))
  2375. return false;
  2376. TryEmitSmallMemcpy(DestAM, SrcAM, Len);
  2377. return true;
  2378. }
  2379. }
  2380. unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
  2381. if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
  2382. return false;
  2383. if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
  2384. return false;
  2385. return lowerCallTo(II, "memcpy", II->arg_size() - 1);
  2386. }
  2387. case Intrinsic::memset: {
  2388. const MemSetInst *MSI = cast<MemSetInst>(II);
  2389. if (MSI->isVolatile())
  2390. return false;
  2391. unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
  2392. if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
  2393. return false;
  2394. if (MSI->getDestAddressSpace() > 255)
  2395. return false;
  2396. return lowerCallTo(II, "memset", II->arg_size() - 1);
  2397. }
  2398. case Intrinsic::stackprotector: {
  2399. // Emit code to store the stack guard onto the stack.
  2400. EVT PtrTy = TLI.getPointerTy(DL);
  2401. const Value *Op1 = II->getArgOperand(0); // The guard's value.
  2402. const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
  2403. MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
  2404. // Grab the frame index.
  2405. X86AddressMode AM;
  2406. if (!X86SelectAddress(Slot, AM)) return false;
  2407. if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
  2408. return true;
  2409. }
  2410. case Intrinsic::dbg_declare: {
  2411. const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
  2412. X86AddressMode AM;
  2413. assert(DI->getAddress() && "Null address should be checked earlier!");
  2414. if (!X86SelectAddress(DI->getAddress(), AM))
  2415. return false;
  2416. const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
  2417. assert(DI->getVariable()->isValidLocationForIntrinsic(MIMD.getDL()) &&
  2418. "Expected inlined-at fields to agree");
  2419. addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II), AM)
  2420. .addImm(0)
  2421. .addMetadata(DI->getVariable())
  2422. .addMetadata(DI->getExpression());
  2423. return true;
  2424. }
  2425. case Intrinsic::trap: {
  2426. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::TRAP));
  2427. return true;
  2428. }
  2429. case Intrinsic::sqrt: {
  2430. if (!Subtarget->hasSSE1())
  2431. return false;
  2432. Type *RetTy = II->getCalledFunction()->getReturnType();
  2433. MVT VT;
  2434. if (!isTypeLegal(RetTy, VT))
  2435. return false;
  2436. // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
  2437. // is not generated by FastISel yet.
  2438. // FIXME: Update this code once tablegen can handle it.
  2439. static const uint16_t SqrtOpc[3][2] = {
  2440. { X86::SQRTSSr, X86::SQRTSDr },
  2441. { X86::VSQRTSSr, X86::VSQRTSDr },
  2442. { X86::VSQRTSSZr, X86::VSQRTSDZr },
  2443. };
  2444. unsigned AVXLevel = Subtarget->hasAVX512() ? 2 :
  2445. Subtarget->hasAVX() ? 1 :
  2446. 0;
  2447. unsigned Opc;
  2448. switch (VT.SimpleTy) {
  2449. default: return false;
  2450. case MVT::f32: Opc = SqrtOpc[AVXLevel][0]; break;
  2451. case MVT::f64: Opc = SqrtOpc[AVXLevel][1]; break;
  2452. }
  2453. const Value *SrcVal = II->getArgOperand(0);
  2454. Register SrcReg = getRegForValue(SrcVal);
  2455. if (SrcReg == 0)
  2456. return false;
  2457. const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
  2458. unsigned ImplicitDefReg = 0;
  2459. if (AVXLevel > 0) {
  2460. ImplicitDefReg = createResultReg(RC);
  2461. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2462. TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
  2463. }
  2464. Register ResultReg = createResultReg(RC);
  2465. MachineInstrBuilder MIB;
  2466. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc),
  2467. ResultReg);
  2468. if (ImplicitDefReg)
  2469. MIB.addReg(ImplicitDefReg);
  2470. MIB.addReg(SrcReg);
  2471. updateValueMap(II, ResultReg);
  2472. return true;
  2473. }
  2474. case Intrinsic::sadd_with_overflow:
  2475. case Intrinsic::uadd_with_overflow:
  2476. case Intrinsic::ssub_with_overflow:
  2477. case Intrinsic::usub_with_overflow:
  2478. case Intrinsic::smul_with_overflow:
  2479. case Intrinsic::umul_with_overflow: {
  2480. // This implements the basic lowering of the xalu with overflow intrinsics
  2481. // into add/sub/mul followed by either seto or setb.
  2482. const Function *Callee = II->getCalledFunction();
  2483. auto *Ty = cast<StructType>(Callee->getReturnType());
  2484. Type *RetTy = Ty->getTypeAtIndex(0U);
  2485. assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&
  2486. Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&
  2487. "Overflow value expected to be an i1");
  2488. MVT VT;
  2489. if (!isTypeLegal(RetTy, VT))
  2490. return false;
  2491. if (VT < MVT::i8 || VT > MVT::i64)
  2492. return false;
  2493. const Value *LHS = II->getArgOperand(0);
  2494. const Value *RHS = II->getArgOperand(1);
  2495. // Canonicalize immediate to the RHS.
  2496. if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) && II->isCommutative())
  2497. std::swap(LHS, RHS);
  2498. unsigned BaseOpc, CondCode;
  2499. switch (II->getIntrinsicID()) {
  2500. default: llvm_unreachable("Unexpected intrinsic!");
  2501. case Intrinsic::sadd_with_overflow:
  2502. BaseOpc = ISD::ADD; CondCode = X86::COND_O; break;
  2503. case Intrinsic::uadd_with_overflow:
  2504. BaseOpc = ISD::ADD; CondCode = X86::COND_B; break;
  2505. case Intrinsic::ssub_with_overflow:
  2506. BaseOpc = ISD::SUB; CondCode = X86::COND_O; break;
  2507. case Intrinsic::usub_with_overflow:
  2508. BaseOpc = ISD::SUB; CondCode = X86::COND_B; break;
  2509. case Intrinsic::smul_with_overflow:
  2510. BaseOpc = X86ISD::SMUL; CondCode = X86::COND_O; break;
  2511. case Intrinsic::umul_with_overflow:
  2512. BaseOpc = X86ISD::UMUL; CondCode = X86::COND_O; break;
  2513. }
  2514. Register LHSReg = getRegForValue(LHS);
  2515. if (LHSReg == 0)
  2516. return false;
  2517. unsigned ResultReg = 0;
  2518. // Check if we have an immediate version.
  2519. if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
  2520. static const uint16_t Opc[2][4] = {
  2521. { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
  2522. { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
  2523. };
  2524. if (CI->isOne() && (BaseOpc == ISD::ADD || BaseOpc == ISD::SUB) &&
  2525. CondCode == X86::COND_O) {
  2526. // We can use INC/DEC.
  2527. ResultReg = createResultReg(TLI.getRegClassFor(VT));
  2528. bool IsDec = BaseOpc == ISD::SUB;
  2529. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2530. TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
  2531. .addReg(LHSReg);
  2532. } else
  2533. ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, CI->getZExtValue());
  2534. }
  2535. unsigned RHSReg;
  2536. if (!ResultReg) {
  2537. RHSReg = getRegForValue(RHS);
  2538. if (RHSReg == 0)
  2539. return false;
  2540. ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, RHSReg);
  2541. }
  2542. // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
  2543. // it manually.
  2544. if (BaseOpc == X86ISD::UMUL && !ResultReg) {
  2545. static const uint16_t MULOpc[] =
  2546. { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
  2547. static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
  2548. // First copy the first operand into RAX, which is an implicit input to
  2549. // the X86::MUL*r instruction.
  2550. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2551. TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
  2552. .addReg(LHSReg);
  2553. ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
  2554. TLI.getRegClassFor(VT), RHSReg);
  2555. } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
  2556. static const uint16_t MULOpc[] =
  2557. { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
  2558. if (VT == MVT::i8) {
  2559. // Copy the first operand into AL, which is an implicit input to the
  2560. // X86::IMUL8r instruction.
  2561. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2562. TII.get(TargetOpcode::COPY), X86::AL)
  2563. .addReg(LHSReg);
  2564. ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg);
  2565. } else
  2566. ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
  2567. TLI.getRegClassFor(VT), LHSReg, RHSReg);
  2568. }
  2569. if (!ResultReg)
  2570. return false;
  2571. // Assign to a GPR since the overflow return value is lowered to a SETcc.
  2572. Register ResultReg2 = createResultReg(&X86::GR8RegClass);
  2573. assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
  2574. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::SETCCr),
  2575. ResultReg2).addImm(CondCode);
  2576. updateValueMap(II, ResultReg, 2);
  2577. return true;
  2578. }
  2579. case Intrinsic::x86_sse_cvttss2si:
  2580. case Intrinsic::x86_sse_cvttss2si64:
  2581. case Intrinsic::x86_sse2_cvttsd2si:
  2582. case Intrinsic::x86_sse2_cvttsd2si64: {
  2583. bool IsInputDouble;
  2584. switch (II->getIntrinsicID()) {
  2585. default: llvm_unreachable("Unexpected intrinsic.");
  2586. case Intrinsic::x86_sse_cvttss2si:
  2587. case Intrinsic::x86_sse_cvttss2si64:
  2588. if (!Subtarget->hasSSE1())
  2589. return false;
  2590. IsInputDouble = false;
  2591. break;
  2592. case Intrinsic::x86_sse2_cvttsd2si:
  2593. case Intrinsic::x86_sse2_cvttsd2si64:
  2594. if (!Subtarget->hasSSE2())
  2595. return false;
  2596. IsInputDouble = true;
  2597. break;
  2598. }
  2599. Type *RetTy = II->getCalledFunction()->getReturnType();
  2600. MVT VT;
  2601. if (!isTypeLegal(RetTy, VT))
  2602. return false;
  2603. static const uint16_t CvtOpc[3][2][2] = {
  2604. { { X86::CVTTSS2SIrr, X86::CVTTSS2SI64rr },
  2605. { X86::CVTTSD2SIrr, X86::CVTTSD2SI64rr } },
  2606. { { X86::VCVTTSS2SIrr, X86::VCVTTSS2SI64rr },
  2607. { X86::VCVTTSD2SIrr, X86::VCVTTSD2SI64rr } },
  2608. { { X86::VCVTTSS2SIZrr, X86::VCVTTSS2SI64Zrr },
  2609. { X86::VCVTTSD2SIZrr, X86::VCVTTSD2SI64Zrr } },
  2610. };
  2611. unsigned AVXLevel = Subtarget->hasAVX512() ? 2 :
  2612. Subtarget->hasAVX() ? 1 :
  2613. 0;
  2614. unsigned Opc;
  2615. switch (VT.SimpleTy) {
  2616. default: llvm_unreachable("Unexpected result type.");
  2617. case MVT::i32: Opc = CvtOpc[AVXLevel][IsInputDouble][0]; break;
  2618. case MVT::i64: Opc = CvtOpc[AVXLevel][IsInputDouble][1]; break;
  2619. }
  2620. // Check if we can fold insertelement instructions into the convert.
  2621. const Value *Op = II->getArgOperand(0);
  2622. while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
  2623. const Value *Index = IE->getOperand(2);
  2624. if (!isa<ConstantInt>(Index))
  2625. break;
  2626. unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
  2627. if (Idx == 0) {
  2628. Op = IE->getOperand(1);
  2629. break;
  2630. }
  2631. Op = IE->getOperand(0);
  2632. }
  2633. Register Reg = getRegForValue(Op);
  2634. if (Reg == 0)
  2635. return false;
  2636. Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
  2637. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), ResultReg)
  2638. .addReg(Reg);
  2639. updateValueMap(II, ResultReg);
  2640. return true;
  2641. }
  2642. }
  2643. }
  2644. bool X86FastISel::fastLowerArguments() {
  2645. if (!FuncInfo.CanLowerReturn)
  2646. return false;
  2647. const Function *F = FuncInfo.Fn;
  2648. if (F->isVarArg())
  2649. return false;
  2650. CallingConv::ID CC = F->getCallingConv();
  2651. if (CC != CallingConv::C)
  2652. return false;
  2653. if (Subtarget->isCallingConvWin64(CC))
  2654. return false;
  2655. if (!Subtarget->is64Bit())
  2656. return false;
  2657. if (Subtarget->useSoftFloat())
  2658. return false;
  2659. // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
  2660. unsigned GPRCnt = 0;
  2661. unsigned FPRCnt = 0;
  2662. for (auto const &Arg : F->args()) {
  2663. if (Arg.hasAttribute(Attribute::ByVal) ||
  2664. Arg.hasAttribute(Attribute::InReg) ||
  2665. Arg.hasAttribute(Attribute::StructRet) ||
  2666. Arg.hasAttribute(Attribute::SwiftSelf) ||
  2667. Arg.hasAttribute(Attribute::SwiftAsync) ||
  2668. Arg.hasAttribute(Attribute::SwiftError) ||
  2669. Arg.hasAttribute(Attribute::Nest))
  2670. return false;
  2671. Type *ArgTy = Arg.getType();
  2672. if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
  2673. return false;
  2674. EVT ArgVT = TLI.getValueType(DL, ArgTy);
  2675. if (!ArgVT.isSimple()) return false;
  2676. switch (ArgVT.getSimpleVT().SimpleTy) {
  2677. default: return false;
  2678. case MVT::i32:
  2679. case MVT::i64:
  2680. ++GPRCnt;
  2681. break;
  2682. case MVT::f32:
  2683. case MVT::f64:
  2684. if (!Subtarget->hasSSE1())
  2685. return false;
  2686. ++FPRCnt;
  2687. break;
  2688. }
  2689. if (GPRCnt > 6)
  2690. return false;
  2691. if (FPRCnt > 8)
  2692. return false;
  2693. }
  2694. static const MCPhysReg GPR32ArgRegs[] = {
  2695. X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
  2696. };
  2697. static const MCPhysReg GPR64ArgRegs[] = {
  2698. X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
  2699. };
  2700. static const MCPhysReg XMMArgRegs[] = {
  2701. X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
  2702. X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
  2703. };
  2704. unsigned GPRIdx = 0;
  2705. unsigned FPRIdx = 0;
  2706. for (auto const &Arg : F->args()) {
  2707. MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
  2708. const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
  2709. unsigned SrcReg;
  2710. switch (VT.SimpleTy) {
  2711. default: llvm_unreachable("Unexpected value type.");
  2712. case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
  2713. case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
  2714. case MVT::f32: [[fallthrough]];
  2715. case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
  2716. }
  2717. Register DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
  2718. // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
  2719. // Without this, EmitLiveInCopies may eliminate the livein if its only
  2720. // use is a bitcast (which isn't turned into an instruction).
  2721. Register ResultReg = createResultReg(RC);
  2722. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2723. TII.get(TargetOpcode::COPY), ResultReg)
  2724. .addReg(DstReg, getKillRegState(true));
  2725. updateValueMap(&Arg, ResultReg);
  2726. }
  2727. return true;
  2728. }
  2729. static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
  2730. CallingConv::ID CC,
  2731. const CallBase *CB) {
  2732. if (Subtarget->is64Bit())
  2733. return 0;
  2734. if (Subtarget->getTargetTriple().isOSMSVCRT())
  2735. return 0;
  2736. if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
  2737. CC == CallingConv::HiPE || CC == CallingConv::Tail ||
  2738. CC == CallingConv::SwiftTail)
  2739. return 0;
  2740. if (CB)
  2741. if (CB->arg_empty() || !CB->paramHasAttr(0, Attribute::StructRet) ||
  2742. CB->paramHasAttr(0, Attribute::InReg) || Subtarget->isTargetMCU())
  2743. return 0;
  2744. return 4;
  2745. }
  2746. bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
  2747. auto &OutVals = CLI.OutVals;
  2748. auto &OutFlags = CLI.OutFlags;
  2749. auto &OutRegs = CLI.OutRegs;
  2750. auto &Ins = CLI.Ins;
  2751. auto &InRegs = CLI.InRegs;
  2752. CallingConv::ID CC = CLI.CallConv;
  2753. bool &IsTailCall = CLI.IsTailCall;
  2754. bool IsVarArg = CLI.IsVarArg;
  2755. const Value *Callee = CLI.Callee;
  2756. MCSymbol *Symbol = CLI.Symbol;
  2757. const auto *CB = CLI.CB;
  2758. bool Is64Bit = Subtarget->is64Bit();
  2759. bool IsWin64 = Subtarget->isCallingConvWin64(CC);
  2760. // Call / invoke instructions with NoCfCheck attribute require special
  2761. // handling.
  2762. if (CB && CB->doesNoCfCheck())
  2763. return false;
  2764. // Functions with no_caller_saved_registers that need special handling.
  2765. if ((CB && isa<CallInst>(CB) && CB->hasFnAttr("no_caller_saved_registers")))
  2766. return false;
  2767. // Functions with no_callee_saved_registers that need special handling.
  2768. if ((CB && CB->hasFnAttr("no_callee_saved_registers")))
  2769. return false;
  2770. // Indirect calls with CFI checks need special handling.
  2771. if (CB && CB->isIndirectCall() && CB->getOperandBundle(LLVMContext::OB_kcfi))
  2772. return false;
  2773. // Functions using thunks for indirect calls need to use SDISel.
  2774. if (Subtarget->useIndirectThunkCalls())
  2775. return false;
  2776. // Handle only C, fastcc, and webkit_js calling conventions for now.
  2777. switch (CC) {
  2778. default: return false;
  2779. case CallingConv::C:
  2780. case CallingConv::Fast:
  2781. case CallingConv::Tail:
  2782. case CallingConv::WebKit_JS:
  2783. case CallingConv::Swift:
  2784. case CallingConv::SwiftTail:
  2785. case CallingConv::X86_FastCall:
  2786. case CallingConv::X86_StdCall:
  2787. case CallingConv::X86_ThisCall:
  2788. case CallingConv::Win64:
  2789. case CallingConv::X86_64_SysV:
  2790. case CallingConv::CFGuard_Check:
  2791. break;
  2792. }
  2793. // Allow SelectionDAG isel to handle tail calls.
  2794. if (IsTailCall)
  2795. return false;
  2796. // fastcc with -tailcallopt is intended to provide a guaranteed
  2797. // tail call optimization. Fastisel doesn't know how to do that.
  2798. if ((CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) ||
  2799. CC == CallingConv::Tail || CC == CallingConv::SwiftTail)
  2800. return false;
  2801. // Don't know how to handle Win64 varargs yet. Nothing special needed for
  2802. // x86-32. Special handling for x86-64 is implemented.
  2803. if (IsVarArg && IsWin64)
  2804. return false;
  2805. // Don't know about inalloca yet.
  2806. if (CLI.CB && CLI.CB->hasInAllocaArgument())
  2807. return false;
  2808. for (auto Flag : CLI.OutFlags)
  2809. if (Flag.isSwiftError() || Flag.isPreallocated())
  2810. return false;
  2811. SmallVector<MVT, 16> OutVTs;
  2812. SmallVector<unsigned, 16> ArgRegs;
  2813. // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
  2814. // instruction. This is safe because it is common to all FastISel supported
  2815. // calling conventions on x86.
  2816. for (int i = 0, e = OutVals.size(); i != e; ++i) {
  2817. Value *&Val = OutVals[i];
  2818. ISD::ArgFlagsTy Flags = OutFlags[i];
  2819. if (auto *CI = dyn_cast<ConstantInt>(Val)) {
  2820. if (CI->getBitWidth() < 32) {
  2821. if (Flags.isSExt())
  2822. Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
  2823. else
  2824. Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
  2825. }
  2826. }
  2827. // Passing bools around ends up doing a trunc to i1 and passing it.
  2828. // Codegen this as an argument + "and 1".
  2829. MVT VT;
  2830. auto *TI = dyn_cast<TruncInst>(Val);
  2831. unsigned ResultReg;
  2832. if (TI && TI->getType()->isIntegerTy(1) && CLI.CB &&
  2833. (TI->getParent() == CLI.CB->getParent()) && TI->hasOneUse()) {
  2834. Value *PrevVal = TI->getOperand(0);
  2835. ResultReg = getRegForValue(PrevVal);
  2836. if (!ResultReg)
  2837. return false;
  2838. if (!isTypeLegal(PrevVal->getType(), VT))
  2839. return false;
  2840. ResultReg = fastEmit_ri(VT, VT, ISD::AND, ResultReg, 1);
  2841. } else {
  2842. if (!isTypeLegal(Val->getType(), VT) ||
  2843. (VT.isVector() && VT.getVectorElementType() == MVT::i1))
  2844. return false;
  2845. ResultReg = getRegForValue(Val);
  2846. }
  2847. if (!ResultReg)
  2848. return false;
  2849. ArgRegs.push_back(ResultReg);
  2850. OutVTs.push_back(VT);
  2851. }
  2852. // Analyze operands of the call, assigning locations to each operand.
  2853. SmallVector<CCValAssign, 16> ArgLocs;
  2854. CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
  2855. // Allocate shadow area for Win64
  2856. if (IsWin64)
  2857. CCInfo.AllocateStack(32, Align(8));
  2858. CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
  2859. // Get a count of how many bytes are to be pushed on the stack.
  2860. unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
  2861. // Issue CALLSEQ_START
  2862. unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
  2863. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(AdjStackDown))
  2864. .addImm(NumBytes).addImm(0).addImm(0);
  2865. // Walk the register/memloc assignments, inserting copies/loads.
  2866. const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
  2867. for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
  2868. CCValAssign const &VA = ArgLocs[i];
  2869. const Value *ArgVal = OutVals[VA.getValNo()];
  2870. MVT ArgVT = OutVTs[VA.getValNo()];
  2871. if (ArgVT == MVT::x86mmx)
  2872. return false;
  2873. unsigned ArgReg = ArgRegs[VA.getValNo()];
  2874. // Promote the value if needed.
  2875. switch (VA.getLocInfo()) {
  2876. case CCValAssign::Full: break;
  2877. case CCValAssign::SExt: {
  2878. assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
  2879. "Unexpected extend");
  2880. if (ArgVT == MVT::i1)
  2881. return false;
  2882. bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
  2883. ArgVT, ArgReg);
  2884. assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
  2885. ArgVT = VA.getLocVT();
  2886. break;
  2887. }
  2888. case CCValAssign::ZExt: {
  2889. assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
  2890. "Unexpected extend");
  2891. // Handle zero-extension from i1 to i8, which is common.
  2892. if (ArgVT == MVT::i1) {
  2893. // Set the high bits to zero.
  2894. ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg);
  2895. ArgVT = MVT::i8;
  2896. if (ArgReg == 0)
  2897. return false;
  2898. }
  2899. bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
  2900. ArgVT, ArgReg);
  2901. assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
  2902. ArgVT = VA.getLocVT();
  2903. break;
  2904. }
  2905. case CCValAssign::AExt: {
  2906. assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
  2907. "Unexpected extend");
  2908. bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
  2909. ArgVT, ArgReg);
  2910. if (!Emitted)
  2911. Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
  2912. ArgVT, ArgReg);
  2913. if (!Emitted)
  2914. Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
  2915. ArgVT, ArgReg);
  2916. assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
  2917. ArgVT = VA.getLocVT();
  2918. break;
  2919. }
  2920. case CCValAssign::BCvt: {
  2921. ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg);
  2922. assert(ArgReg && "Failed to emit a bitcast!");
  2923. ArgVT = VA.getLocVT();
  2924. break;
  2925. }
  2926. case CCValAssign::VExt:
  2927. // VExt has not been implemented, so this should be impossible to reach
  2928. // for now. However, fallback to Selection DAG isel once implemented.
  2929. return false;
  2930. case CCValAssign::AExtUpper:
  2931. case CCValAssign::SExtUpper:
  2932. case CCValAssign::ZExtUpper:
  2933. case CCValAssign::FPExt:
  2934. case CCValAssign::Trunc:
  2935. llvm_unreachable("Unexpected loc info!");
  2936. case CCValAssign::Indirect:
  2937. // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
  2938. // support this.
  2939. return false;
  2940. }
  2941. if (VA.isRegLoc()) {
  2942. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2943. TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
  2944. OutRegs.push_back(VA.getLocReg());
  2945. } else {
  2946. assert(VA.isMemLoc() && "Unknown value location!");
  2947. // Don't emit stores for undef values.
  2948. if (isa<UndefValue>(ArgVal))
  2949. continue;
  2950. unsigned LocMemOffset = VA.getLocMemOffset();
  2951. X86AddressMode AM;
  2952. AM.Base.Reg = RegInfo->getStackRegister();
  2953. AM.Disp = LocMemOffset;
  2954. ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
  2955. Align Alignment = DL.getABITypeAlign(ArgVal->getType());
  2956. MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
  2957. MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
  2958. MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
  2959. if (Flags.isByVal()) {
  2960. X86AddressMode SrcAM;
  2961. SrcAM.Base.Reg = ArgReg;
  2962. if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
  2963. return false;
  2964. } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
  2965. // If this is a really simple value, emit this with the Value* version
  2966. // of X86FastEmitStore. If it isn't simple, we don't want to do this,
  2967. // as it can cause us to reevaluate the argument.
  2968. if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
  2969. return false;
  2970. } else {
  2971. if (!X86FastEmitStore(ArgVT, ArgReg, AM, MMO))
  2972. return false;
  2973. }
  2974. }
  2975. }
  2976. // ELF / PIC requires GOT in the EBX register before function calls via PLT
  2977. // GOT pointer.
  2978. if (Subtarget->isPICStyleGOT()) {
  2979. unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
  2980. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  2981. TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
  2982. }
  2983. if (Is64Bit && IsVarArg && !IsWin64) {
  2984. // From AMD64 ABI document:
  2985. // For calls that may call functions that use varargs or stdargs
  2986. // (prototype-less calls or calls to functions containing ellipsis (...) in
  2987. // the declaration) %al is used as hidden argument to specify the number
  2988. // of SSE registers used. The contents of %al do not need to match exactly
  2989. // the number of registers, but must be an ubound on the number of SSE
  2990. // registers used and is in the range 0 - 8 inclusive.
  2991. // Count the number of XMM registers allocated.
  2992. static const MCPhysReg XMMArgRegs[] = {
  2993. X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
  2994. X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
  2995. };
  2996. unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
  2997. assert((Subtarget->hasSSE1() || !NumXMMRegs)
  2998. && "SSE registers cannot be used when SSE is disabled");
  2999. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV8ri),
  3000. X86::AL).addImm(NumXMMRegs);
  3001. }
  3002. // Materialize callee address in a register. FIXME: GV address can be
  3003. // handled with a CALLpcrel32 instead.
  3004. X86AddressMode CalleeAM;
  3005. if (!X86SelectCallAddress(Callee, CalleeAM))
  3006. return false;
  3007. unsigned CalleeOp = 0;
  3008. const GlobalValue *GV = nullptr;
  3009. if (CalleeAM.GV != nullptr) {
  3010. GV = CalleeAM.GV;
  3011. } else if (CalleeAM.Base.Reg != 0) {
  3012. CalleeOp = CalleeAM.Base.Reg;
  3013. } else
  3014. return false;
  3015. // Issue the call.
  3016. MachineInstrBuilder MIB;
  3017. if (CalleeOp) {
  3018. // Register-indirect call.
  3019. unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
  3020. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(CallOpc))
  3021. .addReg(CalleeOp);
  3022. } else {
  3023. // Direct call.
  3024. assert(GV && "Not a direct call");
  3025. // See if we need any target-specific flags on the GV operand.
  3026. unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
  3027. // This will be a direct call, or an indirect call through memory for
  3028. // NonLazyBind calls or dllimport calls.
  3029. bool NeedLoad = OpFlags == X86II::MO_DLLIMPORT ||
  3030. OpFlags == X86II::MO_GOTPCREL ||
  3031. OpFlags == X86II::MO_GOTPCREL_NORELAX ||
  3032. OpFlags == X86II::MO_COFFSTUB;
  3033. unsigned CallOpc = NeedLoad
  3034. ? (Is64Bit ? X86::CALL64m : X86::CALL32m)
  3035. : (Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32);
  3036. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(CallOpc));
  3037. if (NeedLoad)
  3038. MIB.addReg(Is64Bit ? X86::RIP : 0).addImm(1).addReg(0);
  3039. if (Symbol)
  3040. MIB.addSym(Symbol, OpFlags);
  3041. else
  3042. MIB.addGlobalAddress(GV, 0, OpFlags);
  3043. if (NeedLoad)
  3044. MIB.addReg(0);
  3045. }
  3046. // Add a register mask operand representing the call-preserved registers.
  3047. // Proper defs for return values will be added by setPhysRegsDeadExcept().
  3048. MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
  3049. // Add an implicit use GOT pointer in EBX.
  3050. if (Subtarget->isPICStyleGOT())
  3051. MIB.addReg(X86::EBX, RegState::Implicit);
  3052. if (Is64Bit && IsVarArg && !IsWin64)
  3053. MIB.addReg(X86::AL, RegState::Implicit);
  3054. // Add implicit physical register uses to the call.
  3055. for (auto Reg : OutRegs)
  3056. MIB.addReg(Reg, RegState::Implicit);
  3057. // Issue CALLSEQ_END
  3058. unsigned NumBytesForCalleeToPop =
  3059. X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
  3060. TM.Options.GuaranteedTailCallOpt)
  3061. ? NumBytes // Callee pops everything.
  3062. : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CB);
  3063. unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
  3064. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(AdjStackUp))
  3065. .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
  3066. // Now handle call return values.
  3067. SmallVector<CCValAssign, 16> RVLocs;
  3068. CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
  3069. CLI.RetTy->getContext());
  3070. CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
  3071. // Copy all of the result registers out of their specified physreg.
  3072. Register ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
  3073. for (unsigned i = 0; i != RVLocs.size(); ++i) {
  3074. CCValAssign &VA = RVLocs[i];
  3075. EVT CopyVT = VA.getValVT();
  3076. unsigned CopyReg = ResultReg + i;
  3077. Register SrcReg = VA.getLocReg();
  3078. // If this is x86-64, and we disabled SSE, we can't return FP values
  3079. if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
  3080. ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
  3081. report_fatal_error("SSE register return with SSE disabled");
  3082. }
  3083. // If we prefer to use the value in xmm registers, copy it out as f80 and
  3084. // use a truncate to move it from fp stack reg to xmm reg.
  3085. if ((SrcReg == X86::FP0 || SrcReg == X86::FP1) &&
  3086. isScalarFPTypeInSSEReg(VA.getValVT())) {
  3087. CopyVT = MVT::f80;
  3088. CopyReg = createResultReg(&X86::RFP80RegClass);
  3089. }
  3090. // Copy out the result.
  3091. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  3092. TII.get(TargetOpcode::COPY), CopyReg).addReg(SrcReg);
  3093. InRegs.push_back(VA.getLocReg());
  3094. // Round the f80 to the right size, which also moves it to the appropriate
  3095. // xmm register. This is accomplished by storing the f80 value in memory
  3096. // and then loading it back.
  3097. if (CopyVT != VA.getValVT()) {
  3098. EVT ResVT = VA.getValVT();
  3099. unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
  3100. unsigned MemSize = ResVT.getSizeInBits()/8;
  3101. int FI = MFI.CreateStackObject(MemSize, Align(MemSize), false);
  3102. addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  3103. TII.get(Opc)), FI)
  3104. .addReg(CopyReg);
  3105. Opc = ResVT == MVT::f32 ? X86::MOVSSrm_alt : X86::MOVSDrm_alt;
  3106. addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  3107. TII.get(Opc), ResultReg + i), FI);
  3108. }
  3109. }
  3110. CLI.ResultReg = ResultReg;
  3111. CLI.NumResultRegs = RVLocs.size();
  3112. CLI.Call = MIB;
  3113. return true;
  3114. }
  3115. bool
  3116. X86FastISel::fastSelectInstruction(const Instruction *I) {
  3117. switch (I->getOpcode()) {
  3118. default: break;
  3119. case Instruction::Load:
  3120. return X86SelectLoad(I);
  3121. case Instruction::Store:
  3122. return X86SelectStore(I);
  3123. case Instruction::Ret:
  3124. return X86SelectRet(I);
  3125. case Instruction::ICmp:
  3126. case Instruction::FCmp:
  3127. return X86SelectCmp(I);
  3128. case Instruction::ZExt:
  3129. return X86SelectZExt(I);
  3130. case Instruction::SExt:
  3131. return X86SelectSExt(I);
  3132. case Instruction::Br:
  3133. return X86SelectBranch(I);
  3134. case Instruction::LShr:
  3135. case Instruction::AShr:
  3136. case Instruction::Shl:
  3137. return X86SelectShift(I);
  3138. case Instruction::SDiv:
  3139. case Instruction::UDiv:
  3140. case Instruction::SRem:
  3141. case Instruction::URem:
  3142. return X86SelectDivRem(I);
  3143. case Instruction::Select:
  3144. return X86SelectSelect(I);
  3145. case Instruction::Trunc:
  3146. return X86SelectTrunc(I);
  3147. case Instruction::FPExt:
  3148. return X86SelectFPExt(I);
  3149. case Instruction::FPTrunc:
  3150. return X86SelectFPTrunc(I);
  3151. case Instruction::SIToFP:
  3152. return X86SelectSIToFP(I);
  3153. case Instruction::UIToFP:
  3154. return X86SelectUIToFP(I);
  3155. case Instruction::IntToPtr: // Deliberate fall-through.
  3156. case Instruction::PtrToInt: {
  3157. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  3158. EVT DstVT = TLI.getValueType(DL, I->getType());
  3159. if (DstVT.bitsGT(SrcVT))
  3160. return X86SelectZExt(I);
  3161. if (DstVT.bitsLT(SrcVT))
  3162. return X86SelectTrunc(I);
  3163. Register Reg = getRegForValue(I->getOperand(0));
  3164. if (Reg == 0) return false;
  3165. updateValueMap(I, Reg);
  3166. return true;
  3167. }
  3168. case Instruction::BitCast: {
  3169. // Select SSE2/AVX bitcasts between 128/256/512 bit vector types.
  3170. if (!Subtarget->hasSSE2())
  3171. return false;
  3172. MVT SrcVT, DstVT;
  3173. if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT) ||
  3174. !isTypeLegal(I->getType(), DstVT))
  3175. return false;
  3176. // Only allow vectors that use xmm/ymm/zmm.
  3177. if (!SrcVT.isVector() || !DstVT.isVector() ||
  3178. SrcVT.getVectorElementType() == MVT::i1 ||
  3179. DstVT.getVectorElementType() == MVT::i1)
  3180. return false;
  3181. Register Reg = getRegForValue(I->getOperand(0));
  3182. if (!Reg)
  3183. return false;
  3184. // Emit a reg-reg copy so we don't propagate cached known bits information
  3185. // with the wrong VT if we fall out of fast isel after selecting this.
  3186. const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
  3187. Register ResultReg = createResultReg(DstClass);
  3188. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  3189. TII.get(TargetOpcode::COPY), ResultReg).addReg(Reg);
  3190. updateValueMap(I, ResultReg);
  3191. return true;
  3192. }
  3193. }
  3194. return false;
  3195. }
  3196. unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
  3197. if (VT > MVT::i64)
  3198. return 0;
  3199. uint64_t Imm = CI->getZExtValue();
  3200. if (Imm == 0) {
  3201. Register SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
  3202. switch (VT.SimpleTy) {
  3203. default: llvm_unreachable("Unexpected value type");
  3204. case MVT::i1:
  3205. case MVT::i8:
  3206. return fastEmitInst_extractsubreg(MVT::i8, SrcReg, X86::sub_8bit);
  3207. case MVT::i16:
  3208. return fastEmitInst_extractsubreg(MVT::i16, SrcReg, X86::sub_16bit);
  3209. case MVT::i32:
  3210. return SrcReg;
  3211. case MVT::i64: {
  3212. Register ResultReg = createResultReg(&X86::GR64RegClass);
  3213. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  3214. TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
  3215. .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
  3216. return ResultReg;
  3217. }
  3218. }
  3219. }
  3220. unsigned Opc = 0;
  3221. switch (VT.SimpleTy) {
  3222. default: llvm_unreachable("Unexpected value type");
  3223. case MVT::i1:
  3224. VT = MVT::i8;
  3225. [[fallthrough]];
  3226. case MVT::i8: Opc = X86::MOV8ri; break;
  3227. case MVT::i16: Opc = X86::MOV16ri; break;
  3228. case MVT::i32: Opc = X86::MOV32ri; break;
  3229. case MVT::i64: {
  3230. if (isUInt<32>(Imm))
  3231. Opc = X86::MOV32ri64;
  3232. else if (isInt<32>(Imm))
  3233. Opc = X86::MOV64ri32;
  3234. else
  3235. Opc = X86::MOV64ri;
  3236. break;
  3237. }
  3238. }
  3239. return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
  3240. }
  3241. unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
  3242. if (CFP->isNullValue())
  3243. return fastMaterializeFloatZero(CFP);
  3244. // Can't handle alternate code models yet.
  3245. CodeModel::Model CM = TM.getCodeModel();
  3246. if (CM != CodeModel::Small && CM != CodeModel::Large)
  3247. return 0;
  3248. // Get opcode and regclass of the output for the given load instruction.
  3249. unsigned Opc = 0;
  3250. bool HasSSE1 = Subtarget->hasSSE1();
  3251. bool HasSSE2 = Subtarget->hasSSE2();
  3252. bool HasAVX = Subtarget->hasAVX();
  3253. bool HasAVX512 = Subtarget->hasAVX512();
  3254. switch (VT.SimpleTy) {
  3255. default: return 0;
  3256. case MVT::f32:
  3257. Opc = HasAVX512 ? X86::VMOVSSZrm_alt
  3258. : HasAVX ? X86::VMOVSSrm_alt
  3259. : HasSSE1 ? X86::MOVSSrm_alt
  3260. : X86::LD_Fp32m;
  3261. break;
  3262. case MVT::f64:
  3263. Opc = HasAVX512 ? X86::VMOVSDZrm_alt
  3264. : HasAVX ? X86::VMOVSDrm_alt
  3265. : HasSSE2 ? X86::MOVSDrm_alt
  3266. : X86::LD_Fp64m;
  3267. break;
  3268. case MVT::f80:
  3269. // No f80 support yet.
  3270. return 0;
  3271. }
  3272. // MachineConstantPool wants an explicit alignment.
  3273. Align Alignment = DL.getPrefTypeAlign(CFP->getType());
  3274. // x86-32 PIC requires a PIC base register for constant pools.
  3275. unsigned PICBase = 0;
  3276. unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
  3277. if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
  3278. PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
  3279. else if (OpFlag == X86II::MO_GOTOFF)
  3280. PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
  3281. else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
  3282. PICBase = X86::RIP;
  3283. // Create the load from the constant pool.
  3284. unsigned CPI = MCP.getConstantPoolIndex(CFP, Alignment);
  3285. Register ResultReg = createResultReg(TLI.getRegClassFor(VT.SimpleTy));
  3286. // Large code model only applies to 64-bit mode.
  3287. if (Subtarget->is64Bit() && CM == CodeModel::Large) {
  3288. Register AddrReg = createResultReg(&X86::GR64RegClass);
  3289. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV64ri),
  3290. AddrReg)
  3291. .addConstantPoolIndex(CPI, 0, OpFlag);
  3292. MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  3293. TII.get(Opc), ResultReg);
  3294. addRegReg(MIB, AddrReg, false, PICBase, false);
  3295. MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
  3296. MachinePointerInfo::getConstantPool(*FuncInfo.MF),
  3297. MachineMemOperand::MOLoad, DL.getPointerSize(), Alignment);
  3298. MIB->addMemOperand(*FuncInfo.MF, MMO);
  3299. return ResultReg;
  3300. }
  3301. addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  3302. TII.get(Opc), ResultReg),
  3303. CPI, PICBase, OpFlag);
  3304. return ResultReg;
  3305. }
  3306. unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
  3307. // Can't handle alternate code models yet.
  3308. if (TM.getCodeModel() != CodeModel::Small)
  3309. return 0;
  3310. // Materialize addresses with LEA/MOV instructions.
  3311. X86AddressMode AM;
  3312. if (X86SelectAddress(GV, AM)) {
  3313. // If the expression is just a basereg, then we're done, otherwise we need
  3314. // to emit an LEA.
  3315. if (AM.BaseType == X86AddressMode::RegBase &&
  3316. AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
  3317. return AM.Base.Reg;
  3318. Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
  3319. if (TM.getRelocationModel() == Reloc::Static &&
  3320. TLI.getPointerTy(DL) == MVT::i64) {
  3321. // The displacement code could be more than 32 bits away so we need to use
  3322. // an instruction with a 64 bit immediate
  3323. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV64ri),
  3324. ResultReg)
  3325. .addGlobalAddress(GV);
  3326. } else {
  3327. unsigned Opc =
  3328. TLI.getPointerTy(DL) == MVT::i32
  3329. ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
  3330. : X86::LEA64r;
  3331. addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  3332. TII.get(Opc), ResultReg), AM);
  3333. }
  3334. return ResultReg;
  3335. }
  3336. return 0;
  3337. }
  3338. unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
  3339. EVT CEVT = TLI.getValueType(DL, C->getType(), true);
  3340. // Only handle simple types.
  3341. if (!CEVT.isSimple())
  3342. return 0;
  3343. MVT VT = CEVT.getSimpleVT();
  3344. if (const auto *CI = dyn_cast<ConstantInt>(C))
  3345. return X86MaterializeInt(CI, VT);
  3346. if (const auto *CFP = dyn_cast<ConstantFP>(C))
  3347. return X86MaterializeFP(CFP, VT);
  3348. if (const auto *GV = dyn_cast<GlobalValue>(C))
  3349. return X86MaterializeGV(GV, VT);
  3350. if (isa<UndefValue>(C)) {
  3351. unsigned Opc = 0;
  3352. switch (VT.SimpleTy) {
  3353. default:
  3354. break;
  3355. case MVT::f32:
  3356. if (!Subtarget->hasSSE1())
  3357. Opc = X86::LD_Fp032;
  3358. break;
  3359. case MVT::f64:
  3360. if (!Subtarget->hasSSE2())
  3361. Opc = X86::LD_Fp064;
  3362. break;
  3363. case MVT::f80:
  3364. Opc = X86::LD_Fp080;
  3365. break;
  3366. }
  3367. if (Opc) {
  3368. Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
  3369. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc),
  3370. ResultReg);
  3371. return ResultReg;
  3372. }
  3373. }
  3374. return 0;
  3375. }
  3376. unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
  3377. // Fail on dynamic allocas. At this point, getRegForValue has already
  3378. // checked its CSE maps, so if we're here trying to handle a dynamic
  3379. // alloca, we're not going to succeed. X86SelectAddress has a
  3380. // check for dynamic allocas, because it's called directly from
  3381. // various places, but targetMaterializeAlloca also needs a check
  3382. // in order to avoid recursion between getRegForValue,
  3383. // X86SelectAddrss, and targetMaterializeAlloca.
  3384. if (!FuncInfo.StaticAllocaMap.count(C))
  3385. return 0;
  3386. assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
  3387. X86AddressMode AM;
  3388. if (!X86SelectAddress(C, AM))
  3389. return 0;
  3390. unsigned Opc =
  3391. TLI.getPointerTy(DL) == MVT::i32
  3392. ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
  3393. : X86::LEA64r;
  3394. const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
  3395. Register ResultReg = createResultReg(RC);
  3396. addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
  3397. TII.get(Opc), ResultReg), AM);
  3398. return ResultReg;
  3399. }
  3400. unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
  3401. MVT VT;
  3402. if (!isTypeLegal(CF->getType(), VT))
  3403. return 0;
  3404. // Get opcode and regclass for the given zero.
  3405. bool HasSSE1 = Subtarget->hasSSE1();
  3406. bool HasSSE2 = Subtarget->hasSSE2();
  3407. bool HasAVX512 = Subtarget->hasAVX512();
  3408. unsigned Opc = 0;
  3409. switch (VT.SimpleTy) {
  3410. default: return 0;
  3411. case MVT::f16:
  3412. Opc = HasAVX512 ? X86::AVX512_FsFLD0SH : X86::FsFLD0SH;
  3413. break;
  3414. case MVT::f32:
  3415. Opc = HasAVX512 ? X86::AVX512_FsFLD0SS
  3416. : HasSSE1 ? X86::FsFLD0SS
  3417. : X86::LD_Fp032;
  3418. break;
  3419. case MVT::f64:
  3420. Opc = HasAVX512 ? X86::AVX512_FsFLD0SD
  3421. : HasSSE2 ? X86::FsFLD0SD
  3422. : X86::LD_Fp064;
  3423. break;
  3424. case MVT::f80:
  3425. // No f80 support yet.
  3426. return 0;
  3427. }
  3428. Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
  3429. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), ResultReg);
  3430. return ResultReg;
  3431. }
  3432. bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
  3433. const LoadInst *LI) {
  3434. const Value *Ptr = LI->getPointerOperand();
  3435. X86AddressMode AM;
  3436. if (!X86SelectAddress(Ptr, AM))
  3437. return false;
  3438. const X86InstrInfo &XII = (const X86InstrInfo &)TII;
  3439. unsigned Size = DL.getTypeAllocSize(LI->getType());
  3440. SmallVector<MachineOperand, 8> AddrOps;
  3441. AM.getFullAddress(AddrOps);
  3442. MachineInstr *Result = XII.foldMemoryOperandImpl(
  3443. *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, LI->getAlign(),
  3444. /*AllowCommute=*/true);
  3445. if (!Result)
  3446. return false;
  3447. // The index register could be in the wrong register class. Unfortunately,
  3448. // foldMemoryOperandImpl could have commuted the instruction so its not enough
  3449. // to just look at OpNo + the offset to the index reg. We actually need to
  3450. // scan the instruction to find the index reg and see if its the correct reg
  3451. // class.
  3452. unsigned OperandNo = 0;
  3453. for (MachineInstr::mop_iterator I = Result->operands_begin(),
  3454. E = Result->operands_end(); I != E; ++I, ++OperandNo) {
  3455. MachineOperand &MO = *I;
  3456. if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
  3457. continue;
  3458. // Found the index reg, now try to rewrite it.
  3459. Register IndexReg = constrainOperandRegClass(Result->getDesc(),
  3460. MO.getReg(), OperandNo);
  3461. if (IndexReg == MO.getReg())
  3462. continue;
  3463. MO.setReg(IndexReg);
  3464. }
  3465. Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
  3466. Result->cloneInstrSymbols(*FuncInfo.MF, *MI);
  3467. MachineBasicBlock::iterator I(MI);
  3468. removeDeadCode(I, std::next(I));
  3469. return true;
  3470. }
  3471. unsigned X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode,
  3472. const TargetRegisterClass *RC,
  3473. unsigned Op0, unsigned Op1,
  3474. unsigned Op2, unsigned Op3) {
  3475. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  3476. Register ResultReg = createResultReg(RC);
  3477. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  3478. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  3479. Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
  3480. Op3 = constrainOperandRegClass(II, Op3, II.getNumDefs() + 3);
  3481. if (II.getNumDefs() >= 1)
  3482. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
  3483. .addReg(Op0)
  3484. .addReg(Op1)
  3485. .addReg(Op2)
  3486. .addReg(Op3);
  3487. else {
  3488. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
  3489. .addReg(Op0)
  3490. .addReg(Op1)
  3491. .addReg(Op2)
  3492. .addReg(Op3);
  3493. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
  3494. ResultReg)
  3495. .addReg(II.implicit_defs()[0]);
  3496. }
  3497. return ResultReg;
  3498. }
  3499. namespace llvm {
  3500. FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
  3501. const TargetLibraryInfo *libInfo) {
  3502. return new X86FastISel(funcInfo, libInfo);
  3503. }
  3504. }