TargetLowering.h 226 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file describes how to lower LLVM code to machine code. This has two
  16. /// main components:
  17. ///
  18. /// 1. Which ValueTypes are natively supported by the target.
  19. /// 2. Which operations are supported for supported ValueTypes.
  20. /// 3. Cost thresholds for alternative implementations of certain operations.
  21. ///
  22. /// In addition it has a few other components, like information about FP
  23. /// immediates.
  24. ///
  25. //===----------------------------------------------------------------------===//
  26. #ifndef LLVM_CODEGEN_TARGETLOWERING_H
  27. #define LLVM_CODEGEN_TARGETLOWERING_H
  28. #include "llvm/ADT/APInt.h"
  29. #include "llvm/ADT/ArrayRef.h"
  30. #include "llvm/ADT/DenseMap.h"
  31. #include "llvm/ADT/SmallVector.h"
  32. #include "llvm/ADT/StringRef.h"
  33. #include "llvm/CodeGen/ComplexDeinterleavingPass.h"
  34. #include "llvm/CodeGen/DAGCombine.h"
  35. #include "llvm/CodeGen/ISDOpcodes.h"
  36. #include "llvm/CodeGen/LowLevelType.h"
  37. #include "llvm/CodeGen/RuntimeLibcalls.h"
  38. #include "llvm/CodeGen/SelectionDAG.h"
  39. #include "llvm/CodeGen/SelectionDAGNodes.h"
  40. #include "llvm/CodeGen/TargetCallingConv.h"
  41. #include "llvm/CodeGen/ValueTypes.h"
  42. #include "llvm/IR/Attributes.h"
  43. #include "llvm/IR/CallingConv.h"
  44. #include "llvm/IR/DataLayout.h"
  45. #include "llvm/IR/DerivedTypes.h"
  46. #include "llvm/IR/Function.h"
  47. #include "llvm/IR/InlineAsm.h"
  48. #include "llvm/IR/Instruction.h"
  49. #include "llvm/IR/Instructions.h"
  50. #include "llvm/IR/Type.h"
  51. #include "llvm/Support/Alignment.h"
  52. #include "llvm/Support/AtomicOrdering.h"
  53. #include "llvm/Support/Casting.h"
  54. #include "llvm/Support/ErrorHandling.h"
  55. #include "llvm/Support/MachineValueType.h"
  56. #include <algorithm>
  57. #include <cassert>
  58. #include <climits>
  59. #include <cstdint>
  60. #include <iterator>
  61. #include <map>
  62. #include <string>
  63. #include <utility>
  64. #include <vector>
  65. namespace llvm {
  66. class AssumptionCache;
  67. class CCState;
  68. class CCValAssign;
  69. class Constant;
  70. class FastISel;
  71. class FunctionLoweringInfo;
  72. class GlobalValue;
  73. class Loop;
  74. class GISelKnownBits;
  75. class IntrinsicInst;
  76. class IRBuilderBase;
  77. struct KnownBits;
  78. class LegacyDivergenceAnalysis;
  79. class LLVMContext;
  80. class MachineBasicBlock;
  81. class MachineFunction;
  82. class MachineInstr;
  83. class MachineJumpTableInfo;
  84. class MachineLoop;
  85. class MachineRegisterInfo;
  86. class MCContext;
  87. class MCExpr;
  88. class Module;
  89. class ProfileSummaryInfo;
  90. class TargetLibraryInfo;
  91. class TargetMachine;
  92. class TargetRegisterClass;
  93. class TargetRegisterInfo;
  94. class TargetTransformInfo;
  95. class Value;
  96. namespace Sched {
  97. enum Preference {
  98. None, // No preference
  99. Source, // Follow source order.
  100. RegPressure, // Scheduling for lowest register pressure.
  101. Hybrid, // Scheduling for both latency and register pressure.
  102. ILP, // Scheduling for ILP in low register pressure mode.
  103. VLIW, // Scheduling for VLIW targets.
  104. Fast, // Fast suboptimal list scheduling
  105. Linearize // Linearize DAG, no scheduling
  106. };
  107. } // end namespace Sched
  108. // MemOp models a memory operation, either memset or memcpy/memmove.
  109. struct MemOp {
  110. private:
  111. // Shared
  112. uint64_t Size;
  113. bool DstAlignCanChange; // true if destination alignment can satisfy any
  114. // constraint.
  115. Align DstAlign; // Specified alignment of the memory operation.
  116. bool AllowOverlap;
  117. // memset only
  118. bool IsMemset; // If setthis memory operation is a memset.
  119. bool ZeroMemset; // If set clears out memory with zeros.
  120. // memcpy only
  121. bool MemcpyStrSrc; // Indicates whether the memcpy source is an in-register
  122. // constant so it does not need to be loaded.
  123. Align SrcAlign; // Inferred alignment of the source or default value if the
  124. // memory operation does not need to load the value.
  125. public:
  126. static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
  127. Align SrcAlign, bool IsVolatile,
  128. bool MemcpyStrSrc = false) {
  129. MemOp Op;
  130. Op.Size = Size;
  131. Op.DstAlignCanChange = DstAlignCanChange;
  132. Op.DstAlign = DstAlign;
  133. Op.AllowOverlap = !IsVolatile;
  134. Op.IsMemset = false;
  135. Op.ZeroMemset = false;
  136. Op.MemcpyStrSrc = MemcpyStrSrc;
  137. Op.SrcAlign = SrcAlign;
  138. return Op;
  139. }
  140. static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
  141. bool IsZeroMemset, bool IsVolatile) {
  142. MemOp Op;
  143. Op.Size = Size;
  144. Op.DstAlignCanChange = DstAlignCanChange;
  145. Op.DstAlign = DstAlign;
  146. Op.AllowOverlap = !IsVolatile;
  147. Op.IsMemset = true;
  148. Op.ZeroMemset = IsZeroMemset;
  149. Op.MemcpyStrSrc = false;
  150. return Op;
  151. }
  152. uint64_t size() const { return Size; }
  153. Align getDstAlign() const {
  154. assert(!DstAlignCanChange);
  155. return DstAlign;
  156. }
  157. bool isFixedDstAlign() const { return !DstAlignCanChange; }
  158. bool allowOverlap() const { return AllowOverlap; }
  159. bool isMemset() const { return IsMemset; }
  160. bool isMemcpy() const { return !IsMemset; }
  161. bool isMemcpyWithFixedDstAlign() const {
  162. return isMemcpy() && !DstAlignCanChange;
  163. }
  164. bool isZeroMemset() const { return isMemset() && ZeroMemset; }
  165. bool isMemcpyStrSrc() const {
  166. assert(isMemcpy() && "Must be a memcpy");
  167. return MemcpyStrSrc;
  168. }
  169. Align getSrcAlign() const {
  170. assert(isMemcpy() && "Must be a memcpy");
  171. return SrcAlign;
  172. }
  173. bool isSrcAligned(Align AlignCheck) const {
  174. return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
  175. }
  176. bool isDstAligned(Align AlignCheck) const {
  177. return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
  178. }
  179. bool isAligned(Align AlignCheck) const {
  180. return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
  181. }
  182. };
  183. /// This base class for TargetLowering contains the SelectionDAG-independent
  184. /// parts that can be used from the rest of CodeGen.
  185. class TargetLoweringBase {
  186. public:
  187. /// This enum indicates whether operations are valid for a target, and if not,
  188. /// what action should be used to make them valid.
  189. enum LegalizeAction : uint8_t {
  190. Legal, // The target natively supports this operation.
  191. Promote, // This operation should be executed in a larger type.
  192. Expand, // Try to expand this to other ops, otherwise use a libcall.
  193. LibCall, // Don't try to expand this to other ops, always use a libcall.
  194. Custom // Use the LowerOperation hook to implement custom lowering.
  195. };
  196. /// This enum indicates whether a types are legal for a target, and if not,
  197. /// what action should be used to make them valid.
  198. enum LegalizeTypeAction : uint8_t {
  199. TypeLegal, // The target natively supports this type.
  200. TypePromoteInteger, // Replace this integer with a larger one.
  201. TypeExpandInteger, // Split this integer into two of half the size.
  202. TypeSoftenFloat, // Convert this float to a same size integer type.
  203. TypeExpandFloat, // Split this float into two of half the size.
  204. TypeScalarizeVector, // Replace this one-element vector with its element.
  205. TypeSplitVector, // Split this vector into two of half the size.
  206. TypeWidenVector, // This vector should be widened into a larger vector.
  207. TypePromoteFloat, // Replace this float with a larger one.
  208. TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
  209. TypeScalarizeScalableVector, // This action is explicitly left unimplemented.
  210. // While it is theoretically possible to
  211. // legalize operations on scalable types with a
  212. // loop that handles the vscale * #lanes of the
  213. // vector, this is non-trivial at SelectionDAG
  214. // level and these types are better to be
  215. // widened or promoted.
  216. };
  217. /// LegalizeKind holds the legalization kind that needs to happen to EVT
  218. /// in order to type-legalize it.
  219. using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
  220. /// Enum that describes how the target represents true/false values.
  221. enum BooleanContent {
  222. UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
  223. ZeroOrOneBooleanContent, // All bits zero except for bit 0.
  224. ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
  225. };
  226. /// Enum that describes what type of support for selects the target has.
  227. enum SelectSupportKind {
  228. ScalarValSelect, // The target supports scalar selects (ex: cmov).
  229. ScalarCondVectorVal, // The target supports selects with a scalar condition
  230. // and vector values (ex: cmov).
  231. VectorMaskSelect // The target supports vector selects with a vector
  232. // mask (ex: x86 blends).
  233. };
  234. /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
  235. /// to, if at all. Exists because different targets have different levels of
  236. /// support for these atomic instructions, and also have different options
  237. /// w.r.t. what they should expand to.
  238. enum class AtomicExpansionKind {
  239. None, // Don't expand the instruction.
  240. CastToInteger, // Cast the atomic instruction to another type, e.g. from
  241. // floating-point to integer type.
  242. LLSC, // Expand the instruction into loadlinked/storeconditional; used
  243. // by ARM/AArch64.
  244. LLOnly, // Expand the (load) instruction into just a load-linked, which has
  245. // greater atomic guarantees than a normal load.
  246. CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
  247. MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
  248. BitTestIntrinsic, // Use a target-specific intrinsic for special bit
  249. // operations; used by X86.
  250. CmpArithIntrinsic,// Use a target-specific intrinsic for special compare
  251. // operations; used by X86.
  252. Expand, // Generic expansion in terms of other atomic operations.
  253. // Rewrite to a non-atomic form for use in a known non-preemptible
  254. // environment.
  255. NotAtomic
  256. };
  257. /// Enum that specifies when a multiplication should be expanded.
  258. enum class MulExpansionKind {
  259. Always, // Always expand the instruction.
  260. OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
  261. // or custom.
  262. };
  263. /// Enum that specifies when a float negation is beneficial.
  264. enum class NegatibleCost {
  265. Cheaper = 0, // Negated expression is cheaper.
  266. Neutral = 1, // Negated expression has the same cost.
  267. Expensive = 2 // Negated expression is more expensive.
  268. };
  269. class ArgListEntry {
  270. public:
  271. Value *Val = nullptr;
  272. SDValue Node = SDValue();
  273. Type *Ty = nullptr;
  274. bool IsSExt : 1;
  275. bool IsZExt : 1;
  276. bool IsInReg : 1;
  277. bool IsSRet : 1;
  278. bool IsNest : 1;
  279. bool IsByVal : 1;
  280. bool IsByRef : 1;
  281. bool IsInAlloca : 1;
  282. bool IsPreallocated : 1;
  283. bool IsReturned : 1;
  284. bool IsSwiftSelf : 1;
  285. bool IsSwiftAsync : 1;
  286. bool IsSwiftError : 1;
  287. bool IsCFGuardTarget : 1;
  288. MaybeAlign Alignment = std::nullopt;
  289. Type *IndirectType = nullptr;
  290. ArgListEntry()
  291. : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
  292. IsNest(false), IsByVal(false), IsByRef(false), IsInAlloca(false),
  293. IsPreallocated(false), IsReturned(false), IsSwiftSelf(false),
  294. IsSwiftAsync(false), IsSwiftError(false), IsCFGuardTarget(false) {}
  295. void setAttributes(const CallBase *Call, unsigned ArgIdx);
  296. };
  297. using ArgListTy = std::vector<ArgListEntry>;
  298. virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
  299. ArgListTy &Args) const {};
  300. static ISD::NodeType getExtendForContent(BooleanContent Content) {
  301. switch (Content) {
  302. case UndefinedBooleanContent:
  303. // Extend by adding rubbish bits.
  304. return ISD::ANY_EXTEND;
  305. case ZeroOrOneBooleanContent:
  306. // Extend by adding zero bits.
  307. return ISD::ZERO_EXTEND;
  308. case ZeroOrNegativeOneBooleanContent:
  309. // Extend by copying the sign bit.
  310. return ISD::SIGN_EXTEND;
  311. }
  312. llvm_unreachable("Invalid content kind");
  313. }
  314. explicit TargetLoweringBase(const TargetMachine &TM);
  315. TargetLoweringBase(const TargetLoweringBase &) = delete;
  316. TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
  317. virtual ~TargetLoweringBase() = default;
  318. /// Return true if the target support strict float operation
  319. bool isStrictFPEnabled() const {
  320. return IsStrictFPEnabled;
  321. }
  322. protected:
  323. /// Initialize all of the actions to default values.
  324. void initActions();
  325. public:
  326. const TargetMachine &getTargetMachine() const { return TM; }
  327. virtual bool useSoftFloat() const { return false; }
  328. /// Return the pointer type for the given address space, defaults to
  329. /// the pointer type from the data layout.
  330. /// FIXME: The default needs to be removed once all the code is updated.
  331. virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
  332. return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  333. }
  334. /// Return the in-memory pointer type for the given address space, defaults to
  335. /// the pointer type from the data layout. FIXME: The default needs to be
  336. /// removed once all the code is updated.
  337. virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
  338. return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  339. }
  340. /// Return the type for frame index, which is determined by
  341. /// the alloca address space specified through the data layout.
  342. MVT getFrameIndexTy(const DataLayout &DL) const {
  343. return getPointerTy(DL, DL.getAllocaAddrSpace());
  344. }
  345. /// Return the type for code pointers, which is determined by the program
  346. /// address space specified through the data layout.
  347. MVT getProgramPointerTy(const DataLayout &DL) const {
  348. return getPointerTy(DL, DL.getProgramAddressSpace());
  349. }
  350. /// Return the type for operands of fence.
  351. /// TODO: Let fence operands be of i32 type and remove this.
  352. virtual MVT getFenceOperandTy(const DataLayout &DL) const {
  353. return getPointerTy(DL);
  354. }
  355. /// Return the type to use for a scalar shift opcode, given the shifted amount
  356. /// type. Targets should return a legal type if the input type is legal.
  357. /// Targets can return a type that is too small if the input type is illegal.
  358. virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
  359. /// Returns the type for the shift amount of a shift opcode. For vectors,
  360. /// returns the input type. For scalars, behavior depends on \p LegalTypes. If
  361. /// \p LegalTypes is true, calls getScalarShiftAmountTy, otherwise uses
  362. /// pointer type. If getScalarShiftAmountTy or pointer type cannot represent
  363. /// all possible shift amounts, returns MVT::i32. In general, \p LegalTypes
  364. /// should be set to true for calls during type legalization and after type
  365. /// legalization has been completed.
  366. EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
  367. bool LegalTypes = true) const;
  368. /// Return the preferred type to use for a shift opcode, given the shifted
  369. /// amount type is \p ShiftValueTy.
  370. LLVM_READONLY
  371. virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
  372. return ShiftValueTy;
  373. }
  374. /// Returns the type to be used for the index operand of:
  375. /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
  376. /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
  377. virtual MVT getVectorIdxTy(const DataLayout &DL) const {
  378. return getPointerTy(DL);
  379. }
  380. /// Returns the type to be used for the EVL/AVL operand of VP nodes:
  381. /// ISD::VP_ADD, ISD::VP_SUB, etc. It must be a legal scalar integer type,
  382. /// and must be at least as large as i32. The EVL is implicitly zero-extended
  383. /// to any larger type.
  384. virtual MVT getVPExplicitVectorLengthTy() const { return MVT::i32; }
  385. /// This callback is used to inspect load/store instructions and add
  386. /// target-specific MachineMemOperand flags to them. The default
  387. /// implementation does nothing.
  388. virtual MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const {
  389. return MachineMemOperand::MONone;
  390. }
  391. MachineMemOperand::Flags
  392. getLoadMemOperandFlags(const LoadInst &LI, const DataLayout &DL,
  393. AssumptionCache *AC = nullptr,
  394. const TargetLibraryInfo *LibInfo = nullptr) const;
  395. MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI,
  396. const DataLayout &DL) const;
  397. MachineMemOperand::Flags getAtomicMemOperandFlags(const Instruction &AI,
  398. const DataLayout &DL) const;
  399. virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
  400. return true;
  401. }
  402. /// Return true if the @llvm.get.active.lane.mask intrinsic should be expanded
  403. /// using generic code in SelectionDAGBuilder.
  404. virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const {
  405. return true;
  406. }
  407. /// Return true if it is profitable to convert a select of FP constants into
  408. /// a constant pool load whose address depends on the select condition. The
  409. /// parameter may be used to differentiate a select with FP compare from
  410. /// integer compare.
  411. virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
  412. return true;
  413. }
  414. /// Return true if multiple condition registers are available.
  415. bool hasMultipleConditionRegisters() const {
  416. return HasMultipleConditionRegisters;
  417. }
  418. /// Return true if the target has BitExtract instructions.
  419. bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
  420. /// Return the preferred vector type legalization action.
  421. virtual TargetLoweringBase::LegalizeTypeAction
  422. getPreferredVectorAction(MVT VT) const {
  423. // The default action for one element vectors is to scalarize
  424. if (VT.getVectorElementCount().isScalar())
  425. return TypeScalarizeVector;
  426. // The default action for an odd-width vector is to widen.
  427. if (!VT.isPow2VectorType())
  428. return TypeWidenVector;
  429. // The default action for other vectors is to promote
  430. return TypePromoteInteger;
  431. }
  432. // Return true if the half type should be passed around as i16, but promoted
  433. // to float around arithmetic. The default behavior is to pass around as
  434. // float and convert around loads/stores/bitcasts and other places where
  435. // the size matters.
  436. virtual bool softPromoteHalfType() const { return false; }
  437. // There are two general methods for expanding a BUILD_VECTOR node:
  438. // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
  439. // them together.
  440. // 2. Build the vector on the stack and then load it.
  441. // If this function returns true, then method (1) will be used, subject to
  442. // the constraint that all of the necessary shuffles are legal (as determined
  443. // by isShuffleMaskLegal). If this function returns false, then method (2) is
  444. // always used. The vector type, and the number of defined values, are
  445. // provided.
  446. virtual bool
  447. shouldExpandBuildVectorWithShuffles(EVT /* VT */,
  448. unsigned DefinedValues) const {
  449. return DefinedValues < 3;
  450. }
  451. /// Return true if integer divide is usually cheaper than a sequence of
  452. /// several shifts, adds, and multiplies for this target.
  453. /// The definition of "cheaper" may depend on whether we're optimizing
  454. /// for speed or for size.
  455. virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
  456. /// Return true if the target can handle a standalone remainder operation.
  457. virtual bool hasStandaloneRem(EVT VT) const {
  458. return true;
  459. }
  460. /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
  461. virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
  462. // Default behavior is to replace SQRT(X) with X*RSQRT(X).
  463. return false;
  464. }
  465. /// Reciprocal estimate status values used by the functions below.
  466. enum ReciprocalEstimate : int {
  467. Unspecified = -1,
  468. Disabled = 0,
  469. Enabled = 1
  470. };
  471. /// Return a ReciprocalEstimate enum value for a square root of the given type
  472. /// based on the function's attributes. If the operation is not overridden by
  473. /// the function's attributes, "Unspecified" is returned and target defaults
  474. /// are expected to be used for instruction selection.
  475. int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
  476. /// Return a ReciprocalEstimate enum value for a division of the given type
  477. /// based on the function's attributes. If the operation is not overridden by
  478. /// the function's attributes, "Unspecified" is returned and target defaults
  479. /// are expected to be used for instruction selection.
  480. int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
  481. /// Return the refinement step count for a square root of the given type based
  482. /// on the function's attributes. If the operation is not overridden by
  483. /// the function's attributes, "Unspecified" is returned and target defaults
  484. /// are expected to be used for instruction selection.
  485. int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
  486. /// Return the refinement step count for a division of the given type based
  487. /// on the function's attributes. If the operation is not overridden by
  488. /// the function's attributes, "Unspecified" is returned and target defaults
  489. /// are expected to be used for instruction selection.
  490. int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
  491. /// Returns true if target has indicated at least one type should be bypassed.
  492. bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
  493. /// Returns map of slow types for division or remainder with corresponding
  494. /// fast types
  495. const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
  496. return BypassSlowDivWidths;
  497. }
  498. /// Return true only if vscale must be a power of two.
  499. virtual bool isVScaleKnownToBeAPowerOfTwo() const { return false; }
  500. /// Return true if Flow Control is an expensive operation that should be
  501. /// avoided.
  502. bool isJumpExpensive() const { return JumpIsExpensive; }
  503. /// Return true if selects are only cheaper than branches if the branch is
  504. /// unlikely to be predicted right.
  505. bool isPredictableSelectExpensive() const {
  506. return PredictableSelectIsExpensive;
  507. }
  508. virtual bool fallBackToDAGISel(const Instruction &Inst) const {
  509. return false;
  510. }
  511. /// Return true if the following transform is beneficial:
  512. /// fold (conv (load x)) -> (load (conv*)x)
  513. /// On architectures that don't natively support some vector loads
  514. /// efficiently, casting the load to a smaller vector of larger types and
  515. /// loading is more efficient, however, this can be undone by optimizations in
  516. /// dag combiner.
  517. virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
  518. const SelectionDAG &DAG,
  519. const MachineMemOperand &MMO) const;
  520. /// Return true if the following transform is beneficial:
  521. /// (store (y (conv x)), y*)) -> (store x, (x*))
  522. virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
  523. const SelectionDAG &DAG,
  524. const MachineMemOperand &MMO) const {
  525. // Default to the same logic as loads.
  526. return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
  527. }
  528. /// Return true if it is expected to be cheaper to do a store of a non-zero
  529. /// vector constant with the given size and type for the address space than to
  530. /// store the individual scalar element constants.
  531. virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
  532. unsigned NumElem,
  533. unsigned AddrSpace) const {
  534. return false;
  535. }
  536. /// Allow store merging for the specified type after legalization in addition
  537. /// to before legalization. This may transform stores that do not exist
  538. /// earlier (for example, stores created from intrinsics).
  539. virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
  540. return true;
  541. }
  542. /// Returns if it's reasonable to merge stores to MemVT size.
  543. virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
  544. const MachineFunction &MF) const {
  545. return true;
  546. }
  547. /// Return true if it is cheap to speculate a call to intrinsic cttz.
  548. virtual bool isCheapToSpeculateCttz(Type *Ty) const {
  549. return false;
  550. }
  551. /// Return true if it is cheap to speculate a call to intrinsic ctlz.
  552. virtual bool isCheapToSpeculateCtlz(Type *Ty) const {
  553. return false;
  554. }
  555. /// Return true if ctlz instruction is fast.
  556. virtual bool isCtlzFast() const {
  557. return false;
  558. }
  559. /// Return the maximum number of "x & (x - 1)" operations that can be done
  560. /// instead of deferring to a custom CTPOP.
  561. virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
  562. return 1;
  563. }
  564. /// Return true if instruction generated for equality comparison is folded
  565. /// with instruction generated for signed comparison.
  566. virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
  567. /// Return true if the heuristic to prefer icmp eq zero should be used in code
  568. /// gen prepare.
  569. virtual bool preferZeroCompareBranch() const { return false; }
  570. /// Return true if it is safe to transform an integer-domain bitwise operation
  571. /// into the equivalent floating-point operation. This should be set to true
  572. /// if the target has IEEE-754-compliant fabs/fneg operations for the input
  573. /// type.
  574. virtual bool hasBitPreservingFPLogic(EVT VT) const {
  575. return false;
  576. }
  577. /// Return true if it is cheaper to split the store of a merged int val
  578. /// from a pair of smaller values into multiple stores.
  579. virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
  580. return false;
  581. }
  582. /// Return if the target supports combining a
  583. /// chain like:
  584. /// \code
  585. /// %andResult = and %val1, #mask
  586. /// %icmpResult = icmp %andResult, 0
  587. /// \endcode
  588. /// into a single machine instruction of a form like:
  589. /// \code
  590. /// cc = test %register, #mask
  591. /// \endcode
  592. virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
  593. return false;
  594. }
  595. /// Use bitwise logic to make pairs of compares more efficient. For example:
  596. /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
  597. /// This should be true when it takes more than one instruction to lower
  598. /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
  599. /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
  600. virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
  601. return false;
  602. }
  603. /// Return the preferred operand type if the target has a quick way to compare
  604. /// integer values of the given size. Assume that any legal integer type can
  605. /// be compared efficiently. Targets may override this to allow illegal wide
  606. /// types to return a vector type if there is support to compare that type.
  607. virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
  608. MVT VT = MVT::getIntegerVT(NumBits);
  609. return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
  610. }
  611. /// Return true if the target should transform:
  612. /// (X & Y) == Y ---> (~X & Y) == 0
  613. /// (X & Y) != Y ---> (~X & Y) != 0
  614. ///
  615. /// This may be profitable if the target has a bitwise and-not operation that
  616. /// sets comparison flags. A target may want to limit the transformation based
  617. /// on the type of Y or if Y is a constant.
  618. ///
  619. /// Note that the transform will not occur if Y is known to be a power-of-2
  620. /// because a mask and compare of a single bit can be handled by inverting the
  621. /// predicate, for example:
  622. /// (X & 8) == 8 ---> (X & 8) != 0
  623. virtual bool hasAndNotCompare(SDValue Y) const {
  624. return false;
  625. }
  626. /// Return true if the target has a bitwise and-not operation:
  627. /// X = ~A & B
  628. /// This can be used to simplify select or other instructions.
  629. virtual bool hasAndNot(SDValue X) const {
  630. // If the target has the more complex version of this operation, assume that
  631. // it has this operation too.
  632. return hasAndNotCompare(X);
  633. }
  634. /// Return true if the target has a bit-test instruction:
  635. /// (X & (1 << Y)) ==/!= 0
  636. /// This knowledge can be used to prevent breaking the pattern,
  637. /// or creating it if it could be recognized.
  638. virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
  639. /// There are two ways to clear extreme bits (either low or high):
  640. /// Mask: x & (-1 << y) (the instcombine canonical form)
  641. /// Shifts: x >> y << y
  642. /// Return true if the variant with 2 variable shifts is preferred.
  643. /// Return false if there is no preference.
  644. virtual bool shouldFoldMaskToVariableShiftPair(SDValue X) const {
  645. // By default, let's assume that no one prefers shifts.
  646. return false;
  647. }
  648. /// Return true if it is profitable to fold a pair of shifts into a mask.
  649. /// This is usually true on most targets. But some targets, like Thumb1,
  650. /// have immediate shift instructions, but no immediate "and" instruction;
  651. /// this makes the fold unprofitable.
  652. virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N,
  653. CombineLevel Level) const {
  654. return true;
  655. }
  656. /// Should we tranform the IR-optimal check for whether given truncation
  657. /// down into KeptBits would be truncating or not:
  658. /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
  659. /// Into it's more traditional form:
  660. /// ((%x << C) a>> C) dstcond %x
  661. /// Return true if we should transform.
  662. /// Return false if there is no preference.
  663. virtual bool shouldTransformSignedTruncationCheck(EVT XVT,
  664. unsigned KeptBits) const {
  665. // By default, let's assume that no one prefers shifts.
  666. return false;
  667. }
  668. /// Given the pattern
  669. /// (X & (C l>>/<< Y)) ==/!= 0
  670. /// return true if it should be transformed into:
  671. /// ((X <</l>> Y) & C) ==/!= 0
  672. /// WARNING: if 'X' is a constant, the fold may deadlock!
  673. /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
  674. /// here because it can end up being not linked in.
  675. virtual bool shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
  676. SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
  677. unsigned OldShiftOpcode, unsigned NewShiftOpcode,
  678. SelectionDAG &DAG) const {
  679. if (hasBitTest(X, Y)) {
  680. // One interesting pattern that we'd want to form is 'bit test':
  681. // ((1 << Y) & C) ==/!= 0
  682. // But we also need to be careful not to try to reverse that fold.
  683. // Is this '1 << Y' ?
  684. if (OldShiftOpcode == ISD::SHL && CC->isOne())
  685. return false; // Keep the 'bit test' pattern.
  686. // Will it be '1 << Y' after the transform ?
  687. if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
  688. return true; // Do form the 'bit test' pattern.
  689. }
  690. // If 'X' is a constant, and we transform, then we will immediately
  691. // try to undo the fold, thus causing endless combine loop.
  692. // So by default, let's assume everyone prefers the fold
  693. // iff 'X' is not a constant.
  694. return !XC;
  695. }
  696. /// These two forms are equivalent:
  697. /// sub %y, (xor %x, -1)
  698. /// add (add %x, 1), %y
  699. /// The variant with two add's is IR-canonical.
  700. /// Some targets may prefer one to the other.
  701. virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
  702. // By default, let's assume that everyone prefers the form with two add's.
  703. return true;
  704. }
  705. // Return true if the target wants to transform Op(Splat(X)) -> Splat(Op(X))
  706. virtual bool preferScalarizeSplat(unsigned Opc) const { return true; }
  707. /// Return true if the target wants to use the optimization that
  708. /// turns ext(promotableInst1(...(promotableInstN(load)))) into
  709. /// promotedInst1(...(promotedInstN(ext(load)))).
  710. bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
  711. /// Return true if the target can combine store(extractelement VectorTy,
  712. /// Idx).
  713. /// \p Cost[out] gives the cost of that transformation when this is true.
  714. virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
  715. unsigned &Cost) const {
  716. return false;
  717. }
  718. /// Return true if inserting a scalar into a variable element of an undef
  719. /// vector is more efficiently handled by splatting the scalar instead.
  720. virtual bool shouldSplatInsEltVarIndex(EVT) const {
  721. return false;
  722. }
  723. /// Return true if target always benefits from combining into FMA for a
  724. /// given value type. This must typically return false on targets where FMA
  725. /// takes more cycles to execute than FADD.
  726. virtual bool enableAggressiveFMAFusion(EVT VT) const { return false; }
  727. /// Return true if target always benefits from combining into FMA for a
  728. /// given value type. This must typically return false on targets where FMA
  729. /// takes more cycles to execute than FADD.
  730. virtual bool enableAggressiveFMAFusion(LLT Ty) const { return false; }
  731. /// Return the ValueType of the result of SETCC operations.
  732. virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
  733. EVT VT) const;
  734. /// Return the ValueType for comparison libcalls. Comparison libcalls include
  735. /// floating point comparison calls, and Ordered/Unordered check calls on
  736. /// floating point numbers.
  737. virtual
  738. MVT::SimpleValueType getCmpLibcallReturnType() const;
  739. /// For targets without i1 registers, this gives the nature of the high-bits
  740. /// of boolean values held in types wider than i1.
  741. ///
  742. /// "Boolean values" are special true/false values produced by nodes like
  743. /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
  744. /// Not to be confused with general values promoted from i1. Some cpus
  745. /// distinguish between vectors of boolean and scalars; the isVec parameter
  746. /// selects between the two kinds. For example on X86 a scalar boolean should
  747. /// be zero extended from i1, while the elements of a vector of booleans
  748. /// should be sign extended from i1.
  749. ///
  750. /// Some cpus also treat floating point types the same way as they treat
  751. /// vectors instead of the way they treat scalars.
  752. BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
  753. if (isVec)
  754. return BooleanVectorContents;
  755. return isFloat ? BooleanFloatContents : BooleanContents;
  756. }
  757. BooleanContent getBooleanContents(EVT Type) const {
  758. return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
  759. }
  760. /// Promote the given target boolean to a target boolean of the given type.
  761. /// A target boolean is an integer value, not necessarily of type i1, the bits
  762. /// of which conform to getBooleanContents.
  763. ///
  764. /// ValVT is the type of values that produced the boolean.
  765. SDValue promoteTargetBoolean(SelectionDAG &DAG, SDValue Bool,
  766. EVT ValVT) const {
  767. SDLoc dl(Bool);
  768. EVT BoolVT =
  769. getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ValVT);
  770. ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(ValVT));
  771. return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
  772. }
  773. /// Return target scheduling preference.
  774. Sched::Preference getSchedulingPreference() const {
  775. return SchedPreferenceInfo;
  776. }
  777. /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
  778. /// for different nodes. This function returns the preference (or none) for
  779. /// the given node.
  780. virtual Sched::Preference getSchedulingPreference(SDNode *) const {
  781. return Sched::None;
  782. }
  783. /// Return the register class that should be used for the specified value
  784. /// type.
  785. virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
  786. (void)isDivergent;
  787. const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
  788. assert(RC && "This value type is not natively supported!");
  789. return RC;
  790. }
  791. /// Allows target to decide about the register class of the
  792. /// specific value that is live outside the defining block.
  793. /// Returns true if the value needs uniform register class.
  794. virtual bool requiresUniformRegister(MachineFunction &MF,
  795. const Value *) const {
  796. return false;
  797. }
  798. /// Return the 'representative' register class for the specified value
  799. /// type.
  800. ///
  801. /// The 'representative' register class is the largest legal super-reg
  802. /// register class for the register class of the value type. For example, on
  803. /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
  804. /// register class is GR64 on x86_64.
  805. virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
  806. const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
  807. return RC;
  808. }
  809. /// Return the cost of the 'representative' register class for the specified
  810. /// value type.
  811. virtual uint8_t getRepRegClassCostFor(MVT VT) const {
  812. return RepRegClassCostForVT[VT.SimpleTy];
  813. }
  814. /// Return the preferred strategy to legalize tihs SHIFT instruction, with
  815. /// \p ExpansionFactor being the recursion depth - how many expansion needed.
  816. enum class ShiftLegalizationStrategy {
  817. ExpandToParts,
  818. ExpandThroughStack,
  819. LowerToLibcall
  820. };
  821. virtual ShiftLegalizationStrategy
  822. preferredShiftLegalizationStrategy(SelectionDAG &DAG, SDNode *N,
  823. unsigned ExpansionFactor) const {
  824. if (ExpansionFactor == 1)
  825. return ShiftLegalizationStrategy::ExpandToParts;
  826. return ShiftLegalizationStrategy::ExpandThroughStack;
  827. }
  828. /// Return true if the target has native support for the specified value type.
  829. /// This means that it has a register that directly holds it without
  830. /// promotions or expansions.
  831. bool isTypeLegal(EVT VT) const {
  832. assert(!VT.isSimple() ||
  833. (unsigned)VT.getSimpleVT().SimpleTy < std::size(RegClassForVT));
  834. return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
  835. }
  836. class ValueTypeActionImpl {
  837. /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
  838. /// that indicates how instruction selection should deal with the type.
  839. LegalizeTypeAction ValueTypeActions[MVT::VALUETYPE_SIZE];
  840. public:
  841. ValueTypeActionImpl() {
  842. std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
  843. TypeLegal);
  844. }
  845. LegalizeTypeAction getTypeAction(MVT VT) const {
  846. return ValueTypeActions[VT.SimpleTy];
  847. }
  848. void setTypeAction(MVT VT, LegalizeTypeAction Action) {
  849. ValueTypeActions[VT.SimpleTy] = Action;
  850. }
  851. };
  852. const ValueTypeActionImpl &getValueTypeActions() const {
  853. return ValueTypeActions;
  854. }
  855. /// Return pair that represents the legalization kind (first) that needs to
  856. /// happen to EVT (second) in order to type-legalize it.
  857. ///
  858. /// First: how we should legalize values of this type, either it is already
  859. /// legal (return 'Legal') or we need to promote it to a larger type (return
  860. /// 'Promote'), or we need to expand it into multiple registers of smaller
  861. /// integer type (return 'Expand'). 'Custom' is not an option.
  862. ///
  863. /// Second: for types supported by the target, this is an identity function.
  864. /// For types that must be promoted to larger types, this returns the larger
  865. /// type to promote to. For integer types that are larger than the largest
  866. /// integer register, this contains one step in the expansion to get to the
  867. /// smaller register. For illegal floating point types, this returns the
  868. /// integer type to transform to.
  869. LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
  870. /// Return how we should legalize values of this type, either it is already
  871. /// legal (return 'Legal') or we need to promote it to a larger type (return
  872. /// 'Promote'), or we need to expand it into multiple registers of smaller
  873. /// integer type (return 'Expand'). 'Custom' is not an option.
  874. LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
  875. return getTypeConversion(Context, VT).first;
  876. }
  877. LegalizeTypeAction getTypeAction(MVT VT) const {
  878. return ValueTypeActions.getTypeAction(VT);
  879. }
  880. /// For types supported by the target, this is an identity function. For
  881. /// types that must be promoted to larger types, this returns the larger type
  882. /// to promote to. For integer types that are larger than the largest integer
  883. /// register, this contains one step in the expansion to get to the smaller
  884. /// register. For illegal floating point types, this returns the integer type
  885. /// to transform to.
  886. virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
  887. return getTypeConversion(Context, VT).second;
  888. }
  889. /// For types supported by the target, this is an identity function. For
  890. /// types that must be expanded (i.e. integer types that are larger than the
  891. /// largest integer register or illegal floating point types), this returns
  892. /// the largest legal type it will be expanded to.
  893. EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
  894. assert(!VT.isVector());
  895. while (true) {
  896. switch (getTypeAction(Context, VT)) {
  897. case TypeLegal:
  898. return VT;
  899. case TypeExpandInteger:
  900. VT = getTypeToTransformTo(Context, VT);
  901. break;
  902. default:
  903. llvm_unreachable("Type is not legal nor is it to be expanded!");
  904. }
  905. }
  906. }
  907. /// Vector types are broken down into some number of legal first class types.
  908. /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
  909. /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
  910. /// turns into 4 EVT::i32 values with both PPC and X86.
  911. ///
  912. /// This method returns the number of registers needed, and the VT for each
  913. /// register. It also returns the VT and quantity of the intermediate values
  914. /// before they are promoted/expanded.
  915. unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
  916. EVT &IntermediateVT,
  917. unsigned &NumIntermediates,
  918. MVT &RegisterVT) const;
  919. /// Certain targets such as MIPS require that some types such as vectors are
  920. /// always broken down into scalars in some contexts. This occurs even if the
  921. /// vector type is legal.
  922. virtual unsigned getVectorTypeBreakdownForCallingConv(
  923. LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
  924. unsigned &NumIntermediates, MVT &RegisterVT) const {
  925. return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
  926. RegisterVT);
  927. }
  928. struct IntrinsicInfo {
  929. unsigned opc = 0; // target opcode
  930. EVT memVT; // memory VT
  931. // value representing memory location
  932. PointerUnion<const Value *, const PseudoSourceValue *> ptrVal;
  933. // Fallback address space for use if ptrVal is nullptr. std::nullopt means
  934. // unknown address space.
  935. std::optional<unsigned> fallbackAddressSpace;
  936. int offset = 0; // offset off of ptrVal
  937. uint64_t size = 0; // the size of the memory location
  938. // (taken from memVT if zero)
  939. MaybeAlign align = Align(1); // alignment
  940. MachineMemOperand::Flags flags = MachineMemOperand::MONone;
  941. IntrinsicInfo() = default;
  942. };
  943. /// Given an intrinsic, checks if on the target the intrinsic will need to map
  944. /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
  945. /// true and store the intrinsic information into the IntrinsicInfo that was
  946. /// passed to the function.
  947. virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
  948. MachineFunction &,
  949. unsigned /*Intrinsic*/) const {
  950. return false;
  951. }
  952. /// Returns true if the target can instruction select the specified FP
  953. /// immediate natively. If false, the legalizer will materialize the FP
  954. /// immediate as a load from a constant pool.
  955. virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
  956. bool ForCodeSize = false) const {
  957. return false;
  958. }
  959. /// Targets can use this to indicate that they only support *some*
  960. /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
  961. /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
  962. /// legal.
  963. virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
  964. return true;
  965. }
  966. /// Returns true if the operation can trap for the value type.
  967. ///
  968. /// VT must be a legal type. By default, we optimistically assume most
  969. /// operations don't trap except for integer divide and remainder.
  970. virtual bool canOpTrap(unsigned Op, EVT VT) const;
  971. /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
  972. /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
  973. /// constant pool entry.
  974. virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
  975. EVT /*VT*/) const {
  976. return false;
  977. }
  978. /// How to legalize this custom operation?
  979. virtual LegalizeAction getCustomOperationAction(SDNode &Op) const {
  980. return Legal;
  981. }
  982. /// Return how this operation should be treated: either it is legal, needs to
  983. /// be promoted to a larger size, needs to be expanded to some other code
  984. /// sequence, or the target has a custom expander for it.
  985. LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
  986. if (VT.isExtended()) return Expand;
  987. // If a target-specific SDNode requires legalization, require the target
  988. // to provide custom legalization for it.
  989. if (Op >= std::size(OpActions[0]))
  990. return Custom;
  991. return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
  992. }
  993. /// Custom method defined by each target to indicate if an operation which
  994. /// may require a scale is supported natively by the target.
  995. /// If not, the operation is illegal.
  996. virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
  997. unsigned Scale) const {
  998. return false;
  999. }
  1000. /// Some fixed point operations may be natively supported by the target but
  1001. /// only for specific scales. This method allows for checking
  1002. /// if the width is supported by the target for a given operation that may
  1003. /// depend on scale.
  1004. LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT,
  1005. unsigned Scale) const {
  1006. auto Action = getOperationAction(Op, VT);
  1007. if (Action != Legal)
  1008. return Action;
  1009. // This operation is supported in this type but may only work on specific
  1010. // scales.
  1011. bool Supported;
  1012. switch (Op) {
  1013. default:
  1014. llvm_unreachable("Unexpected fixed point operation.");
  1015. case ISD::SMULFIX:
  1016. case ISD::SMULFIXSAT:
  1017. case ISD::UMULFIX:
  1018. case ISD::UMULFIXSAT:
  1019. case ISD::SDIVFIX:
  1020. case ISD::SDIVFIXSAT:
  1021. case ISD::UDIVFIX:
  1022. case ISD::UDIVFIXSAT:
  1023. Supported = isSupportedFixedPointOperation(Op, VT, Scale);
  1024. break;
  1025. }
  1026. return Supported ? Action : Expand;
  1027. }
  1028. // If Op is a strict floating-point operation, return the result
  1029. // of getOperationAction for the equivalent non-strict operation.
  1030. LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const {
  1031. unsigned EqOpc;
  1032. switch (Op) {
  1033. default: llvm_unreachable("Unexpected FP pseudo-opcode");
  1034. #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  1035. case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
  1036. #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  1037. case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
  1038. #include "llvm/IR/ConstrainedOps.def"
  1039. }
  1040. return getOperationAction(EqOpc, VT);
  1041. }
  1042. /// Return true if the specified operation is legal on this target or can be
  1043. /// made legal with custom lowering. This is used to help guide high-level
  1044. /// lowering decisions. LegalOnly is an optional convenience for code paths
  1045. /// traversed pre and post legalisation.
  1046. bool isOperationLegalOrCustom(unsigned Op, EVT VT,
  1047. bool LegalOnly = false) const {
  1048. if (LegalOnly)
  1049. return isOperationLegal(Op, VT);
  1050. return (VT == MVT::Other || isTypeLegal(VT)) &&
  1051. (getOperationAction(Op, VT) == Legal ||
  1052. getOperationAction(Op, VT) == Custom);
  1053. }
  1054. /// Return true if the specified operation is legal on this target or can be
  1055. /// made legal using promotion. This is used to help guide high-level lowering
  1056. /// decisions. LegalOnly is an optional convenience for code paths traversed
  1057. /// pre and post legalisation.
  1058. bool isOperationLegalOrPromote(unsigned Op, EVT VT,
  1059. bool LegalOnly = false) const {
  1060. if (LegalOnly)
  1061. return isOperationLegal(Op, VT);
  1062. return (VT == MVT::Other || isTypeLegal(VT)) &&
  1063. (getOperationAction(Op, VT) == Legal ||
  1064. getOperationAction(Op, VT) == Promote);
  1065. }
  1066. /// Return true if the specified operation is legal on this target or can be
  1067. /// made legal with custom lowering or using promotion. This is used to help
  1068. /// guide high-level lowering decisions. LegalOnly is an optional convenience
  1069. /// for code paths traversed pre and post legalisation.
  1070. bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT,
  1071. bool LegalOnly = false) const {
  1072. if (LegalOnly)
  1073. return isOperationLegal(Op, VT);
  1074. return (VT == MVT::Other || isTypeLegal(VT)) &&
  1075. (getOperationAction(Op, VT) == Legal ||
  1076. getOperationAction(Op, VT) == Custom ||
  1077. getOperationAction(Op, VT) == Promote);
  1078. }
  1079. /// Return true if the operation uses custom lowering, regardless of whether
  1080. /// the type is legal or not.
  1081. bool isOperationCustom(unsigned Op, EVT VT) const {
  1082. return getOperationAction(Op, VT) == Custom;
  1083. }
  1084. /// Return true if lowering to a jump table is allowed.
  1085. virtual bool areJTsAllowed(const Function *Fn) const {
  1086. if (Fn->getFnAttribute("no-jump-tables").getValueAsBool())
  1087. return false;
  1088. return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  1089. isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
  1090. }
  1091. /// Check whether the range [Low,High] fits in a machine word.
  1092. bool rangeFitsInWord(const APInt &Low, const APInt &High,
  1093. const DataLayout &DL) const {
  1094. // FIXME: Using the pointer type doesn't seem ideal.
  1095. uint64_t BW = DL.getIndexSizeInBits(0u);
  1096. uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
  1097. return Range <= BW;
  1098. }
  1099. /// Return true if lowering to a jump table is suitable for a set of case
  1100. /// clusters which may contain \p NumCases cases, \p Range range of values.
  1101. virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
  1102. uint64_t Range, ProfileSummaryInfo *PSI,
  1103. BlockFrequencyInfo *BFI) const;
  1104. /// Returns preferred type for switch condition.
  1105. virtual MVT getPreferredSwitchConditionType(LLVMContext &Context,
  1106. EVT ConditionVT) const;
  1107. /// Return true if lowering to a bit test is suitable for a set of case
  1108. /// clusters which contains \p NumDests unique destinations, \p Low and
  1109. /// \p High as its lowest and highest case values, and expects \p NumCmps
  1110. /// case value comparisons. Check if the number of destinations, comparison
  1111. /// metric, and range are all suitable.
  1112. bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
  1113. const APInt &Low, const APInt &High,
  1114. const DataLayout &DL) const {
  1115. // FIXME: I don't think NumCmps is the correct metric: a single case and a
  1116. // range of cases both require only one branch to lower. Just looking at the
  1117. // number of clusters and destinations should be enough to decide whether to
  1118. // build bit tests.
  1119. // To lower a range with bit tests, the range must fit the bitwidth of a
  1120. // machine word.
  1121. if (!rangeFitsInWord(Low, High, DL))
  1122. return false;
  1123. // Decide whether it's profitable to lower this range with bit tests. Each
  1124. // destination requires a bit test and branch, and there is an overall range
  1125. // check branch. For a small number of clusters, separate comparisons might
  1126. // be cheaper, and for many destinations, splitting the range might be
  1127. // better.
  1128. return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
  1129. (NumDests == 3 && NumCmps >= 6);
  1130. }
  1131. /// Return true if the specified operation is illegal on this target or
  1132. /// unlikely to be made legal with custom lowering. This is used to help guide
  1133. /// high-level lowering decisions.
  1134. bool isOperationExpand(unsigned Op, EVT VT) const {
  1135. return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
  1136. }
  1137. /// Return true if the specified operation is legal on this target.
  1138. bool isOperationLegal(unsigned Op, EVT VT) const {
  1139. return (VT == MVT::Other || isTypeLegal(VT)) &&
  1140. getOperationAction(Op, VT) == Legal;
  1141. }
  1142. /// Return how this load with extension should be treated: either it is legal,
  1143. /// needs to be promoted to a larger size, needs to be expanded to some other
  1144. /// code sequence, or the target has a custom expander for it.
  1145. LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
  1146. EVT MemVT) const {
  1147. if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
  1148. unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
  1149. unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
  1150. assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::VALUETYPE_SIZE &&
  1151. MemI < MVT::VALUETYPE_SIZE && "Table isn't big enough!");
  1152. unsigned Shift = 4 * ExtType;
  1153. return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
  1154. }
  1155. /// Return true if the specified load with extension is legal on this target.
  1156. bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
  1157. return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
  1158. }
  1159. /// Return true if the specified load with extension is legal or custom
  1160. /// on this target.
  1161. bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
  1162. return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
  1163. getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
  1164. }
  1165. /// Return how this store with truncation should be treated: either it is
  1166. /// legal, needs to be promoted to a larger size, needs to be expanded to some
  1167. /// other code sequence, or the target has a custom expander for it.
  1168. LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
  1169. if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
  1170. unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
  1171. unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
  1172. assert(ValI < MVT::VALUETYPE_SIZE && MemI < MVT::VALUETYPE_SIZE &&
  1173. "Table isn't big enough!");
  1174. return TruncStoreActions[ValI][MemI];
  1175. }
  1176. /// Return true if the specified store with truncation is legal on this
  1177. /// target.
  1178. bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
  1179. return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
  1180. }
  1181. /// Return true if the specified store with truncation has solution on this
  1182. /// target.
  1183. bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
  1184. return isTypeLegal(ValVT) &&
  1185. (getTruncStoreAction(ValVT, MemVT) == Legal ||
  1186. getTruncStoreAction(ValVT, MemVT) == Custom);
  1187. }
  1188. virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT,
  1189. bool LegalOnly) const {
  1190. if (LegalOnly)
  1191. return isTruncStoreLegal(ValVT, MemVT);
  1192. return isTruncStoreLegalOrCustom(ValVT, MemVT);
  1193. }
  1194. /// Return how the indexed load should be treated: either it is legal, needs
  1195. /// to be promoted to a larger size, needs to be expanded to some other code
  1196. /// sequence, or the target has a custom expander for it.
  1197. LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
  1198. return getIndexedModeAction(IdxMode, VT, IMAB_Load);
  1199. }
  1200. /// Return true if the specified indexed load is legal on this target.
  1201. bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
  1202. return VT.isSimple() &&
  1203. (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
  1204. getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
  1205. }
  1206. /// Return how the indexed store should be treated: either it is legal, needs
  1207. /// to be promoted to a larger size, needs to be expanded to some other code
  1208. /// sequence, or the target has a custom expander for it.
  1209. LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
  1210. return getIndexedModeAction(IdxMode, VT, IMAB_Store);
  1211. }
  1212. /// Return true if the specified indexed load is legal on this target.
  1213. bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
  1214. return VT.isSimple() &&
  1215. (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
  1216. getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
  1217. }
  1218. /// Return how the indexed load should be treated: either it is legal, needs
  1219. /// to be promoted to a larger size, needs to be expanded to some other code
  1220. /// sequence, or the target has a custom expander for it.
  1221. LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
  1222. return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
  1223. }
  1224. /// Return true if the specified indexed load is legal on this target.
  1225. bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
  1226. return VT.isSimple() &&
  1227. (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
  1228. getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
  1229. }
  1230. /// Return how the indexed store should be treated: either it is legal, needs
  1231. /// to be promoted to a larger size, needs to be expanded to some other code
  1232. /// sequence, or the target has a custom expander for it.
  1233. LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
  1234. return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
  1235. }
  1236. /// Return true if the specified indexed load is legal on this target.
  1237. bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
  1238. return VT.isSimple() &&
  1239. (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
  1240. getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
  1241. }
  1242. /// Returns true if the index type for a masked gather/scatter requires
  1243. /// extending
  1244. virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const { return false; }
  1245. // Returns true if VT is a legal index type for masked gathers/scatters
  1246. // on this target
  1247. virtual bool shouldRemoveExtendFromGSIndex(EVT IndexVT, EVT DataVT) const {
  1248. return false;
  1249. }
  1250. // Return true if the target supports a scatter/gather instruction with
  1251. // indices which are scaled by the particular value. Note that all targets
  1252. // must by definition support scale of 1.
  1253. virtual bool isLegalScaleForGatherScatter(uint64_t Scale,
  1254. uint64_t ElemSize) const {
  1255. // MGATHER/MSCATTER are only required to support scaling by one or by the
  1256. // element size.
  1257. if (Scale != ElemSize && Scale != 1)
  1258. return false;
  1259. return true;
  1260. }
  1261. /// Return how the condition code should be treated: either it is legal, needs
  1262. /// to be expanded to some other code sequence, or the target has a custom
  1263. /// expander for it.
  1264. LegalizeAction
  1265. getCondCodeAction(ISD::CondCode CC, MVT VT) const {
  1266. assert((unsigned)CC < std::size(CondCodeActions) &&
  1267. ((unsigned)VT.SimpleTy >> 3) < std::size(CondCodeActions[0]) &&
  1268. "Table isn't big enough!");
  1269. // See setCondCodeAction for how this is encoded.
  1270. uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
  1271. uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
  1272. LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
  1273. assert(Action != Promote && "Can't promote condition code!");
  1274. return Action;
  1275. }
  1276. /// Return true if the specified condition code is legal on this target.
  1277. bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
  1278. return getCondCodeAction(CC, VT) == Legal;
  1279. }
  1280. /// Return true if the specified condition code is legal or custom on this
  1281. /// target.
  1282. bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const {
  1283. return getCondCodeAction(CC, VT) == Legal ||
  1284. getCondCodeAction(CC, VT) == Custom;
  1285. }
  1286. /// If the action for this operation is to promote, this method returns the
  1287. /// ValueType to promote to.
  1288. MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
  1289. assert(getOperationAction(Op, VT) == Promote &&
  1290. "This operation isn't promoted!");
  1291. // See if this has an explicit type specified.
  1292. std::map<std::pair<unsigned, MVT::SimpleValueType>,
  1293. MVT::SimpleValueType>::const_iterator PTTI =
  1294. PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
  1295. if (PTTI != PromoteToType.end()) return PTTI->second;
  1296. assert((VT.isInteger() || VT.isFloatingPoint()) &&
  1297. "Cannot autopromote this type, add it with AddPromotedToType.");
  1298. MVT NVT = VT;
  1299. do {
  1300. NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
  1301. assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
  1302. "Didn't find type to promote to!");
  1303. } while (!isTypeLegal(NVT) ||
  1304. getOperationAction(Op, NVT) == Promote);
  1305. return NVT;
  1306. }
  1307. virtual EVT getAsmOperandValueType(const DataLayout &DL, Type *Ty,
  1308. bool AllowUnknown = false) const {
  1309. return getValueType(DL, Ty, AllowUnknown);
  1310. }
  1311. /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
  1312. /// operations except for the pointer size. If AllowUnknown is true, this
  1313. /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
  1314. /// otherwise it will assert.
  1315. EVT getValueType(const DataLayout &DL, Type *Ty,
  1316. bool AllowUnknown = false) const {
  1317. // Lower scalar pointers to native pointer types.
  1318. if (auto *PTy = dyn_cast<PointerType>(Ty))
  1319. return getPointerTy(DL, PTy->getAddressSpace());
  1320. if (auto *VTy = dyn_cast<VectorType>(Ty)) {
  1321. Type *EltTy = VTy->getElementType();
  1322. // Lower vectors of pointers to native pointer types.
  1323. if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
  1324. EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
  1325. EltTy = PointerTy.getTypeForEVT(Ty->getContext());
  1326. }
  1327. return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
  1328. VTy->getElementCount());
  1329. }
  1330. return EVT::getEVT(Ty, AllowUnknown);
  1331. }
  1332. EVT getMemValueType(const DataLayout &DL, Type *Ty,
  1333. bool AllowUnknown = false) const {
  1334. // Lower scalar pointers to native pointer types.
  1335. if (PointerType *PTy = dyn_cast<PointerType>(Ty))
  1336. return getPointerMemTy(DL, PTy->getAddressSpace());
  1337. else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  1338. Type *Elm = VTy->getElementType();
  1339. if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
  1340. EVT PointerTy(getPointerMemTy(DL, PT->getAddressSpace()));
  1341. Elm = PointerTy.getTypeForEVT(Ty->getContext());
  1342. }
  1343. return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
  1344. VTy->getElementCount());
  1345. }
  1346. return getValueType(DL, Ty, AllowUnknown);
  1347. }
  1348. /// Return the MVT corresponding to this LLVM type. See getValueType.
  1349. MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
  1350. bool AllowUnknown = false) const {
  1351. return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
  1352. }
  1353. /// Return the desired alignment for ByVal or InAlloca aggregate function
  1354. /// arguments in the caller parameter area. This is the actual alignment, not
  1355. /// its logarithm.
  1356. virtual uint64_t getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
  1357. /// Return the type of registers that this ValueType will eventually require.
  1358. MVT getRegisterType(MVT VT) const {
  1359. assert((unsigned)VT.SimpleTy < std::size(RegisterTypeForVT));
  1360. return RegisterTypeForVT[VT.SimpleTy];
  1361. }
  1362. /// Return the type of registers that this ValueType will eventually require.
  1363. MVT getRegisterType(LLVMContext &Context, EVT VT) const {
  1364. if (VT.isSimple()) {
  1365. assert((unsigned)VT.getSimpleVT().SimpleTy <
  1366. std::size(RegisterTypeForVT));
  1367. return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
  1368. }
  1369. if (VT.isVector()) {
  1370. EVT VT1;
  1371. MVT RegisterVT;
  1372. unsigned NumIntermediates;
  1373. (void)getVectorTypeBreakdown(Context, VT, VT1,
  1374. NumIntermediates, RegisterVT);
  1375. return RegisterVT;
  1376. }
  1377. if (VT.isInteger()) {
  1378. return getRegisterType(Context, getTypeToTransformTo(Context, VT));
  1379. }
  1380. llvm_unreachable("Unsupported extended type!");
  1381. }
  1382. /// Return the number of registers that this ValueType will eventually
  1383. /// require.
  1384. ///
  1385. /// This is one for any types promoted to live in larger registers, but may be
  1386. /// more than one for types (like i64) that are split into pieces. For types
  1387. /// like i140, which are first promoted then expanded, it is the number of
  1388. /// registers needed to hold all the bits of the original type. For an i140
  1389. /// on a 32 bit machine this means 5 registers.
  1390. ///
  1391. /// RegisterVT may be passed as a way to override the default settings, for
  1392. /// instance with i128 inline assembly operands on SystemZ.
  1393. virtual unsigned
  1394. getNumRegisters(LLVMContext &Context, EVT VT,
  1395. std::optional<MVT> RegisterVT = std::nullopt) const {
  1396. if (VT.isSimple()) {
  1397. assert((unsigned)VT.getSimpleVT().SimpleTy <
  1398. std::size(NumRegistersForVT));
  1399. return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
  1400. }
  1401. if (VT.isVector()) {
  1402. EVT VT1;
  1403. MVT VT2;
  1404. unsigned NumIntermediates;
  1405. return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
  1406. }
  1407. if (VT.isInteger()) {
  1408. unsigned BitWidth = VT.getSizeInBits();
  1409. unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
  1410. return (BitWidth + RegWidth - 1) / RegWidth;
  1411. }
  1412. llvm_unreachable("Unsupported extended type!");
  1413. }
  1414. /// Certain combinations of ABIs, Targets and features require that types
  1415. /// are legal for some operations and not for other operations.
  1416. /// For MIPS all vector types must be passed through the integer register set.
  1417. virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context,
  1418. CallingConv::ID CC, EVT VT) const {
  1419. return getRegisterType(Context, VT);
  1420. }
  1421. /// Certain targets require unusual breakdowns of certain types. For MIPS,
  1422. /// this occurs when a vector type is used, as vector are passed through the
  1423. /// integer register set.
  1424. virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
  1425. CallingConv::ID CC,
  1426. EVT VT) const {
  1427. return getNumRegisters(Context, VT);
  1428. }
  1429. /// Certain targets have context sensitive alignment requirements, where one
  1430. /// type has the alignment requirement of another type.
  1431. virtual Align getABIAlignmentForCallingConv(Type *ArgTy,
  1432. const DataLayout &DL) const {
  1433. return DL.getABITypeAlign(ArgTy);
  1434. }
  1435. /// If true, then instruction selection should seek to shrink the FP constant
  1436. /// of the specified type to a smaller type in order to save space and / or
  1437. /// reduce runtime.
  1438. virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
  1439. /// Return true if it is profitable to reduce a load to a smaller type.
  1440. /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
  1441. virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy,
  1442. EVT NewVT) const {
  1443. // By default, assume that it is cheaper to extract a subvector from a wide
  1444. // vector load rather than creating multiple narrow vector loads.
  1445. if (NewVT.isVector() && !Load->hasOneUse())
  1446. return false;
  1447. return true;
  1448. }
  1449. /// When splitting a value of the specified type into parts, does the Lo
  1450. /// or Hi part come first? This usually follows the endianness, except
  1451. /// for ppcf128, where the Hi part always comes first.
  1452. bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
  1453. return DL.isBigEndian() || VT == MVT::ppcf128;
  1454. }
  1455. /// If true, the target has custom DAG combine transformations that it can
  1456. /// perform for the specified node.
  1457. bool hasTargetDAGCombine(ISD::NodeType NT) const {
  1458. assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
  1459. return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
  1460. }
  1461. unsigned getGatherAllAliasesMaxDepth() const {
  1462. return GatherAllAliasesMaxDepth;
  1463. }
  1464. /// Returns the size of the platform's va_list object.
  1465. virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
  1466. return getPointerTy(DL).getSizeInBits();
  1467. }
  1468. /// Get maximum # of store operations permitted for llvm.memset
  1469. ///
  1470. /// This function returns the maximum number of store operations permitted
  1471. /// to replace a call to llvm.memset. The value is set by the target at the
  1472. /// performance threshold for such a replacement. If OptSize is true,
  1473. /// return the limit for functions that have OptSize attribute.
  1474. unsigned getMaxStoresPerMemset(bool OptSize) const {
  1475. return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
  1476. }
  1477. /// Get maximum # of store operations permitted for llvm.memcpy
  1478. ///
  1479. /// This function returns the maximum number of store operations permitted
  1480. /// to replace a call to llvm.memcpy. The value is set by the target at the
  1481. /// performance threshold for such a replacement. If OptSize is true,
  1482. /// return the limit for functions that have OptSize attribute.
  1483. unsigned getMaxStoresPerMemcpy(bool OptSize) const {
  1484. return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
  1485. }
  1486. /// \brief Get maximum # of store operations to be glued together
  1487. ///
  1488. /// This function returns the maximum number of store operations permitted
  1489. /// to glue together during lowering of llvm.memcpy. The value is set by
  1490. // the target at the performance threshold for such a replacement.
  1491. virtual unsigned getMaxGluedStoresPerMemcpy() const {
  1492. return MaxGluedStoresPerMemcpy;
  1493. }
  1494. /// Get maximum # of load operations permitted for memcmp
  1495. ///
  1496. /// This function returns the maximum number of load operations permitted
  1497. /// to replace a call to memcmp. The value is set by the target at the
  1498. /// performance threshold for such a replacement. If OptSize is true,
  1499. /// return the limit for functions that have OptSize attribute.
  1500. unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
  1501. return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
  1502. }
  1503. /// Get maximum # of store operations permitted for llvm.memmove
  1504. ///
  1505. /// This function returns the maximum number of store operations permitted
  1506. /// to replace a call to llvm.memmove. The value is set by the target at the
  1507. /// performance threshold for such a replacement. If OptSize is true,
  1508. /// return the limit for functions that have OptSize attribute.
  1509. unsigned getMaxStoresPerMemmove(bool OptSize) const {
  1510. return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
  1511. }
  1512. /// Determine if the target supports unaligned memory accesses.
  1513. ///
  1514. /// This function returns true if the target allows unaligned memory accesses
  1515. /// of the specified type in the given address space. If true, it also returns
  1516. /// a relative speed of the unaligned memory access in the last argument by
  1517. /// reference. The higher the speed number the faster the operation comparing
  1518. /// to a number returned by another such call. This is used, for example, in
  1519. /// situations where an array copy/move/set is converted to a sequence of
  1520. /// store operations. Its use helps to ensure that such replacements don't
  1521. /// generate code that causes an alignment error (trap) on the target machine.
  1522. virtual bool allowsMisalignedMemoryAccesses(
  1523. EVT, unsigned AddrSpace = 0, Align Alignment = Align(1),
  1524. MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
  1525. unsigned * /*Fast*/ = nullptr) const {
  1526. return false;
  1527. }
  1528. /// LLT handling variant.
  1529. virtual bool allowsMisalignedMemoryAccesses(
  1530. LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
  1531. MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
  1532. unsigned * /*Fast*/ = nullptr) const {
  1533. return false;
  1534. }
  1535. /// This function returns true if the memory access is aligned or if the
  1536. /// target allows this specific unaligned memory access. If the access is
  1537. /// allowed, the optional final parameter returns a relative speed of the
  1538. /// access (as defined by the target).
  1539. bool allowsMemoryAccessForAlignment(
  1540. LLVMContext &Context, const DataLayout &DL, EVT VT,
  1541. unsigned AddrSpace = 0, Align Alignment = Align(1),
  1542. MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
  1543. unsigned *Fast = nullptr) const;
  1544. /// Return true if the memory access of this type is aligned or if the target
  1545. /// allows this specific unaligned access for the given MachineMemOperand.
  1546. /// If the access is allowed, the optional final parameter returns a relative
  1547. /// speed of the access (as defined by the target).
  1548. bool allowsMemoryAccessForAlignment(LLVMContext &Context,
  1549. const DataLayout &DL, EVT VT,
  1550. const MachineMemOperand &MMO,
  1551. unsigned *Fast = nullptr) const;
  1552. /// Return true if the target supports a memory access of this type for the
  1553. /// given address space and alignment. If the access is allowed, the optional
  1554. /// final parameter returns the relative speed of the access (as defined by
  1555. /// the target).
  1556. virtual bool
  1557. allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
  1558. unsigned AddrSpace = 0, Align Alignment = Align(1),
  1559. MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
  1560. unsigned *Fast = nullptr) const;
  1561. /// Return true if the target supports a memory access of this type for the
  1562. /// given MachineMemOperand. If the access is allowed, the optional
  1563. /// final parameter returns the relative access speed (as defined by the
  1564. /// target).
  1565. bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
  1566. const MachineMemOperand &MMO,
  1567. unsigned *Fast = nullptr) const;
  1568. /// LLT handling variant.
  1569. bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, LLT Ty,
  1570. const MachineMemOperand &MMO,
  1571. unsigned *Fast = nullptr) const;
  1572. /// Returns the target specific optimal type for load and store operations as
  1573. /// a result of memset, memcpy, and memmove lowering.
  1574. /// It returns EVT::Other if the type should be determined using generic
  1575. /// target-independent logic.
  1576. virtual EVT
  1577. getOptimalMemOpType(const MemOp &Op,
  1578. const AttributeList & /*FuncAttributes*/) const {
  1579. return MVT::Other;
  1580. }
  1581. /// LLT returning variant.
  1582. virtual LLT
  1583. getOptimalMemOpLLT(const MemOp &Op,
  1584. const AttributeList & /*FuncAttributes*/) const {
  1585. return LLT();
  1586. }
  1587. /// Returns true if it's safe to use load / store of the specified type to
  1588. /// expand memcpy / memset inline.
  1589. ///
  1590. /// This is mostly true for all types except for some special cases. For
  1591. /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
  1592. /// fstpl which also does type conversion. Note the specified type doesn't
  1593. /// have to be legal as the hook is used before type legalization.
  1594. virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
  1595. /// Return lower limit for number of blocks in a jump table.
  1596. virtual unsigned getMinimumJumpTableEntries() const;
  1597. /// Return lower limit of the density in a jump table.
  1598. unsigned getMinimumJumpTableDensity(bool OptForSize) const;
  1599. /// Return upper limit for number of entries in a jump table.
  1600. /// Zero if no limit.
  1601. unsigned getMaximumJumpTableSize() const;
  1602. virtual bool isJumpTableRelative() const;
  1603. /// If a physical register, this specifies the register that
  1604. /// llvm.savestack/llvm.restorestack should save and restore.
  1605. Register getStackPointerRegisterToSaveRestore() const {
  1606. return StackPointerRegisterToSaveRestore;
  1607. }
  1608. /// If a physical register, this returns the register that receives the
  1609. /// exception address on entry to an EH pad.
  1610. virtual Register
  1611. getExceptionPointerRegister(const Constant *PersonalityFn) const {
  1612. return Register();
  1613. }
  1614. /// If a physical register, this returns the register that receives the
  1615. /// exception typeid on entry to a landing pad.
  1616. virtual Register
  1617. getExceptionSelectorRegister(const Constant *PersonalityFn) const {
  1618. return Register();
  1619. }
  1620. virtual bool needsFixedCatchObjects() const {
  1621. report_fatal_error("Funclet EH is not implemented for this target");
  1622. }
  1623. /// Return the minimum stack alignment of an argument.
  1624. Align getMinStackArgumentAlignment() const {
  1625. return MinStackArgumentAlignment;
  1626. }
  1627. /// Return the minimum function alignment.
  1628. Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
  1629. /// Return the preferred function alignment.
  1630. Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
  1631. /// Return the preferred loop alignment.
  1632. virtual Align getPrefLoopAlignment(MachineLoop *ML = nullptr) const;
  1633. /// Return the maximum amount of bytes allowed to be emitted when padding for
  1634. /// alignment
  1635. virtual unsigned
  1636. getMaxPermittedBytesForAlignment(MachineBasicBlock *MBB) const;
  1637. /// Should loops be aligned even when the function is marked OptSize (but not
  1638. /// MinSize).
  1639. virtual bool alignLoopsWithOptSize() const { return false; }
  1640. /// If the target has a standard location for the stack protector guard,
  1641. /// returns the address of that location. Otherwise, returns nullptr.
  1642. /// DEPRECATED: please override useLoadStackGuardNode and customize
  1643. /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
  1644. virtual Value *getIRStackGuard(IRBuilderBase &IRB) const;
  1645. /// Inserts necessary declarations for SSP (stack protection) purpose.
  1646. /// Should be used only when getIRStackGuard returns nullptr.
  1647. virtual void insertSSPDeclarations(Module &M) const;
  1648. /// Return the variable that's previously inserted by insertSSPDeclarations,
  1649. /// if any, otherwise return nullptr. Should be used only when
  1650. /// getIRStackGuard returns nullptr.
  1651. virtual Value *getSDagStackGuard(const Module &M) const;
  1652. /// If this function returns true, stack protection checks should XOR the
  1653. /// frame pointer (or whichever pointer is used to address locals) into the
  1654. /// stack guard value before checking it. getIRStackGuard must return nullptr
  1655. /// if this returns true.
  1656. virtual bool useStackGuardXorFP() const { return false; }
  1657. /// If the target has a standard stack protection check function that
  1658. /// performs validation and error handling, returns the function. Otherwise,
  1659. /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
  1660. /// Should be used only when getIRStackGuard returns nullptr.
  1661. virtual Function *getSSPStackGuardCheck(const Module &M) const;
  1662. /// \returns true if a constant G_UBFX is legal on the target.
  1663. virtual bool isConstantUnsignedBitfieldExtractLegal(unsigned Opc, LLT Ty1,
  1664. LLT Ty2) const {
  1665. return false;
  1666. }
  1667. protected:
  1668. Value *getDefaultSafeStackPointerLocation(IRBuilderBase &IRB,
  1669. bool UseTLS) const;
  1670. public:
  1671. /// Returns the target-specific address of the unsafe stack pointer.
  1672. virtual Value *getSafeStackPointerLocation(IRBuilderBase &IRB) const;
  1673. /// Returns the name of the symbol used to emit stack probes or the empty
  1674. /// string if not applicable.
  1675. virtual bool hasStackProbeSymbol(const MachineFunction &MF) const { return false; }
  1676. virtual bool hasInlineStackProbe(const MachineFunction &MF) const { return false; }
  1677. virtual StringRef getStackProbeSymbolName(const MachineFunction &MF) const {
  1678. return "";
  1679. }
  1680. /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
  1681. /// are happy to sink it into basic blocks. A cast may be free, but not
  1682. /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
  1683. virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const;
  1684. /// Return true if the pointer arguments to CI should be aligned by aligning
  1685. /// the object whose address is being passed. If so then MinSize is set to the
  1686. /// minimum size the object must be to be aligned and PrefAlign is set to the
  1687. /// preferred alignment.
  1688. virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
  1689. Align & /*PrefAlign*/) const {
  1690. return false;
  1691. }
  1692. //===--------------------------------------------------------------------===//
  1693. /// \name Helpers for TargetTransformInfo implementations
  1694. /// @{
  1695. /// Get the ISD node that corresponds to the Instruction class opcode.
  1696. int InstructionOpcodeToISD(unsigned Opcode) const;
  1697. /// @}
  1698. //===--------------------------------------------------------------------===//
  1699. /// \name Helpers for atomic expansion.
  1700. /// @{
  1701. /// Returns the maximum atomic operation size (in bits) supported by
  1702. /// the backend. Atomic operations greater than this size (as well
  1703. /// as ones that are not naturally aligned), will be expanded by
  1704. /// AtomicExpandPass into an __atomic_* library call.
  1705. unsigned getMaxAtomicSizeInBitsSupported() const {
  1706. return MaxAtomicSizeInBitsSupported;
  1707. }
  1708. /// Returns the size in bits of the maximum div/rem the backend supports.
  1709. /// Larger operations will be expanded by ExpandLargeDivRem.
  1710. unsigned getMaxDivRemBitWidthSupported() const {
  1711. return MaxDivRemBitWidthSupported;
  1712. }
  1713. /// Returns the size in bits of the maximum larget fp convert the backend
  1714. /// supports. Larger operations will be expanded by ExpandLargeFPConvert.
  1715. unsigned getMaxLargeFPConvertBitWidthSupported() const {
  1716. return MaxLargeFPConvertBitWidthSupported;
  1717. }
  1718. /// Returns the size of the smallest cmpxchg or ll/sc instruction
  1719. /// the backend supports. Any smaller operations are widened in
  1720. /// AtomicExpandPass.
  1721. ///
  1722. /// Note that *unlike* operations above the maximum size, atomic ops
  1723. /// are still natively supported below the minimum; they just
  1724. /// require a more complex expansion.
  1725. unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
  1726. /// Whether the target supports unaligned atomic operations.
  1727. bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
  1728. /// Whether AtomicExpandPass should automatically insert fences and reduce
  1729. /// ordering for this atomic. This should be true for most architectures with
  1730. /// weak memory ordering. Defaults to false.
  1731. virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
  1732. return false;
  1733. }
  1734. /// Whether AtomicExpandPass should automatically insert a trailing fence
  1735. /// without reducing the ordering for this atomic. Defaults to false.
  1736. virtual bool
  1737. shouldInsertTrailingFenceForAtomicStore(const Instruction *I) const {
  1738. return false;
  1739. }
  1740. /// Perform a load-linked operation on Addr, returning a "Value *" with the
  1741. /// corresponding pointee type. This may entail some non-trivial operations to
  1742. /// truncate or reconstruct types that will be illegal in the backend. See
  1743. /// ARMISelLowering for an example implementation.
  1744. virtual Value *emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
  1745. Value *Addr, AtomicOrdering Ord) const {
  1746. llvm_unreachable("Load linked unimplemented on this target");
  1747. }
  1748. /// Perform a store-conditional operation to Addr. Return the status of the
  1749. /// store. This should be 0 if the store succeeded, non-zero otherwise.
  1750. virtual Value *emitStoreConditional(IRBuilderBase &Builder, Value *Val,
  1751. Value *Addr, AtomicOrdering Ord) const {
  1752. llvm_unreachable("Store conditional unimplemented on this target");
  1753. }
  1754. /// Perform a masked atomicrmw using a target-specific intrinsic. This
  1755. /// represents the core LL/SC loop which will be lowered at a late stage by
  1756. /// the backend. The target-specific intrinsic returns the loaded value and
  1757. /// is not responsible for masking and shifting the result.
  1758. virtual Value *emitMaskedAtomicRMWIntrinsic(IRBuilderBase &Builder,
  1759. AtomicRMWInst *AI,
  1760. Value *AlignedAddr, Value *Incr,
  1761. Value *Mask, Value *ShiftAmt,
  1762. AtomicOrdering Ord) const {
  1763. llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
  1764. }
  1765. /// Perform a atomicrmw expansion using a target-specific way. This is
  1766. /// expected to be called when masked atomicrmw and bit test atomicrmw don't
  1767. /// work, and the target supports another way to lower atomicrmw.
  1768. virtual void emitExpandAtomicRMW(AtomicRMWInst *AI) const {
  1769. llvm_unreachable(
  1770. "Generic atomicrmw expansion unimplemented on this target");
  1771. }
  1772. /// Perform a bit test atomicrmw using a target-specific intrinsic. This
  1773. /// represents the combined bit test intrinsic which will be lowered at a late
  1774. /// stage by the backend.
  1775. virtual void emitBitTestAtomicRMWIntrinsic(AtomicRMWInst *AI) const {
  1776. llvm_unreachable(
  1777. "Bit test atomicrmw expansion unimplemented on this target");
  1778. }
  1779. /// Perform a atomicrmw which the result is only used by comparison, using a
  1780. /// target-specific intrinsic. This represents the combined atomic and compare
  1781. /// intrinsic which will be lowered at a late stage by the backend.
  1782. virtual void emitCmpArithAtomicRMWIntrinsic(AtomicRMWInst *AI) const {
  1783. llvm_unreachable(
  1784. "Compare arith atomicrmw expansion unimplemented on this target");
  1785. }
  1786. /// Perform a masked cmpxchg using a target-specific intrinsic. This
  1787. /// represents the core LL/SC loop which will be lowered at a late stage by
  1788. /// the backend. The target-specific intrinsic returns the loaded value and
  1789. /// is not responsible for masking and shifting the result.
  1790. virtual Value *emitMaskedAtomicCmpXchgIntrinsic(
  1791. IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
  1792. Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
  1793. llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
  1794. }
  1795. /// Inserts in the IR a target-specific intrinsic specifying a fence.
  1796. /// It is called by AtomicExpandPass before expanding an
  1797. /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
  1798. /// if shouldInsertFencesForAtomic returns true.
  1799. ///
  1800. /// Inst is the original atomic instruction, prior to other expansions that
  1801. /// may be performed.
  1802. ///
  1803. /// This function should either return a nullptr, or a pointer to an IR-level
  1804. /// Instruction*. Even complex fence sequences can be represented by a
  1805. /// single Instruction* through an intrinsic to be lowered later.
  1806. /// Backends should override this method to produce target-specific intrinsic
  1807. /// for their fences.
  1808. /// FIXME: Please note that the default implementation here in terms of
  1809. /// IR-level fences exists for historical/compatibility reasons and is
  1810. /// *unsound* ! Fences cannot, in general, be used to restore sequential
  1811. /// consistency. For example, consider the following example:
  1812. /// atomic<int> x = y = 0;
  1813. /// int r1, r2, r3, r4;
  1814. /// Thread 0:
  1815. /// x.store(1);
  1816. /// Thread 1:
  1817. /// y.store(1);
  1818. /// Thread 2:
  1819. /// r1 = x.load();
  1820. /// r2 = y.load();
  1821. /// Thread 3:
  1822. /// r3 = y.load();
  1823. /// r4 = x.load();
  1824. /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
  1825. /// seq_cst. But if they are lowered to monotonic accesses, no amount of
  1826. /// IR-level fences can prevent it.
  1827. /// @{
  1828. virtual Instruction *emitLeadingFence(IRBuilderBase &Builder,
  1829. Instruction *Inst,
  1830. AtomicOrdering Ord) const;
  1831. virtual Instruction *emitTrailingFence(IRBuilderBase &Builder,
  1832. Instruction *Inst,
  1833. AtomicOrdering Ord) const;
  1834. /// @}
  1835. // Emits code that executes when the comparison result in the ll/sc
  1836. // expansion of a cmpxchg instruction is such that the store-conditional will
  1837. // not execute. This makes it possible to balance out the load-linked with
  1838. // a dedicated instruction, if desired.
  1839. // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
  1840. // be unnecessarily held, except if clrex, inserted by this hook, is executed.
  1841. virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const {}
  1842. /// Returns true if arguments should be sign-extended in lib calls.
  1843. virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
  1844. return IsSigned;
  1845. }
  1846. /// Returns true if arguments should be extended in lib calls.
  1847. virtual bool shouldExtendTypeInLibCall(EVT Type) const {
  1848. return true;
  1849. }
  1850. /// Returns how the given (atomic) load should be expanded by the
  1851. /// IR-level AtomicExpand pass.
  1852. virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
  1853. return AtomicExpansionKind::None;
  1854. }
  1855. /// Returns how the given (atomic) load should be cast by the IR-level
  1856. /// AtomicExpand pass.
  1857. virtual AtomicExpansionKind shouldCastAtomicLoadInIR(LoadInst *LI) const {
  1858. if (LI->getType()->isFloatingPointTy())
  1859. return AtomicExpansionKind::CastToInteger;
  1860. return AtomicExpansionKind::None;
  1861. }
  1862. /// Returns how the given (atomic) store should be expanded by the IR-level
  1863. /// AtomicExpand pass into. For instance AtomicExpansionKind::Expand will try
  1864. /// to use an atomicrmw xchg.
  1865. virtual AtomicExpansionKind shouldExpandAtomicStoreInIR(StoreInst *SI) const {
  1866. return AtomicExpansionKind::None;
  1867. }
  1868. /// Returns how the given (atomic) store should be cast by the IR-level
  1869. /// AtomicExpand pass into. For instance AtomicExpansionKind::CastToInteger
  1870. /// will try to cast the operands to integer values.
  1871. virtual AtomicExpansionKind shouldCastAtomicStoreInIR(StoreInst *SI) const {
  1872. if (SI->getValueOperand()->getType()->isFloatingPointTy())
  1873. return AtomicExpansionKind::CastToInteger;
  1874. return AtomicExpansionKind::None;
  1875. }
  1876. /// Returns how the given atomic cmpxchg should be expanded by the IR-level
  1877. /// AtomicExpand pass.
  1878. virtual AtomicExpansionKind
  1879. shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
  1880. return AtomicExpansionKind::None;
  1881. }
  1882. /// Returns how the IR-level AtomicExpand pass should expand the given
  1883. /// AtomicRMW, if at all. Default is to never expand.
  1884. virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
  1885. return RMW->isFloatingPointOperation() ?
  1886. AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None;
  1887. }
  1888. /// Returns how the given atomic atomicrmw should be cast by the IR-level
  1889. /// AtomicExpand pass.
  1890. virtual AtomicExpansionKind
  1891. shouldCastAtomicRMWIInIR(AtomicRMWInst *RMWI) const {
  1892. if (RMWI->getOperation() == AtomicRMWInst::Xchg &&
  1893. (RMWI->getValOperand()->getType()->isFloatingPointTy() ||
  1894. RMWI->getValOperand()->getType()->isPointerTy()))
  1895. return AtomicExpansionKind::CastToInteger;
  1896. return AtomicExpansionKind::None;
  1897. }
  1898. /// On some platforms, an AtomicRMW that never actually modifies the value
  1899. /// (such as fetch_add of 0) can be turned into a fence followed by an
  1900. /// atomic load. This may sound useless, but it makes it possible for the
  1901. /// processor to keep the cacheline shared, dramatically improving
  1902. /// performance. And such idempotent RMWs are useful for implementing some
  1903. /// kinds of locks, see for example (justification + benchmarks):
  1904. /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
  1905. /// This method tries doing that transformation, returning the atomic load if
  1906. /// it succeeds, and nullptr otherwise.
  1907. /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
  1908. /// another round of expansion.
  1909. virtual LoadInst *
  1910. lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
  1911. return nullptr;
  1912. }
  1913. /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
  1914. /// SIGN_EXTEND, or ANY_EXTEND).
  1915. virtual ISD::NodeType getExtendForAtomicOps() const {
  1916. return ISD::ZERO_EXTEND;
  1917. }
  1918. /// Returns how the platform's atomic compare and swap expects its comparison
  1919. /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
  1920. /// separate from getExtendForAtomicOps, which is concerned with the
  1921. /// sign-extension of the instruction's output, whereas here we are concerned
  1922. /// with the sign-extension of the input. For targets with compare-and-swap
  1923. /// instructions (or sub-word comparisons in their LL/SC loop expansions),
  1924. /// the input can be ANY_EXTEND, but the output will still have a specific
  1925. /// extension.
  1926. virtual ISD::NodeType getExtendForAtomicCmpSwapArg() const {
  1927. return ISD::ANY_EXTEND;
  1928. }
  1929. /// @}
  1930. /// Returns true if we should normalize
  1931. /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
  1932. /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
  1933. /// that it saves us from materializing N0 and N1 in an integer register.
  1934. /// Targets that are able to perform and/or on flags should return false here.
  1935. virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
  1936. EVT VT) const {
  1937. // If a target has multiple condition registers, then it likely has logical
  1938. // operations on those registers.
  1939. if (hasMultipleConditionRegisters())
  1940. return false;
  1941. // Only do the transform if the value won't be split into multiple
  1942. // registers.
  1943. LegalizeTypeAction Action = getTypeAction(Context, VT);
  1944. return Action != TypeExpandInteger && Action != TypeExpandFloat &&
  1945. Action != TypeSplitVector;
  1946. }
  1947. virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
  1948. /// Return true if a select of constants (select Cond, C1, C2) should be
  1949. /// transformed into simple math ops with the condition value. For example:
  1950. /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
  1951. virtual bool convertSelectOfConstantsToMath(EVT VT) const {
  1952. return false;
  1953. }
  1954. /// Return true if it is profitable to transform an integer
  1955. /// multiplication-by-constant into simpler operations like shifts and adds.
  1956. /// This may be true if the target does not directly support the
  1957. /// multiplication operation for the specified type or the sequence of simpler
  1958. /// ops is faster than the multiply.
  1959. virtual bool decomposeMulByConstant(LLVMContext &Context,
  1960. EVT VT, SDValue C) const {
  1961. return false;
  1962. }
  1963. /// Return true if it may be profitable to transform
  1964. /// (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
  1965. /// This may not be true if c1 and c2 can be represented as immediates but
  1966. /// c1*c2 cannot, for example.
  1967. /// The target should check if c1, c2 and c1*c2 can be represented as
  1968. /// immediates, or have to be materialized into registers. If it is not sure
  1969. /// about some cases, a default true can be returned to let the DAGCombiner
  1970. /// decide.
  1971. /// AddNode is (add x, c1), and ConstNode is c2.
  1972. virtual bool isMulAddWithConstProfitable(SDValue AddNode,
  1973. SDValue ConstNode) const {
  1974. return true;
  1975. }
  1976. /// Return true if it is more correct/profitable to use strict FP_TO_INT
  1977. /// conversion operations - canonicalizing the FP source value instead of
  1978. /// converting all cases and then selecting based on value.
  1979. /// This may be true if the target throws exceptions for out of bounds
  1980. /// conversions or has fast FP CMOV.
  1981. virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
  1982. bool IsSigned) const {
  1983. return false;
  1984. }
  1985. /// Return true if it is beneficial to expand an @llvm.powi.* intrinsic.
  1986. /// If not optimizing for size, expanding @llvm.powi.* intrinsics is always
  1987. /// considered beneficial.
  1988. /// If optimizing for size, expansion is only considered beneficial for upto
  1989. /// 5 multiplies and a divide (if the exponent is negative).
  1990. bool isBeneficialToExpandPowI(int Exponent, bool OptForSize) const {
  1991. if (Exponent < 0)
  1992. Exponent = -Exponent;
  1993. return !OptForSize ||
  1994. (llvm::popcount((unsigned int)Exponent) + Log2_32(Exponent) < 7);
  1995. }
  1996. //===--------------------------------------------------------------------===//
  1997. // TargetLowering Configuration Methods - These methods should be invoked by
  1998. // the derived class constructor to configure this object for the target.
  1999. //
  2000. protected:
  2001. /// Specify how the target extends the result of integer and floating point
  2002. /// boolean values from i1 to a wider type. See getBooleanContents.
  2003. void setBooleanContents(BooleanContent Ty) {
  2004. BooleanContents = Ty;
  2005. BooleanFloatContents = Ty;
  2006. }
  2007. /// Specify how the target extends the result of integer and floating point
  2008. /// boolean values from i1 to a wider type. See getBooleanContents.
  2009. void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
  2010. BooleanContents = IntTy;
  2011. BooleanFloatContents = FloatTy;
  2012. }
  2013. /// Specify how the target extends the result of a vector boolean value from a
  2014. /// vector of i1 to a wider type. See getBooleanContents.
  2015. void setBooleanVectorContents(BooleanContent Ty) {
  2016. BooleanVectorContents = Ty;
  2017. }
  2018. /// Specify the target scheduling preference.
  2019. void setSchedulingPreference(Sched::Preference Pref) {
  2020. SchedPreferenceInfo = Pref;
  2021. }
  2022. /// Indicate the minimum number of blocks to generate jump tables.
  2023. void setMinimumJumpTableEntries(unsigned Val);
  2024. /// Indicate the maximum number of entries in jump tables.
  2025. /// Set to zero to generate unlimited jump tables.
  2026. void setMaximumJumpTableSize(unsigned);
  2027. /// If set to a physical register, this specifies the register that
  2028. /// llvm.savestack/llvm.restorestack should save and restore.
  2029. void setStackPointerRegisterToSaveRestore(Register R) {
  2030. StackPointerRegisterToSaveRestore = R;
  2031. }
  2032. /// Tells the code generator that the target has multiple (allocatable)
  2033. /// condition registers that can be used to store the results of comparisons
  2034. /// for use by selects and conditional branches. With multiple condition
  2035. /// registers, the code generator will not aggressively sink comparisons into
  2036. /// the blocks of their users.
  2037. void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
  2038. HasMultipleConditionRegisters = hasManyRegs;
  2039. }
  2040. /// Tells the code generator that the target has BitExtract instructions.
  2041. /// The code generator will aggressively sink "shift"s into the blocks of
  2042. /// their users if the users will generate "and" instructions which can be
  2043. /// combined with "shift" to BitExtract instructions.
  2044. void setHasExtractBitsInsn(bool hasExtractInsn = true) {
  2045. HasExtractBitsInsn = hasExtractInsn;
  2046. }
  2047. /// Tells the code generator not to expand logic operations on comparison
  2048. /// predicates into separate sequences that increase the amount of flow
  2049. /// control.
  2050. void setJumpIsExpensive(bool isExpensive = true);
  2051. /// Tells the code generator which bitwidths to bypass.
  2052. void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
  2053. BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
  2054. }
  2055. /// Add the specified register class as an available regclass for the
  2056. /// specified value type. This indicates the selector can handle values of
  2057. /// that class natively.
  2058. void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
  2059. assert((unsigned)VT.SimpleTy < std::size(RegClassForVT));
  2060. RegClassForVT[VT.SimpleTy] = RC;
  2061. }
  2062. /// Return the largest legal super-reg register class of the register class
  2063. /// for the specified type and its associated "cost".
  2064. virtual std::pair<const TargetRegisterClass *, uint8_t>
  2065. findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
  2066. /// Once all of the register classes are added, this allows us to compute
  2067. /// derived properties we expose.
  2068. void computeRegisterProperties(const TargetRegisterInfo *TRI);
  2069. /// Indicate that the specified operation does not work with the specified
  2070. /// type and indicate what to do about it. Note that VT may refer to either
  2071. /// the type of a result or that of an operand of Op.
  2072. void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action) {
  2073. assert(Op < std::size(OpActions[0]) && "Table isn't big enough!");
  2074. OpActions[(unsigned)VT.SimpleTy][Op] = Action;
  2075. }
  2076. void setOperationAction(ArrayRef<unsigned> Ops, MVT VT,
  2077. LegalizeAction Action) {
  2078. for (auto Op : Ops)
  2079. setOperationAction(Op, VT, Action);
  2080. }
  2081. void setOperationAction(ArrayRef<unsigned> Ops, ArrayRef<MVT> VTs,
  2082. LegalizeAction Action) {
  2083. for (auto VT : VTs)
  2084. setOperationAction(Ops, VT, Action);
  2085. }
  2086. /// Indicate that the specified load with extension does not work with the
  2087. /// specified type and indicate what to do about it.
  2088. void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
  2089. LegalizeAction Action) {
  2090. assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
  2091. MemVT.isValid() && "Table isn't big enough!");
  2092. assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
  2093. unsigned Shift = 4 * ExtType;
  2094. LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
  2095. LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
  2096. }
  2097. void setLoadExtAction(ArrayRef<unsigned> ExtTypes, MVT ValVT, MVT MemVT,
  2098. LegalizeAction Action) {
  2099. for (auto ExtType : ExtTypes)
  2100. setLoadExtAction(ExtType, ValVT, MemVT, Action);
  2101. }
  2102. void setLoadExtAction(ArrayRef<unsigned> ExtTypes, MVT ValVT,
  2103. ArrayRef<MVT> MemVTs, LegalizeAction Action) {
  2104. for (auto MemVT : MemVTs)
  2105. setLoadExtAction(ExtTypes, ValVT, MemVT, Action);
  2106. }
  2107. /// Indicate that the specified truncating store does not work with the
  2108. /// specified type and indicate what to do about it.
  2109. void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action) {
  2110. assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
  2111. TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
  2112. }
  2113. /// Indicate that the specified indexed load does or does not work with the
  2114. /// specified type and indicate what to do abort it.
  2115. ///
  2116. /// NOTE: All indexed mode loads are initialized to Expand in
  2117. /// TargetLowering.cpp
  2118. void setIndexedLoadAction(ArrayRef<unsigned> IdxModes, MVT VT,
  2119. LegalizeAction Action) {
  2120. for (auto IdxMode : IdxModes)
  2121. setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
  2122. }
  2123. void setIndexedLoadAction(ArrayRef<unsigned> IdxModes, ArrayRef<MVT> VTs,
  2124. LegalizeAction Action) {
  2125. for (auto VT : VTs)
  2126. setIndexedLoadAction(IdxModes, VT, Action);
  2127. }
  2128. /// Indicate that the specified indexed store does or does not work with the
  2129. /// specified type and indicate what to do about it.
  2130. ///
  2131. /// NOTE: All indexed mode stores are initialized to Expand in
  2132. /// TargetLowering.cpp
  2133. void setIndexedStoreAction(ArrayRef<unsigned> IdxModes, MVT VT,
  2134. LegalizeAction Action) {
  2135. for (auto IdxMode : IdxModes)
  2136. setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
  2137. }
  2138. void setIndexedStoreAction(ArrayRef<unsigned> IdxModes, ArrayRef<MVT> VTs,
  2139. LegalizeAction Action) {
  2140. for (auto VT : VTs)
  2141. setIndexedStoreAction(IdxModes, VT, Action);
  2142. }
  2143. /// Indicate that the specified indexed masked load does or does not work with
  2144. /// the specified type and indicate what to do about it.
  2145. ///
  2146. /// NOTE: All indexed mode masked loads are initialized to Expand in
  2147. /// TargetLowering.cpp
  2148. void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
  2149. LegalizeAction Action) {
  2150. setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
  2151. }
  2152. /// Indicate that the specified indexed masked store does or does not work
  2153. /// with the specified type and indicate what to do about it.
  2154. ///
  2155. /// NOTE: All indexed mode masked stores are initialized to Expand in
  2156. /// TargetLowering.cpp
  2157. void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
  2158. LegalizeAction Action) {
  2159. setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
  2160. }
  2161. /// Indicate that the specified condition code is or isn't supported on the
  2162. /// target and indicate what to do about it.
  2163. void setCondCodeAction(ArrayRef<ISD::CondCode> CCs, MVT VT,
  2164. LegalizeAction Action) {
  2165. for (auto CC : CCs) {
  2166. assert(VT.isValid() && (unsigned)CC < std::size(CondCodeActions) &&
  2167. "Table isn't big enough!");
  2168. assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
  2169. /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the
  2170. /// 32-bit value and the upper 29 bits index into the second dimension of
  2171. /// the array to select what 32-bit value to use.
  2172. uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
  2173. CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
  2174. CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
  2175. }
  2176. }
  2177. void setCondCodeAction(ArrayRef<ISD::CondCode> CCs, ArrayRef<MVT> VTs,
  2178. LegalizeAction Action) {
  2179. for (auto VT : VTs)
  2180. setCondCodeAction(CCs, VT, Action);
  2181. }
  2182. /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
  2183. /// to trying a larger integer/fp until it can find one that works. If that
  2184. /// default is insufficient, this method can be used by the target to override
  2185. /// the default.
  2186. void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
  2187. PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
  2188. }
  2189. /// Convenience method to set an operation to Promote and specify the type
  2190. /// in a single call.
  2191. void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
  2192. setOperationAction(Opc, OrigVT, Promote);
  2193. AddPromotedToType(Opc, OrigVT, DestVT);
  2194. }
  2195. /// Targets should invoke this method for each target independent node that
  2196. /// they want to provide a custom DAG combiner for by implementing the
  2197. /// PerformDAGCombine virtual method.
  2198. void setTargetDAGCombine(ArrayRef<ISD::NodeType> NTs) {
  2199. for (auto NT : NTs) {
  2200. assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
  2201. TargetDAGCombineArray[NT >> 3] |= 1 << (NT & 7);
  2202. }
  2203. }
  2204. /// Set the target's minimum function alignment.
  2205. void setMinFunctionAlignment(Align Alignment) {
  2206. MinFunctionAlignment = Alignment;
  2207. }
  2208. /// Set the target's preferred function alignment. This should be set if
  2209. /// there is a performance benefit to higher-than-minimum alignment
  2210. void setPrefFunctionAlignment(Align Alignment) {
  2211. PrefFunctionAlignment = Alignment;
  2212. }
  2213. /// Set the target's preferred loop alignment. Default alignment is one, it
  2214. /// means the target does not care about loop alignment. The target may also
  2215. /// override getPrefLoopAlignment to provide per-loop values.
  2216. void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
  2217. void setMaxBytesForAlignment(unsigned MaxBytes) {
  2218. MaxBytesForAlignment = MaxBytes;
  2219. }
  2220. /// Set the minimum stack alignment of an argument.
  2221. void setMinStackArgumentAlignment(Align Alignment) {
  2222. MinStackArgumentAlignment = Alignment;
  2223. }
  2224. /// Set the maximum atomic operation size supported by the
  2225. /// backend. Atomic operations greater than this size (as well as
  2226. /// ones that are not naturally aligned), will be expanded by
  2227. /// AtomicExpandPass into an __atomic_* library call.
  2228. void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
  2229. MaxAtomicSizeInBitsSupported = SizeInBits;
  2230. }
  2231. /// Set the size in bits of the maximum div/rem the backend supports.
  2232. /// Larger operations will be expanded by ExpandLargeDivRem.
  2233. void setMaxDivRemBitWidthSupported(unsigned SizeInBits) {
  2234. MaxDivRemBitWidthSupported = SizeInBits;
  2235. }
  2236. /// Set the size in bits of the maximum fp convert the backend supports.
  2237. /// Larger operations will be expanded by ExpandLargeFPConvert.
  2238. void setMaxLargeFPConvertBitWidthSupported(unsigned SizeInBits) {
  2239. MaxLargeFPConvertBitWidthSupported = SizeInBits;
  2240. }
  2241. /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
  2242. void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
  2243. MinCmpXchgSizeInBits = SizeInBits;
  2244. }
  2245. /// Sets whether unaligned atomic operations are supported.
  2246. void setSupportsUnalignedAtomics(bool UnalignedSupported) {
  2247. SupportsUnalignedAtomics = UnalignedSupported;
  2248. }
  2249. public:
  2250. //===--------------------------------------------------------------------===//
  2251. // Addressing mode description hooks (used by LSR etc).
  2252. //
  2253. /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
  2254. /// instructions reading the address. This allows as much computation as
  2255. /// possible to be done in the address mode for that operand. This hook lets
  2256. /// targets also pass back when this should be done on intrinsics which
  2257. /// load/store.
  2258. virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
  2259. SmallVectorImpl<Value*> &/*Ops*/,
  2260. Type *&/*AccessTy*/) const {
  2261. return false;
  2262. }
  2263. /// This represents an addressing mode of:
  2264. /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
  2265. /// If BaseGV is null, there is no BaseGV.
  2266. /// If BaseOffs is zero, there is no base offset.
  2267. /// If HasBaseReg is false, there is no base register.
  2268. /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
  2269. /// no scale.
  2270. struct AddrMode {
  2271. GlobalValue *BaseGV = nullptr;
  2272. int64_t BaseOffs = 0;
  2273. bool HasBaseReg = false;
  2274. int64_t Scale = 0;
  2275. AddrMode() = default;
  2276. };
  2277. /// Return true if the addressing mode represented by AM is legal for this
  2278. /// target, for a load/store of the specified type.
  2279. ///
  2280. /// The type may be VoidTy, in which case only return true if the addressing
  2281. /// mode is legal for a load/store of any legal type. TODO: Handle
  2282. /// pre/postinc as well.
  2283. ///
  2284. /// If the address space cannot be determined, it will be -1.
  2285. ///
  2286. /// TODO: Remove default argument
  2287. virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
  2288. Type *Ty, unsigned AddrSpace,
  2289. Instruction *I = nullptr) const;
  2290. /// Return true if the specified immediate is legal icmp immediate, that is
  2291. /// the target has icmp instructions which can compare a register against the
  2292. /// immediate without having to materialize the immediate into a register.
  2293. virtual bool isLegalICmpImmediate(int64_t) const {
  2294. return true;
  2295. }
  2296. /// Return true if the specified immediate is legal add immediate, that is the
  2297. /// target has add instructions which can add a register with the immediate
  2298. /// without having to materialize the immediate into a register.
  2299. virtual bool isLegalAddImmediate(int64_t) const {
  2300. return true;
  2301. }
  2302. /// Return true if the specified immediate is legal for the value input of a
  2303. /// store instruction.
  2304. virtual bool isLegalStoreImmediate(int64_t Value) const {
  2305. // Default implementation assumes that at least 0 works since it is likely
  2306. // that a zero register exists or a zero immediate is allowed.
  2307. return Value == 0;
  2308. }
  2309. /// Return true if it's significantly cheaper to shift a vector by a uniform
  2310. /// scalar than by an amount which will vary across each lane. On x86 before
  2311. /// AVX2 for example, there is a "psllw" instruction for the former case, but
  2312. /// no simple instruction for a general "a << b" operation on vectors.
  2313. /// This should also apply to lowering for vector funnel shifts (rotates).
  2314. virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
  2315. return false;
  2316. }
  2317. /// Given a shuffle vector SVI representing a vector splat, return a new
  2318. /// scalar type of size equal to SVI's scalar type if the new type is more
  2319. /// profitable. Returns nullptr otherwise. For example under MVE float splats
  2320. /// are converted to integer to prevent the need to move from SPR to GPR
  2321. /// registers.
  2322. virtual Type* shouldConvertSplatType(ShuffleVectorInst* SVI) const {
  2323. return nullptr;
  2324. }
  2325. /// Given a set in interconnected phis of type 'From' that are loaded/stored
  2326. /// or bitcast to type 'To', return true if the set should be converted to
  2327. /// 'To'.
  2328. virtual bool shouldConvertPhiType(Type *From, Type *To) const {
  2329. return (From->isIntegerTy() || From->isFloatingPointTy()) &&
  2330. (To->isIntegerTy() || To->isFloatingPointTy());
  2331. }
  2332. /// Returns true if the opcode is a commutative binary operation.
  2333. virtual bool isCommutativeBinOp(unsigned Opcode) const {
  2334. // FIXME: This should get its info from the td file.
  2335. switch (Opcode) {
  2336. case ISD::ADD:
  2337. case ISD::SMIN:
  2338. case ISD::SMAX:
  2339. case ISD::UMIN:
  2340. case ISD::UMAX:
  2341. case ISD::MUL:
  2342. case ISD::MULHU:
  2343. case ISD::MULHS:
  2344. case ISD::SMUL_LOHI:
  2345. case ISD::UMUL_LOHI:
  2346. case ISD::FADD:
  2347. case ISD::FMUL:
  2348. case ISD::AND:
  2349. case ISD::OR:
  2350. case ISD::XOR:
  2351. case ISD::SADDO:
  2352. case ISD::UADDO:
  2353. case ISD::ADDC:
  2354. case ISD::ADDE:
  2355. case ISD::SADDSAT:
  2356. case ISD::UADDSAT:
  2357. case ISD::FMINNUM:
  2358. case ISD::FMAXNUM:
  2359. case ISD::FMINNUM_IEEE:
  2360. case ISD::FMAXNUM_IEEE:
  2361. case ISD::FMINIMUM:
  2362. case ISD::FMAXIMUM:
  2363. case ISD::AVGFLOORS:
  2364. case ISD::AVGFLOORU:
  2365. case ISD::AVGCEILS:
  2366. case ISD::AVGCEILU:
  2367. return true;
  2368. default: return false;
  2369. }
  2370. }
  2371. /// Return true if the node is a math/logic binary operator.
  2372. virtual bool isBinOp(unsigned Opcode) const {
  2373. // A commutative binop must be a binop.
  2374. if (isCommutativeBinOp(Opcode))
  2375. return true;
  2376. // These are non-commutative binops.
  2377. switch (Opcode) {
  2378. case ISD::SUB:
  2379. case ISD::SHL:
  2380. case ISD::SRL:
  2381. case ISD::SRA:
  2382. case ISD::ROTL:
  2383. case ISD::ROTR:
  2384. case ISD::SDIV:
  2385. case ISD::UDIV:
  2386. case ISD::SREM:
  2387. case ISD::UREM:
  2388. case ISD::SSUBSAT:
  2389. case ISD::USUBSAT:
  2390. case ISD::FSUB:
  2391. case ISD::FDIV:
  2392. case ISD::FREM:
  2393. return true;
  2394. default:
  2395. return false;
  2396. }
  2397. }
  2398. /// Return true if it's free to truncate a value of type FromTy to type
  2399. /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
  2400. /// by referencing its sub-register AX.
  2401. /// Targets must return false when FromTy <= ToTy.
  2402. virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
  2403. return false;
  2404. }
  2405. /// Return true if a truncation from FromTy to ToTy is permitted when deciding
  2406. /// whether a call is in tail position. Typically this means that both results
  2407. /// would be assigned to the same register or stack slot, but it could mean
  2408. /// the target performs adequate checks of its own before proceeding with the
  2409. /// tail call. Targets must return false when FromTy <= ToTy.
  2410. virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
  2411. return false;
  2412. }
  2413. virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const { return false; }
  2414. virtual bool isTruncateFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
  2415. LLVMContext &Ctx) const {
  2416. return isTruncateFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
  2417. getApproximateEVTForLLT(ToTy, DL, Ctx));
  2418. }
  2419. virtual bool isProfitableToHoist(Instruction *I) const { return true; }
  2420. /// Return true if the extension represented by \p I is free.
  2421. /// Unlikely the is[Z|FP]ExtFree family which is based on types,
  2422. /// this method can use the context provided by \p I to decide
  2423. /// whether or not \p I is free.
  2424. /// This method extends the behavior of the is[Z|FP]ExtFree family.
  2425. /// In other words, if is[Z|FP]Free returns true, then this method
  2426. /// returns true as well. The converse is not true.
  2427. /// The target can perform the adequate checks by overriding isExtFreeImpl.
  2428. /// \pre \p I must be a sign, zero, or fp extension.
  2429. bool isExtFree(const Instruction *I) const {
  2430. switch (I->getOpcode()) {
  2431. case Instruction::FPExt:
  2432. if (isFPExtFree(EVT::getEVT(I->getType()),
  2433. EVT::getEVT(I->getOperand(0)->getType())))
  2434. return true;
  2435. break;
  2436. case Instruction::ZExt:
  2437. if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
  2438. return true;
  2439. break;
  2440. case Instruction::SExt:
  2441. break;
  2442. default:
  2443. llvm_unreachable("Instruction is not an extension");
  2444. }
  2445. return isExtFreeImpl(I);
  2446. }
  2447. /// Return true if \p Load and \p Ext can form an ExtLoad.
  2448. /// For example, in AArch64
  2449. /// %L = load i8, i8* %ptr
  2450. /// %E = zext i8 %L to i32
  2451. /// can be lowered into one load instruction
  2452. /// ldrb w0, [x0]
  2453. bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
  2454. const DataLayout &DL) const {
  2455. EVT VT = getValueType(DL, Ext->getType());
  2456. EVT LoadVT = getValueType(DL, Load->getType());
  2457. // If the load has other users and the truncate is not free, the ext
  2458. // probably isn't free.
  2459. if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
  2460. !isTruncateFree(Ext->getType(), Load->getType()))
  2461. return false;
  2462. // Check whether the target supports casts folded into loads.
  2463. unsigned LType;
  2464. if (isa<ZExtInst>(Ext))
  2465. LType = ISD::ZEXTLOAD;
  2466. else {
  2467. assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
  2468. LType = ISD::SEXTLOAD;
  2469. }
  2470. return isLoadExtLegal(LType, VT, LoadVT);
  2471. }
  2472. /// Return true if any actual instruction that defines a value of type FromTy
  2473. /// implicitly zero-extends the value to ToTy in the result register.
  2474. ///
  2475. /// The function should return true when it is likely that the truncate can
  2476. /// be freely folded with an instruction defining a value of FromTy. If
  2477. /// the defining instruction is unknown (because you're looking at a
  2478. /// function argument, PHI, etc.) then the target may require an
  2479. /// explicit truncate, which is not necessarily free, but this function
  2480. /// does not deal with those cases.
  2481. /// Targets must return false when FromTy >= ToTy.
  2482. virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
  2483. return false;
  2484. }
  2485. virtual bool isZExtFree(EVT FromTy, EVT ToTy) const { return false; }
  2486. virtual bool isZExtFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
  2487. LLVMContext &Ctx) const {
  2488. return isZExtFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
  2489. getApproximateEVTForLLT(ToTy, DL, Ctx));
  2490. }
  2491. /// Return true if sign-extension from FromTy to ToTy is cheaper than
  2492. /// zero-extension.
  2493. virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
  2494. return false;
  2495. }
  2496. /// Return true if this constant should be sign extended when promoting to
  2497. /// a larger type.
  2498. virtual bool signExtendConstant(const ConstantInt *C) const { return false; }
  2499. /// Return true if sinking I's operands to the same basic block as I is
  2500. /// profitable, e.g. because the operands can be folded into a target
  2501. /// instruction during instruction selection. After calling the function
  2502. /// \p Ops contains the Uses to sink ordered by dominance (dominating users
  2503. /// come first).
  2504. virtual bool shouldSinkOperands(Instruction *I,
  2505. SmallVectorImpl<Use *> &Ops) const {
  2506. return false;
  2507. }
  2508. /// Try to optimize extending or truncating conversion instructions (like
  2509. /// zext, trunc, fptoui, uitofp) for the target.
  2510. virtual bool optimizeExtendOrTruncateConversion(Instruction *I,
  2511. Loop *L) const {
  2512. return false;
  2513. }
  2514. /// Return true if the target supplies and combines to a paired load
  2515. /// two loaded values of type LoadedType next to each other in memory.
  2516. /// RequiredAlignment gives the minimal alignment constraints that must be met
  2517. /// to be able to select this paired load.
  2518. ///
  2519. /// This information is *not* used to generate actual paired loads, but it is
  2520. /// used to generate a sequence of loads that is easier to combine into a
  2521. /// paired load.
  2522. /// For instance, something like this:
  2523. /// a = load i64* addr
  2524. /// b = trunc i64 a to i32
  2525. /// c = lshr i64 a, 32
  2526. /// d = trunc i64 c to i32
  2527. /// will be optimized into:
  2528. /// b = load i32* addr1
  2529. /// d = load i32* addr2
  2530. /// Where addr1 = addr2 +/- sizeof(i32).
  2531. ///
  2532. /// In other words, unless the target performs a post-isel load combining,
  2533. /// this information should not be provided because it will generate more
  2534. /// loads.
  2535. virtual bool hasPairedLoad(EVT /*LoadedType*/,
  2536. Align & /*RequiredAlignment*/) const {
  2537. return false;
  2538. }
  2539. /// Return true if the target has a vector blend instruction.
  2540. virtual bool hasVectorBlend() const { return false; }
  2541. /// Get the maximum supported factor for interleaved memory accesses.
  2542. /// Default to be the minimum interleave factor: 2.
  2543. virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
  2544. /// Lower an interleaved load to target specific intrinsics. Return
  2545. /// true on success.
  2546. ///
  2547. /// \p LI is the vector load instruction.
  2548. /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
  2549. /// \p Indices is the corresponding indices for each shufflevector.
  2550. /// \p Factor is the interleave factor.
  2551. virtual bool lowerInterleavedLoad(LoadInst *LI,
  2552. ArrayRef<ShuffleVectorInst *> Shuffles,
  2553. ArrayRef<unsigned> Indices,
  2554. unsigned Factor) const {
  2555. return false;
  2556. }
  2557. /// Lower an interleaved store to target specific intrinsics. Return
  2558. /// true on success.
  2559. ///
  2560. /// \p SI is the vector store instruction.
  2561. /// \p SVI is the shufflevector to RE-interleave the stored vector.
  2562. /// \p Factor is the interleave factor.
  2563. virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
  2564. unsigned Factor) const {
  2565. return false;
  2566. }
  2567. /// Return true if zero-extending the specific node Val to type VT2 is free
  2568. /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
  2569. /// because it's folded such as X86 zero-extending loads).
  2570. virtual bool isZExtFree(SDValue Val, EVT VT2) const {
  2571. return isZExtFree(Val.getValueType(), VT2);
  2572. }
  2573. /// Return true if an fpext operation is free (for instance, because
  2574. /// single-precision floating-point numbers are implicitly extended to
  2575. /// double-precision).
  2576. virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
  2577. assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
  2578. "invalid fpext types");
  2579. return false;
  2580. }
  2581. /// Return true if an fpext operation input to an \p Opcode operation is free
  2582. /// (for instance, because half-precision floating-point numbers are
  2583. /// implicitly extended to float-precision) for an FMA instruction.
  2584. virtual bool isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
  2585. LLT DestTy, LLT SrcTy) const {
  2586. return false;
  2587. }
  2588. /// Return true if an fpext operation input to an \p Opcode operation is free
  2589. /// (for instance, because half-precision floating-point numbers are
  2590. /// implicitly extended to float-precision) for an FMA instruction.
  2591. virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
  2592. EVT DestVT, EVT SrcVT) const {
  2593. assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
  2594. "invalid fpext types");
  2595. return isFPExtFree(DestVT, SrcVT);
  2596. }
  2597. /// Return true if folding a vector load into ExtVal (a sign, zero, or any
  2598. /// extend node) is profitable.
  2599. virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
  2600. /// Return true if an fneg operation is free to the point where it is never
  2601. /// worthwhile to replace it with a bitwise operation.
  2602. virtual bool isFNegFree(EVT VT) const {
  2603. assert(VT.isFloatingPoint());
  2604. return false;
  2605. }
  2606. /// Return true if an fabs operation is free to the point where it is never
  2607. /// worthwhile to replace it with a bitwise operation.
  2608. virtual bool isFAbsFree(EVT VT) const {
  2609. assert(VT.isFloatingPoint());
  2610. return false;
  2611. }
  2612. /// Return true if an FMA operation is faster than a pair of fmul and fadd
  2613. /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
  2614. /// returns true, otherwise fmuladd is expanded to fmul + fadd.
  2615. ///
  2616. /// NOTE: This may be called before legalization on types for which FMAs are
  2617. /// not legal, but should return true if those types will eventually legalize
  2618. /// to types that support FMAs. After legalization, it will only be called on
  2619. /// types that support FMAs (via Legal or Custom actions)
  2620. virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
  2621. EVT) const {
  2622. return false;
  2623. }
  2624. /// Return true if an FMA operation is faster than a pair of fmul and fadd
  2625. /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
  2626. /// returns true, otherwise fmuladd is expanded to fmul + fadd.
  2627. ///
  2628. /// NOTE: This may be called before legalization on types for which FMAs are
  2629. /// not legal, but should return true if those types will eventually legalize
  2630. /// to types that support FMAs. After legalization, it will only be called on
  2631. /// types that support FMAs (via Legal or Custom actions)
  2632. virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
  2633. LLT) const {
  2634. return false;
  2635. }
  2636. /// IR version
  2637. virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
  2638. return false;
  2639. }
  2640. /// Returns true if \p MI can be combined with another instruction to
  2641. /// form TargetOpcode::G_FMAD. \p N may be an TargetOpcode::G_FADD,
  2642. /// TargetOpcode::G_FSUB, or an TargetOpcode::G_FMUL which will be
  2643. /// distributed into an fadd/fsub.
  2644. virtual bool isFMADLegal(const MachineInstr &MI, LLT Ty) const {
  2645. assert((MI.getOpcode() == TargetOpcode::G_FADD ||
  2646. MI.getOpcode() == TargetOpcode::G_FSUB ||
  2647. MI.getOpcode() == TargetOpcode::G_FMUL) &&
  2648. "unexpected node in FMAD forming combine");
  2649. switch (Ty.getScalarSizeInBits()) {
  2650. case 16:
  2651. return isOperationLegal(TargetOpcode::G_FMAD, MVT::f16);
  2652. case 32:
  2653. return isOperationLegal(TargetOpcode::G_FMAD, MVT::f32);
  2654. case 64:
  2655. return isOperationLegal(TargetOpcode::G_FMAD, MVT::f64);
  2656. default:
  2657. break;
  2658. }
  2659. return false;
  2660. }
  2661. /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
  2662. /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
  2663. /// fadd/fsub.
  2664. virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
  2665. assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
  2666. N->getOpcode() == ISD::FMUL) &&
  2667. "unexpected node in FMAD forming combine");
  2668. return isOperationLegal(ISD::FMAD, N->getValueType(0));
  2669. }
  2670. // Return true when the decision to generate FMA's (or FMS, FMLA etc) rather
  2671. // than FMUL and ADD is delegated to the machine combiner.
  2672. virtual bool generateFMAsInMachineCombiner(EVT VT,
  2673. CodeGenOpt::Level OptLevel) const {
  2674. return false;
  2675. }
  2676. /// Return true if it's profitable to narrow operations of type VT1 to
  2677. /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
  2678. /// i32 to i16.
  2679. virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
  2680. return false;
  2681. }
  2682. /// Return true if pulling a binary operation into a select with an identity
  2683. /// constant is profitable. This is the inverse of an IR transform.
  2684. /// Example: X + (Cond ? Y : 0) --> Cond ? (X + Y) : X
  2685. virtual bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode,
  2686. EVT VT) const {
  2687. return false;
  2688. }
  2689. /// Return true if it is beneficial to convert a load of a constant to
  2690. /// just the constant itself.
  2691. /// On some targets it might be more efficient to use a combination of
  2692. /// arithmetic instructions to materialize the constant instead of loading it
  2693. /// from a constant pool.
  2694. virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
  2695. Type *Ty) const {
  2696. return false;
  2697. }
  2698. /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
  2699. /// from this source type with this index. This is needed because
  2700. /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
  2701. /// the first element, and only the target knows which lowering is cheap.
  2702. virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
  2703. unsigned Index) const {
  2704. return false;
  2705. }
  2706. /// Try to convert an extract element of a vector binary operation into an
  2707. /// extract element followed by a scalar operation.
  2708. virtual bool shouldScalarizeBinop(SDValue VecOp) const {
  2709. return false;
  2710. }
  2711. /// Return true if extraction of a scalar element from the given vector type
  2712. /// at the given index is cheap. For example, if scalar operations occur on
  2713. /// the same register file as vector operations, then an extract element may
  2714. /// be a sub-register rename rather than an actual instruction.
  2715. virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
  2716. return false;
  2717. }
  2718. /// Try to convert math with an overflow comparison into the corresponding DAG
  2719. /// node operation. Targets may want to override this independently of whether
  2720. /// the operation is legal/custom for the given type because it may obscure
  2721. /// matching of other patterns.
  2722. virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
  2723. bool MathUsed) const {
  2724. // TODO: The default logic is inherited from code in CodeGenPrepare.
  2725. // The opcode should not make a difference by default?
  2726. if (Opcode != ISD::UADDO)
  2727. return false;
  2728. // Allow the transform as long as we have an integer type that is not
  2729. // obviously illegal and unsupported and if the math result is used
  2730. // besides the overflow check. On some targets (e.g. SPARC), it is
  2731. // not profitable to form on overflow op if the math result has no
  2732. // concrete users.
  2733. if (VT.isVector())
  2734. return false;
  2735. return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
  2736. }
  2737. // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
  2738. // even if the vector itself has multiple uses.
  2739. virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
  2740. return false;
  2741. }
  2742. // Return true if CodeGenPrepare should consider splitting large offset of a
  2743. // GEP to make the GEP fit into the addressing mode and can be sunk into the
  2744. // same blocks of its users.
  2745. virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
  2746. /// Return true if creating a shift of the type by the given
  2747. /// amount is not profitable.
  2748. virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
  2749. return false;
  2750. }
  2751. /// Does this target require the clearing of high-order bits in a register
  2752. /// passed to the fp16 to fp conversion library function.
  2753. virtual bool shouldKeepZExtForFP16Conv() const { return false; }
  2754. /// Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type VT
  2755. /// from min(max(fptoi)) saturation patterns.
  2756. virtual bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const {
  2757. return isOperationLegalOrCustom(Op, VT);
  2758. }
  2759. /// Does this target support complex deinterleaving
  2760. virtual bool isComplexDeinterleavingSupported() const { return false; }
  2761. /// Does this target support complex deinterleaving with the given operation
  2762. /// and type
  2763. virtual bool isComplexDeinterleavingOperationSupported(
  2764. ComplexDeinterleavingOperation Operation, Type *Ty) const {
  2765. return false;
  2766. }
  2767. /// Create the IR node for the given complex deinterleaving operation.
  2768. /// If one cannot be created using all the given inputs, nullptr should be
  2769. /// returned.
  2770. virtual Value *createComplexDeinterleavingIR(
  2771. Instruction *I, ComplexDeinterleavingOperation OperationType,
  2772. ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
  2773. Value *Accumulator = nullptr) const {
  2774. return nullptr;
  2775. }
  2776. //===--------------------------------------------------------------------===//
  2777. // Runtime Library hooks
  2778. //
  2779. /// Rename the default libcall routine name for the specified libcall.
  2780. void setLibcallName(RTLIB::Libcall Call, const char *Name) {
  2781. LibcallRoutineNames[Call] = Name;
  2782. }
  2783. void setLibcallName(ArrayRef<RTLIB::Libcall> Calls, const char *Name) {
  2784. for (auto Call : Calls)
  2785. setLibcallName(Call, Name);
  2786. }
  2787. /// Get the libcall routine name for the specified libcall.
  2788. const char *getLibcallName(RTLIB::Libcall Call) const {
  2789. return LibcallRoutineNames[Call];
  2790. }
  2791. /// Override the default CondCode to be used to test the result of the
  2792. /// comparison libcall against zero.
  2793. void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
  2794. CmpLibcallCCs[Call] = CC;
  2795. }
  2796. /// Get the CondCode that's to be used to test the result of the comparison
  2797. /// libcall against zero.
  2798. ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
  2799. return CmpLibcallCCs[Call];
  2800. }
  2801. /// Set the CallingConv that should be used for the specified libcall.
  2802. void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
  2803. LibcallCallingConvs[Call] = CC;
  2804. }
  2805. /// Get the CallingConv that should be used for the specified libcall.
  2806. CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
  2807. return LibcallCallingConvs[Call];
  2808. }
  2809. /// Execute target specific actions to finalize target lowering.
  2810. /// This is used to set extra flags in MachineFrameInformation and freezing
  2811. /// the set of reserved registers.
  2812. /// The default implementation just freezes the set of reserved registers.
  2813. virtual void finalizeLowering(MachineFunction &MF) const;
  2814. //===----------------------------------------------------------------------===//
  2815. // GlobalISel Hooks
  2816. //===----------------------------------------------------------------------===//
  2817. /// Check whether or not \p MI needs to be moved close to its uses.
  2818. virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
  2819. private:
  2820. const TargetMachine &TM;
  2821. /// Tells the code generator that the target has multiple (allocatable)
  2822. /// condition registers that can be used to store the results of comparisons
  2823. /// for use by selects and conditional branches. With multiple condition
  2824. /// registers, the code generator will not aggressively sink comparisons into
  2825. /// the blocks of their users.
  2826. bool HasMultipleConditionRegisters;
  2827. /// Tells the code generator that the target has BitExtract instructions.
  2828. /// The code generator will aggressively sink "shift"s into the blocks of
  2829. /// their users if the users will generate "and" instructions which can be
  2830. /// combined with "shift" to BitExtract instructions.
  2831. bool HasExtractBitsInsn;
  2832. /// Tells the code generator to bypass slow divide or remainder
  2833. /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
  2834. /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
  2835. /// div/rem when the operands are positive and less than 256.
  2836. DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
  2837. /// Tells the code generator that it shouldn't generate extra flow control
  2838. /// instructions and should attempt to combine flow control instructions via
  2839. /// predication.
  2840. bool JumpIsExpensive;
  2841. /// Information about the contents of the high-bits in boolean values held in
  2842. /// a type wider than i1. See getBooleanContents.
  2843. BooleanContent BooleanContents;
  2844. /// Information about the contents of the high-bits in boolean values held in
  2845. /// a type wider than i1. See getBooleanContents.
  2846. BooleanContent BooleanFloatContents;
  2847. /// Information about the contents of the high-bits in boolean vector values
  2848. /// when the element type is wider than i1. See getBooleanContents.
  2849. BooleanContent BooleanVectorContents;
  2850. /// The target scheduling preference: shortest possible total cycles or lowest
  2851. /// register usage.
  2852. Sched::Preference SchedPreferenceInfo;
  2853. /// The minimum alignment that any argument on the stack needs to have.
  2854. Align MinStackArgumentAlignment;
  2855. /// The minimum function alignment (used when optimizing for size, and to
  2856. /// prevent explicitly provided alignment from leading to incorrect code).
  2857. Align MinFunctionAlignment;
  2858. /// The preferred function alignment (used when alignment unspecified and
  2859. /// optimizing for speed).
  2860. Align PrefFunctionAlignment;
  2861. /// The preferred loop alignment (in log2 bot in bytes).
  2862. Align PrefLoopAlignment;
  2863. /// The maximum amount of bytes permitted to be emitted for alignment.
  2864. unsigned MaxBytesForAlignment;
  2865. /// Size in bits of the maximum atomics size the backend supports.
  2866. /// Accesses larger than this will be expanded by AtomicExpandPass.
  2867. unsigned MaxAtomicSizeInBitsSupported;
  2868. /// Size in bits of the maximum div/rem size the backend supports.
  2869. /// Larger operations will be expanded by ExpandLargeDivRem.
  2870. unsigned MaxDivRemBitWidthSupported;
  2871. /// Size in bits of the maximum larget fp convert size the backend
  2872. /// supports. Larger operations will be expanded by ExpandLargeFPConvert.
  2873. unsigned MaxLargeFPConvertBitWidthSupported;
  2874. /// Size in bits of the minimum cmpxchg or ll/sc operation the
  2875. /// backend supports.
  2876. unsigned MinCmpXchgSizeInBits;
  2877. /// This indicates if the target supports unaligned atomic operations.
  2878. bool SupportsUnalignedAtomics;
  2879. /// If set to a physical register, this specifies the register that
  2880. /// llvm.savestack/llvm.restorestack should save and restore.
  2881. Register StackPointerRegisterToSaveRestore;
  2882. /// This indicates the default register class to use for each ValueType the
  2883. /// target supports natively.
  2884. const TargetRegisterClass *RegClassForVT[MVT::VALUETYPE_SIZE];
  2885. uint16_t NumRegistersForVT[MVT::VALUETYPE_SIZE];
  2886. MVT RegisterTypeForVT[MVT::VALUETYPE_SIZE];
  2887. /// This indicates the "representative" register class to use for each
  2888. /// ValueType the target supports natively. This information is used by the
  2889. /// scheduler to track register pressure. By default, the representative
  2890. /// register class is the largest legal super-reg register class of the
  2891. /// register class of the specified type. e.g. On x86, i8, i16, and i32's
  2892. /// representative class would be GR32.
  2893. const TargetRegisterClass *RepRegClassForVT[MVT::VALUETYPE_SIZE];
  2894. /// This indicates the "cost" of the "representative" register class for each
  2895. /// ValueType. The cost is used by the scheduler to approximate register
  2896. /// pressure.
  2897. uint8_t RepRegClassCostForVT[MVT::VALUETYPE_SIZE];
  2898. /// For any value types we are promoting or expanding, this contains the value
  2899. /// type that we are changing to. For Expanded types, this contains one step
  2900. /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
  2901. /// (e.g. i64 -> i16). For types natively supported by the system, this holds
  2902. /// the same type (e.g. i32 -> i32).
  2903. MVT TransformToType[MVT::VALUETYPE_SIZE];
  2904. /// For each operation and each value type, keep a LegalizeAction that
  2905. /// indicates how instruction selection should deal with the operation. Most
  2906. /// operations are Legal (aka, supported natively by the target), but
  2907. /// operations that are not should be described. Note that operations on
  2908. /// non-legal value types are not described here.
  2909. LegalizeAction OpActions[MVT::VALUETYPE_SIZE][ISD::BUILTIN_OP_END];
  2910. /// For each load extension type and each value type, keep a LegalizeAction
  2911. /// that indicates how instruction selection should deal with a load of a
  2912. /// specific value type and extension type. Uses 4-bits to store the action
  2913. /// for each of the 4 load ext types.
  2914. uint16_t LoadExtActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
  2915. /// For each value type pair keep a LegalizeAction that indicates whether a
  2916. /// truncating store of a specific value type and truncating type is legal.
  2917. LegalizeAction TruncStoreActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
  2918. /// For each indexed mode and each value type, keep a quad of LegalizeAction
  2919. /// that indicates how instruction selection should deal with the load /
  2920. /// store / maskedload / maskedstore.
  2921. ///
  2922. /// The first dimension is the value_type for the reference. The second
  2923. /// dimension represents the various modes for load store.
  2924. uint16_t IndexedModeActions[MVT::VALUETYPE_SIZE][ISD::LAST_INDEXED_MODE];
  2925. /// For each condition code (ISD::CondCode) keep a LegalizeAction that
  2926. /// indicates how instruction selection should deal with the condition code.
  2927. ///
  2928. /// Because each CC action takes up 4 bits, we need to have the array size be
  2929. /// large enough to fit all of the value types. This can be done by rounding
  2930. /// up the MVT::VALUETYPE_SIZE value to the next multiple of 8.
  2931. uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::VALUETYPE_SIZE + 7) / 8];
  2932. ValueTypeActionImpl ValueTypeActions;
  2933. private:
  2934. /// Targets can specify ISD nodes that they would like PerformDAGCombine
  2935. /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
  2936. /// array.
  2937. unsigned char
  2938. TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
  2939. /// For operations that must be promoted to a specific type, this holds the
  2940. /// destination type. This map should be sparse, so don't hold it as an
  2941. /// array.
  2942. ///
  2943. /// Targets add entries to this map with AddPromotedToType(..), clients access
  2944. /// this with getTypeToPromoteTo(..).
  2945. std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
  2946. PromoteToType;
  2947. /// Stores the name each libcall.
  2948. const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
  2949. /// The ISD::CondCode that should be used to test the result of each of the
  2950. /// comparison libcall against zero.
  2951. ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
  2952. /// Stores the CallingConv that should be used for each libcall.
  2953. CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
  2954. /// Set default libcall names and calling conventions.
  2955. void InitLibcalls(const Triple &TT);
  2956. /// The bits of IndexedModeActions used to store the legalisation actions
  2957. /// We store the data as | ML | MS | L | S | each taking 4 bits.
  2958. enum IndexedModeActionsBits {
  2959. IMAB_Store = 0,
  2960. IMAB_Load = 4,
  2961. IMAB_MaskedStore = 8,
  2962. IMAB_MaskedLoad = 12
  2963. };
  2964. void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
  2965. LegalizeAction Action) {
  2966. assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
  2967. (unsigned)Action < 0xf && "Table isn't big enough!");
  2968. unsigned Ty = (unsigned)VT.SimpleTy;
  2969. IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
  2970. IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
  2971. }
  2972. LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
  2973. unsigned Shift) const {
  2974. assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
  2975. "Table isn't big enough!");
  2976. unsigned Ty = (unsigned)VT.SimpleTy;
  2977. return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
  2978. }
  2979. protected:
  2980. /// Return true if the extension represented by \p I is free.
  2981. /// \pre \p I is a sign, zero, or fp extension and
  2982. /// is[Z|FP]ExtFree of the related types is not true.
  2983. virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
  2984. /// Depth that GatherAllAliases should should continue looking for chain
  2985. /// dependencies when trying to find a more preferable chain. As an
  2986. /// approximation, this should be more than the number of consecutive stores
  2987. /// expected to be merged.
  2988. unsigned GatherAllAliasesMaxDepth;
  2989. /// \brief Specify maximum number of store instructions per memset call.
  2990. ///
  2991. /// When lowering \@llvm.memset this field specifies the maximum number of
  2992. /// store operations that may be substituted for the call to memset. Targets
  2993. /// must set this value based on the cost threshold for that target. Targets
  2994. /// should assume that the memset will be done using as many of the largest
  2995. /// store operations first, followed by smaller ones, if necessary, per
  2996. /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
  2997. /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
  2998. /// store. This only applies to setting a constant array of a constant size.
  2999. unsigned MaxStoresPerMemset;
  3000. /// Likewise for functions with the OptSize attribute.
  3001. unsigned MaxStoresPerMemsetOptSize;
  3002. /// \brief Specify maximum number of store instructions per memcpy call.
  3003. ///
  3004. /// When lowering \@llvm.memcpy this field specifies the maximum number of
  3005. /// store operations that may be substituted for a call to memcpy. Targets
  3006. /// must set this value based on the cost threshold for that target. Targets
  3007. /// should assume that the memcpy will be done using as many of the largest
  3008. /// store operations first, followed by smaller ones, if necessary, per
  3009. /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
  3010. /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
  3011. /// and one 1-byte store. This only applies to copying a constant array of
  3012. /// constant size.
  3013. unsigned MaxStoresPerMemcpy;
  3014. /// Likewise for functions with the OptSize attribute.
  3015. unsigned MaxStoresPerMemcpyOptSize;
  3016. /// \brief Specify max number of store instructions to glue in inlined memcpy.
  3017. ///
  3018. /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
  3019. /// of store instructions to keep together. This helps in pairing and
  3020. // vectorization later on.
  3021. unsigned MaxGluedStoresPerMemcpy = 0;
  3022. /// \brief Specify maximum number of load instructions per memcmp call.
  3023. ///
  3024. /// When lowering \@llvm.memcmp this field specifies the maximum number of
  3025. /// pairs of load operations that may be substituted for a call to memcmp.
  3026. /// Targets must set this value based on the cost threshold for that target.
  3027. /// Targets should assume that the memcmp will be done using as many of the
  3028. /// largest load operations first, followed by smaller ones, if necessary, per
  3029. /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
  3030. /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
  3031. /// and one 1-byte load. This only applies to copying a constant array of
  3032. /// constant size.
  3033. unsigned MaxLoadsPerMemcmp;
  3034. /// Likewise for functions with the OptSize attribute.
  3035. unsigned MaxLoadsPerMemcmpOptSize;
  3036. /// \brief Specify maximum number of store instructions per memmove call.
  3037. ///
  3038. /// When lowering \@llvm.memmove this field specifies the maximum number of
  3039. /// store instructions that may be substituted for a call to memmove. Targets
  3040. /// must set this value based on the cost threshold for that target. Targets
  3041. /// should assume that the memmove will be done using as many of the largest
  3042. /// store operations first, followed by smaller ones, if necessary, per
  3043. /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
  3044. /// with 8-bit alignment would result in nine 1-byte stores. This only
  3045. /// applies to copying a constant array of constant size.
  3046. unsigned MaxStoresPerMemmove;
  3047. /// Likewise for functions with the OptSize attribute.
  3048. unsigned MaxStoresPerMemmoveOptSize;
  3049. /// Tells the code generator that select is more expensive than a branch if
  3050. /// the branch is usually predicted right.
  3051. bool PredictableSelectIsExpensive;
  3052. /// \see enableExtLdPromotion.
  3053. bool EnableExtLdPromotion;
  3054. /// Return true if the value types that can be represented by the specified
  3055. /// register class are all legal.
  3056. bool isLegalRC(const TargetRegisterInfo &TRI,
  3057. const TargetRegisterClass &RC) const;
  3058. /// Replace/modify any TargetFrameIndex operands with a targte-dependent
  3059. /// sequence of memory operands that is recognized by PrologEpilogInserter.
  3060. MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
  3061. MachineBasicBlock *MBB) const;
  3062. bool IsStrictFPEnabled;
  3063. };
  3064. /// This class defines information used to lower LLVM code to legal SelectionDAG
  3065. /// operators that the target instruction selector can accept natively.
  3066. ///
  3067. /// This class also defines callbacks that targets must implement to lower
  3068. /// target-specific constructs to SelectionDAG operators.
  3069. class TargetLowering : public TargetLoweringBase {
  3070. public:
  3071. struct DAGCombinerInfo;
  3072. struct MakeLibCallOptions;
  3073. TargetLowering(const TargetLowering &) = delete;
  3074. TargetLowering &operator=(const TargetLowering &) = delete;
  3075. explicit TargetLowering(const TargetMachine &TM);
  3076. bool isPositionIndependent() const;
  3077. virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
  3078. FunctionLoweringInfo *FLI,
  3079. LegacyDivergenceAnalysis *DA) const {
  3080. return false;
  3081. }
  3082. // Lets target to control the following reassociation of operands: (op (op x,
  3083. // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
  3084. // default consider profitable any case where N0 has single use. This
  3085. // behavior reflects the condition replaced by this target hook call in the
  3086. // DAGCombiner. Any particular target can implement its own heuristic to
  3087. // restrict common combiner.
  3088. virtual bool isReassocProfitable(SelectionDAG &DAG, SDValue N0,
  3089. SDValue N1) const {
  3090. return N0.hasOneUse();
  3091. }
  3092. virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
  3093. return false;
  3094. }
  3095. /// Returns true by value, base pointer and offset pointer and addressing mode
  3096. /// by reference if the node's address can be legally represented as
  3097. /// pre-indexed load / store address.
  3098. virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
  3099. SDValue &/*Offset*/,
  3100. ISD::MemIndexedMode &/*AM*/,
  3101. SelectionDAG &/*DAG*/) const {
  3102. return false;
  3103. }
  3104. /// Returns true by value, base pointer and offset pointer and addressing mode
  3105. /// by reference if this node can be combined with a load / store to form a
  3106. /// post-indexed load / store.
  3107. virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
  3108. SDValue &/*Base*/,
  3109. SDValue &/*Offset*/,
  3110. ISD::MemIndexedMode &/*AM*/,
  3111. SelectionDAG &/*DAG*/) const {
  3112. return false;
  3113. }
  3114. /// Returns true if the specified base+offset is a legal indexed addressing
  3115. /// mode for this target. \p MI is the load or store instruction that is being
  3116. /// considered for transformation.
  3117. virtual bool isIndexingLegal(MachineInstr &MI, Register Base, Register Offset,
  3118. bool IsPre, MachineRegisterInfo &MRI) const {
  3119. return false;
  3120. }
  3121. /// Return the entry encoding for a jump table in the current function. The
  3122. /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
  3123. virtual unsigned getJumpTableEncoding() const;
  3124. virtual const MCExpr *
  3125. LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
  3126. const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
  3127. MCContext &/*Ctx*/) const {
  3128. llvm_unreachable("Need to implement this hook if target has custom JTIs");
  3129. }
  3130. /// Returns relocation base for the given PIC jumptable.
  3131. virtual SDValue getPICJumpTableRelocBase(SDValue Table,
  3132. SelectionDAG &DAG) const;
  3133. /// This returns the relocation base for the given PIC jumptable, the same as
  3134. /// getPICJumpTableRelocBase, but as an MCExpr.
  3135. virtual const MCExpr *
  3136. getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
  3137. unsigned JTI, MCContext &Ctx) const;
  3138. /// Return true if folding a constant offset with the given GlobalAddress is
  3139. /// legal. It is frequently not legal in PIC relocation models.
  3140. virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
  3141. /// Return true if the operand with index OpNo corresponding to a target
  3142. /// branch, for example, in following case
  3143. ///
  3144. /// call void asm "lea r8, $0\0A\09call qword ptr ${1:P}\0A\09ret",
  3145. /// "*m,*m,~{r8},~{dirflag},~{fpsr},~{flags}"
  3146. /// ([9 x i32]* @Arr), void (...)* @sincos_asm)
  3147. ///
  3148. /// the operand $1 (sincos_asm) is target branch in inline asm, but the
  3149. /// operand $0 (Arr) is not.
  3150. virtual bool
  3151. isInlineAsmTargetBranch(const SmallVectorImpl<StringRef> &AsmStrs,
  3152. unsigned OpNo) const {
  3153. return false;
  3154. }
  3155. bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
  3156. SDValue &Chain) const;
  3157. void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
  3158. SDValue &NewRHS, ISD::CondCode &CCCode,
  3159. const SDLoc &DL, const SDValue OldLHS,
  3160. const SDValue OldRHS) const;
  3161. void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
  3162. SDValue &NewRHS, ISD::CondCode &CCCode,
  3163. const SDLoc &DL, const SDValue OldLHS,
  3164. const SDValue OldRHS, SDValue &Chain,
  3165. bool IsSignaling = false) const;
  3166. /// Returns a pair of (return value, chain).
  3167. /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
  3168. std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
  3169. EVT RetVT, ArrayRef<SDValue> Ops,
  3170. MakeLibCallOptions CallOptions,
  3171. const SDLoc &dl,
  3172. SDValue Chain = SDValue()) const;
  3173. /// Check whether parameters to a call that are passed in callee saved
  3174. /// registers are the same as from the calling function. This needs to be
  3175. /// checked for tail call eligibility.
  3176. bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
  3177. const uint32_t *CallerPreservedMask,
  3178. const SmallVectorImpl<CCValAssign> &ArgLocs,
  3179. const SmallVectorImpl<SDValue> &OutVals) const;
  3180. //===--------------------------------------------------------------------===//
  3181. // TargetLowering Optimization Methods
  3182. //
  3183. /// A convenience struct that encapsulates a DAG, and two SDValues for
  3184. /// returning information from TargetLowering to its clients that want to
  3185. /// combine.
  3186. struct TargetLoweringOpt {
  3187. SelectionDAG &DAG;
  3188. bool LegalTys;
  3189. bool LegalOps;
  3190. SDValue Old;
  3191. SDValue New;
  3192. explicit TargetLoweringOpt(SelectionDAG &InDAG,
  3193. bool LT, bool LO) :
  3194. DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
  3195. bool LegalTypes() const { return LegalTys; }
  3196. bool LegalOperations() const { return LegalOps; }
  3197. bool CombineTo(SDValue O, SDValue N) {
  3198. Old = O;
  3199. New = N;
  3200. return true;
  3201. }
  3202. };
  3203. /// Determines the optimal series of memory ops to replace the memset / memcpy.
  3204. /// Return true if the number of memory ops is below the threshold (Limit).
  3205. /// Note that this is always the case when Limit is ~0.
  3206. /// It returns the types of the sequence of memory ops to perform
  3207. /// memset / memcpy by reference.
  3208. virtual bool
  3209. findOptimalMemOpLowering(std::vector<EVT> &MemOps, unsigned Limit,
  3210. const MemOp &Op, unsigned DstAS, unsigned SrcAS,
  3211. const AttributeList &FuncAttributes) const;
  3212. /// Check to see if the specified operand of the specified instruction is a
  3213. /// constant integer. If so, check to see if there are any bits set in the
  3214. /// constant that are not demanded. If so, shrink the constant and return
  3215. /// true.
  3216. bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
  3217. const APInt &DemandedElts,
  3218. TargetLoweringOpt &TLO) const;
  3219. /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
  3220. bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
  3221. TargetLoweringOpt &TLO) const;
  3222. // Target hook to do target-specific const optimization, which is called by
  3223. // ShrinkDemandedConstant. This function should return true if the target
  3224. // doesn't want ShrinkDemandedConstant to further optimize the constant.
  3225. virtual bool targetShrinkDemandedConstant(SDValue Op,
  3226. const APInt &DemandedBits,
  3227. const APInt &DemandedElts,
  3228. TargetLoweringOpt &TLO) const {
  3229. return false;
  3230. }
  3231. /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
  3232. /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
  3233. /// generalized for targets with other types of implicit widening casts.
  3234. bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
  3235. TargetLoweringOpt &TLO) const;
  3236. /// Look at Op. At this point, we know that only the DemandedBits bits of the
  3237. /// result of Op are ever used downstream. If we can use this information to
  3238. /// simplify Op, create a new simplified DAG node and return true, returning
  3239. /// the original and new nodes in Old and New. Otherwise, analyze the
  3240. /// expression and return a mask of KnownOne and KnownZero bits for the
  3241. /// expression (used to simplify the caller). The KnownZero/One bits may only
  3242. /// be accurate for those bits in the Demanded masks.
  3243. /// \p AssumeSingleUse When this parameter is true, this function will
  3244. /// attempt to simplify \p Op even if there are multiple uses.
  3245. /// Callers are responsible for correctly updating the DAG based on the
  3246. /// results of this function, because simply replacing replacing TLO.Old
  3247. /// with TLO.New will be incorrect when this parameter is true and TLO.Old
  3248. /// has multiple uses.
  3249. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  3250. const APInt &DemandedElts, KnownBits &Known,
  3251. TargetLoweringOpt &TLO, unsigned Depth = 0,
  3252. bool AssumeSingleUse = false) const;
  3253. /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
  3254. /// Adds Op back to the worklist upon success.
  3255. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  3256. KnownBits &Known, TargetLoweringOpt &TLO,
  3257. unsigned Depth = 0,
  3258. bool AssumeSingleUse = false) const;
  3259. /// Helper wrapper around SimplifyDemandedBits.
  3260. /// Adds Op back to the worklist upon success.
  3261. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  3262. DAGCombinerInfo &DCI) const;
  3263. /// Helper wrapper around SimplifyDemandedBits.
  3264. /// Adds Op back to the worklist upon success.
  3265. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  3266. const APInt &DemandedElts,
  3267. DAGCombinerInfo &DCI) const;
  3268. /// More limited version of SimplifyDemandedBits that can be used to "look
  3269. /// through" ops that don't contribute to the DemandedBits/DemandedElts -
  3270. /// bitwise ops etc.
  3271. SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
  3272. const APInt &DemandedElts,
  3273. SelectionDAG &DAG,
  3274. unsigned Depth = 0) const;
  3275. /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
  3276. /// elements.
  3277. SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
  3278. SelectionDAG &DAG,
  3279. unsigned Depth = 0) const;
  3280. /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
  3281. /// bits from only some vector elements.
  3282. SDValue SimplifyMultipleUseDemandedVectorElts(SDValue Op,
  3283. const APInt &DemandedElts,
  3284. SelectionDAG &DAG,
  3285. unsigned Depth = 0) const;
  3286. /// Look at Vector Op. At this point, we know that only the DemandedElts
  3287. /// elements of the result of Op are ever used downstream. If we can use
  3288. /// this information to simplify Op, create a new simplified DAG node and
  3289. /// return true, storing the original and new nodes in TLO.
  3290. /// Otherwise, analyze the expression and return a mask of KnownUndef and
  3291. /// KnownZero elements for the expression (used to simplify the caller).
  3292. /// The KnownUndef/Zero elements may only be accurate for those bits
  3293. /// in the DemandedMask.
  3294. /// \p AssumeSingleUse When this parameter is true, this function will
  3295. /// attempt to simplify \p Op even if there are multiple uses.
  3296. /// Callers are responsible for correctly updating the DAG based on the
  3297. /// results of this function, because simply replacing replacing TLO.Old
  3298. /// with TLO.New will be incorrect when this parameter is true and TLO.Old
  3299. /// has multiple uses.
  3300. bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
  3301. APInt &KnownUndef, APInt &KnownZero,
  3302. TargetLoweringOpt &TLO, unsigned Depth = 0,
  3303. bool AssumeSingleUse = false) const;
  3304. /// Helper wrapper around SimplifyDemandedVectorElts.
  3305. /// Adds Op back to the worklist upon success.
  3306. bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
  3307. DAGCombinerInfo &DCI) const;
  3308. /// Return true if the target supports simplifying demanded vector elements by
  3309. /// converting them to undefs.
  3310. virtual bool
  3311. shouldSimplifyDemandedVectorElts(SDValue Op,
  3312. const TargetLoweringOpt &TLO) const {
  3313. return true;
  3314. }
  3315. /// Determine which of the bits specified in Mask are known to be either zero
  3316. /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
  3317. /// argument allows us to only collect the known bits that are shared by the
  3318. /// requested vector elements.
  3319. virtual void computeKnownBitsForTargetNode(const SDValue Op,
  3320. KnownBits &Known,
  3321. const APInt &DemandedElts,
  3322. const SelectionDAG &DAG,
  3323. unsigned Depth = 0) const;
  3324. /// Determine which of the bits specified in Mask are known to be either zero
  3325. /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
  3326. /// argument allows us to only collect the known bits that are shared by the
  3327. /// requested vector elements. This is for GISel.
  3328. virtual void computeKnownBitsForTargetInstr(GISelKnownBits &Analysis,
  3329. Register R, KnownBits &Known,
  3330. const APInt &DemandedElts,
  3331. const MachineRegisterInfo &MRI,
  3332. unsigned Depth = 0) const;
  3333. /// Determine the known alignment for the pointer value \p R. This is can
  3334. /// typically be inferred from the number of low known 0 bits. However, for a
  3335. /// pointer with a non-integral address space, the alignment value may be
  3336. /// independent from the known low bits.
  3337. virtual Align computeKnownAlignForTargetInstr(GISelKnownBits &Analysis,
  3338. Register R,
  3339. const MachineRegisterInfo &MRI,
  3340. unsigned Depth = 0) const;
  3341. /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
  3342. /// Default implementation computes low bits based on alignment
  3343. /// information. This should preserve known bits passed into it.
  3344. virtual void computeKnownBitsForFrameIndex(int FIOp,
  3345. KnownBits &Known,
  3346. const MachineFunction &MF) const;
  3347. /// This method can be implemented by targets that want to expose additional
  3348. /// information about sign bits to the DAG Combiner. The DemandedElts
  3349. /// argument allows us to only collect the minimum sign bits that are shared
  3350. /// by the requested vector elements.
  3351. virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
  3352. const APInt &DemandedElts,
  3353. const SelectionDAG &DAG,
  3354. unsigned Depth = 0) const;
  3355. /// This method can be implemented by targets that want to expose additional
  3356. /// information about sign bits to GlobalISel combiners. The DemandedElts
  3357. /// argument allows us to only collect the minimum sign bits that are shared
  3358. /// by the requested vector elements.
  3359. virtual unsigned computeNumSignBitsForTargetInstr(GISelKnownBits &Analysis,
  3360. Register R,
  3361. const APInt &DemandedElts,
  3362. const MachineRegisterInfo &MRI,
  3363. unsigned Depth = 0) const;
  3364. /// Attempt to simplify any target nodes based on the demanded vector
  3365. /// elements, returning true on success. Otherwise, analyze the expression and
  3366. /// return a mask of KnownUndef and KnownZero elements for the expression
  3367. /// (used to simplify the caller). The KnownUndef/Zero elements may only be
  3368. /// accurate for those bits in the DemandedMask.
  3369. virtual bool SimplifyDemandedVectorEltsForTargetNode(
  3370. SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
  3371. APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
  3372. /// Attempt to simplify any target nodes based on the demanded bits/elts,
  3373. /// returning true on success. Otherwise, analyze the
  3374. /// expression and return a mask of KnownOne and KnownZero bits for the
  3375. /// expression (used to simplify the caller). The KnownZero/One bits may only
  3376. /// be accurate for those bits in the Demanded masks.
  3377. virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op,
  3378. const APInt &DemandedBits,
  3379. const APInt &DemandedElts,
  3380. KnownBits &Known,
  3381. TargetLoweringOpt &TLO,
  3382. unsigned Depth = 0) const;
  3383. /// More limited version of SimplifyDemandedBits that can be used to "look
  3384. /// through" ops that don't contribute to the DemandedBits/DemandedElts -
  3385. /// bitwise ops etc.
  3386. virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(
  3387. SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
  3388. SelectionDAG &DAG, unsigned Depth) const;
  3389. /// Return true if this function can prove that \p Op is never poison
  3390. /// and, if \p PoisonOnly is false, does not have undef bits. The DemandedElts
  3391. /// argument limits the check to the requested vector elements.
  3392. virtual bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(
  3393. SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
  3394. bool PoisonOnly, unsigned Depth) const;
  3395. /// Return true if Op can create undef or poison from non-undef & non-poison
  3396. /// operands. The DemandedElts argument limits the check to the requested
  3397. /// vector elements.
  3398. virtual bool
  3399. canCreateUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts,
  3400. const SelectionDAG &DAG, bool PoisonOnly,
  3401. bool ConsiderFlags, unsigned Depth) const;
  3402. /// Tries to build a legal vector shuffle using the provided parameters
  3403. /// or equivalent variations. The Mask argument maybe be modified as the
  3404. /// function tries different variations.
  3405. /// Returns an empty SDValue if the operation fails.
  3406. SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
  3407. SDValue N1, MutableArrayRef<int> Mask,
  3408. SelectionDAG &DAG) const;
  3409. /// This method returns the constant pool value that will be loaded by LD.
  3410. /// NOTE: You must check for implicit extensions of the constant by LD.
  3411. virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
  3412. /// If \p SNaN is false, \returns true if \p Op is known to never be any
  3413. /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
  3414. /// NaN.
  3415. virtual bool isKnownNeverNaNForTargetNode(SDValue Op,
  3416. const SelectionDAG &DAG,
  3417. bool SNaN = false,
  3418. unsigned Depth = 0) const;
  3419. /// Return true if vector \p Op has the same value across all \p DemandedElts,
  3420. /// indicating any elements which may be undef in the output \p UndefElts.
  3421. virtual bool isSplatValueForTargetNode(SDValue Op, const APInt &DemandedElts,
  3422. APInt &UndefElts,
  3423. const SelectionDAG &DAG,
  3424. unsigned Depth = 0) const;
  3425. /// Returns true if the given Opc is considered a canonical constant for the
  3426. /// target, which should not be transformed back into a BUILD_VECTOR.
  3427. virtual bool isTargetCanonicalConstantNode(SDValue Op) const {
  3428. return Op.getOpcode() == ISD::SPLAT_VECTOR;
  3429. }
  3430. struct DAGCombinerInfo {
  3431. void *DC; // The DAG Combiner object.
  3432. CombineLevel Level;
  3433. bool CalledByLegalizer;
  3434. public:
  3435. SelectionDAG &DAG;
  3436. DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
  3437. : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
  3438. bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
  3439. bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
  3440. bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
  3441. CombineLevel getDAGCombineLevel() { return Level; }
  3442. bool isCalledByLegalizer() const { return CalledByLegalizer; }
  3443. void AddToWorklist(SDNode *N);
  3444. SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
  3445. SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
  3446. SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
  3447. bool recursivelyDeleteUnusedNodes(SDNode *N);
  3448. void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
  3449. };
  3450. /// Return if the N is a constant or constant vector equal to the true value
  3451. /// from getBooleanContents().
  3452. bool isConstTrueVal(SDValue N) const;
  3453. /// Return if the N is a constant or constant vector equal to the false value
  3454. /// from getBooleanContents().
  3455. bool isConstFalseVal(SDValue N) const;
  3456. /// Return if \p N is a True value when extended to \p VT.
  3457. bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
  3458. /// Try to simplify a setcc built with the specified operands and cc. If it is
  3459. /// unable to simplify it, return a null SDValue.
  3460. SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
  3461. bool foldBooleans, DAGCombinerInfo &DCI,
  3462. const SDLoc &dl) const;
  3463. // For targets which wrap address, unwrap for analysis.
  3464. virtual SDValue unwrapAddress(SDValue N) const { return N; }
  3465. /// Returns true (and the GlobalValue and the offset) if the node is a
  3466. /// GlobalAddress + offset.
  3467. virtual bool
  3468. isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
  3469. /// This method will be invoked for all target nodes and for any
  3470. /// target-independent nodes that the target has registered with invoke it
  3471. /// for.
  3472. ///
  3473. /// The semantics are as follows:
  3474. /// Return Value:
  3475. /// SDValue.Val == 0 - No change was made
  3476. /// SDValue.Val == N - N was replaced, is dead, and is already handled.
  3477. /// otherwise - N should be replaced by the returned Operand.
  3478. ///
  3479. /// In addition, methods provided by DAGCombinerInfo may be used to perform
  3480. /// more complex transformations.
  3481. ///
  3482. virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
  3483. /// Return true if it is profitable to move this shift by a constant amount
  3484. /// through its operand, adjusting any immediate operands as necessary to
  3485. /// preserve semantics. This transformation may not be desirable if it
  3486. /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
  3487. /// extraction in AArch64). By default, it returns true.
  3488. ///
  3489. /// @param N the shift node
  3490. /// @param Level the current DAGCombine legalization level.
  3491. virtual bool isDesirableToCommuteWithShift(const SDNode *N,
  3492. CombineLevel Level) const {
  3493. return true;
  3494. }
  3495. /// Return true if it is profitable to combine an XOR of a logical shift
  3496. /// to create a logical shift of NOT. This transformation may not be desirable
  3497. /// if it disrupts a particularly auspicious target-specific tree (e.g.
  3498. /// BIC on ARM/AArch64). By default, it returns true.
  3499. virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const {
  3500. return true;
  3501. }
  3502. /// Return true if the target has native support for the specified value type
  3503. /// and it is 'desirable' to use the type for the given node type. e.g. On x86
  3504. /// i16 is legal, but undesirable since i16 instruction encodings are longer
  3505. /// and some i16 instructions are slow.
  3506. virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
  3507. // By default, assume all legal types are desirable.
  3508. return isTypeLegal(VT);
  3509. }
  3510. /// Return true if it is profitable for dag combiner to transform a floating
  3511. /// point op of specified opcode to a equivalent op of an integer
  3512. /// type. e.g. f32 load -> i32 load can be profitable on ARM.
  3513. virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
  3514. EVT /*VT*/) const {
  3515. return false;
  3516. }
  3517. /// This method query the target whether it is beneficial for dag combiner to
  3518. /// promote the specified node. If true, it should return the desired
  3519. /// promotion type by reference.
  3520. virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
  3521. return false;
  3522. }
  3523. /// Return true if the target supports swifterror attribute. It optimizes
  3524. /// loads and stores to reading and writing a specific register.
  3525. virtual bool supportSwiftError() const {
  3526. return false;
  3527. }
  3528. /// Return true if the target supports that a subset of CSRs for the given
  3529. /// machine function is handled explicitly via copies.
  3530. virtual bool supportSplitCSR(MachineFunction *MF) const {
  3531. return false;
  3532. }
  3533. /// Return true if the target supports kcfi operand bundles.
  3534. virtual bool supportKCFIBundles() const { return false; }
  3535. /// Perform necessary initialization to handle a subset of CSRs explicitly
  3536. /// via copies. This function is called at the beginning of instruction
  3537. /// selection.
  3538. virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
  3539. llvm_unreachable("Not Implemented");
  3540. }
  3541. /// Insert explicit copies in entry and exit blocks. We copy a subset of
  3542. /// CSRs to virtual registers in the entry block, and copy them back to
  3543. /// physical registers in the exit blocks. This function is called at the end
  3544. /// of instruction selection.
  3545. virtual void insertCopiesSplitCSR(
  3546. MachineBasicBlock *Entry,
  3547. const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
  3548. llvm_unreachable("Not Implemented");
  3549. }
  3550. /// Return the newly negated expression if the cost is not expensive and
  3551. /// set the cost in \p Cost to indicate that if it is cheaper or neutral to
  3552. /// do the negation.
  3553. virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG,
  3554. bool LegalOps, bool OptForSize,
  3555. NegatibleCost &Cost,
  3556. unsigned Depth = 0) const;
  3557. SDValue getCheaperOrNeutralNegatedExpression(
  3558. SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize,
  3559. const NegatibleCost CostThreshold = NegatibleCost::Neutral,
  3560. unsigned Depth = 0) const {
  3561. NegatibleCost Cost = NegatibleCost::Expensive;
  3562. SDValue Neg =
  3563. getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
  3564. if (!Neg)
  3565. return SDValue();
  3566. if (Cost <= CostThreshold)
  3567. return Neg;
  3568. // Remove the new created node to avoid the side effect to the DAG.
  3569. if (Neg->use_empty())
  3570. DAG.RemoveDeadNode(Neg.getNode());
  3571. return SDValue();
  3572. }
  3573. /// This is the helper function to return the newly negated expression only
  3574. /// when the cost is cheaper.
  3575. SDValue getCheaperNegatedExpression(SDValue Op, SelectionDAG &DAG,
  3576. bool LegalOps, bool OptForSize,
  3577. unsigned Depth = 0) const {
  3578. return getCheaperOrNeutralNegatedExpression(Op, DAG, LegalOps, OptForSize,
  3579. NegatibleCost::Cheaper, Depth);
  3580. }
  3581. /// This is the helper function to return the newly negated expression if
  3582. /// the cost is not expensive.
  3583. SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps,
  3584. bool OptForSize, unsigned Depth = 0) const {
  3585. NegatibleCost Cost = NegatibleCost::Expensive;
  3586. return getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
  3587. }
  3588. //===--------------------------------------------------------------------===//
  3589. // Lowering methods - These methods must be implemented by targets so that
  3590. // the SelectionDAGBuilder code knows how to lower these.
  3591. //
  3592. /// Target-specific splitting of values into parts that fit a register
  3593. /// storing a legal type
  3594. virtual bool splitValueIntoRegisterParts(
  3595. SelectionDAG & DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
  3596. unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
  3597. return false;
  3598. }
  3599. /// Allows the target to handle physreg-carried dependency
  3600. /// in target-specific way. Used from the ScheduleDAGSDNodes to decide whether
  3601. /// to add the edge to the dependency graph.
  3602. /// Def - input: Selection DAG node defininfg physical register
  3603. /// User - input: Selection DAG node using physical register
  3604. /// Op - input: Number of User operand
  3605. /// PhysReg - inout: set to the physical register if the edge is
  3606. /// necessary, unchanged otherwise
  3607. /// Cost - inout: physical register copy cost.
  3608. /// Returns 'true' is the edge is necessary, 'false' otherwise
  3609. virtual bool checkForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
  3610. const TargetRegisterInfo *TRI,
  3611. const TargetInstrInfo *TII,
  3612. unsigned &PhysReg, int &Cost) const {
  3613. return false;
  3614. }
  3615. /// Target-specific combining of register parts into its original value
  3616. virtual SDValue
  3617. joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL,
  3618. const SDValue *Parts, unsigned NumParts,
  3619. MVT PartVT, EVT ValueVT,
  3620. std::optional<CallingConv::ID> CC) const {
  3621. return SDValue();
  3622. }
  3623. /// This hook must be implemented to lower the incoming (formal) arguments,
  3624. /// described by the Ins array, into the specified DAG. The implementation
  3625. /// should fill in the InVals array with legal-type argument values, and
  3626. /// return the resulting token chain value.
  3627. virtual SDValue LowerFormalArguments(
  3628. SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
  3629. const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
  3630. SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
  3631. llvm_unreachable("Not Implemented");
  3632. }
  3633. /// This structure contains all information that is necessary for lowering
  3634. /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
  3635. /// needs to lower a call, and targets will see this struct in their LowerCall
  3636. /// implementation.
  3637. struct CallLoweringInfo {
  3638. SDValue Chain;
  3639. Type *RetTy = nullptr;
  3640. bool RetSExt : 1;
  3641. bool RetZExt : 1;
  3642. bool IsVarArg : 1;
  3643. bool IsInReg : 1;
  3644. bool DoesNotReturn : 1;
  3645. bool IsReturnValueUsed : 1;
  3646. bool IsConvergent : 1;
  3647. bool IsPatchPoint : 1;
  3648. bool IsPreallocated : 1;
  3649. bool NoMerge : 1;
  3650. // IsTailCall should be modified by implementations of
  3651. // TargetLowering::LowerCall that perform tail call conversions.
  3652. bool IsTailCall = false;
  3653. // Is Call lowering done post SelectionDAG type legalization.
  3654. bool IsPostTypeLegalization = false;
  3655. unsigned NumFixedArgs = -1;
  3656. CallingConv::ID CallConv = CallingConv::C;
  3657. SDValue Callee;
  3658. ArgListTy Args;
  3659. SelectionDAG &DAG;
  3660. SDLoc DL;
  3661. const CallBase *CB = nullptr;
  3662. SmallVector<ISD::OutputArg, 32> Outs;
  3663. SmallVector<SDValue, 32> OutVals;
  3664. SmallVector<ISD::InputArg, 32> Ins;
  3665. SmallVector<SDValue, 4> InVals;
  3666. const ConstantInt *CFIType = nullptr;
  3667. CallLoweringInfo(SelectionDAG &DAG)
  3668. : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
  3669. DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
  3670. IsPatchPoint(false), IsPreallocated(false), NoMerge(false),
  3671. DAG(DAG) {}
  3672. CallLoweringInfo &setDebugLoc(const SDLoc &dl) {
  3673. DL = dl;
  3674. return *this;
  3675. }
  3676. CallLoweringInfo &setChain(SDValue InChain) {
  3677. Chain = InChain;
  3678. return *this;
  3679. }
  3680. // setCallee with target/module-specific attributes
  3681. CallLoweringInfo &setLibCallee(CallingConv::ID CC, Type *ResultType,
  3682. SDValue Target, ArgListTy &&ArgsList) {
  3683. RetTy = ResultType;
  3684. Callee = Target;
  3685. CallConv = CC;
  3686. NumFixedArgs = ArgsList.size();
  3687. Args = std::move(ArgsList);
  3688. DAG.getTargetLoweringInfo().markLibCallAttributes(
  3689. &(DAG.getMachineFunction()), CC, Args);
  3690. return *this;
  3691. }
  3692. CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
  3693. SDValue Target, ArgListTy &&ArgsList) {
  3694. RetTy = ResultType;
  3695. Callee = Target;
  3696. CallConv = CC;
  3697. NumFixedArgs = ArgsList.size();
  3698. Args = std::move(ArgsList);
  3699. return *this;
  3700. }
  3701. CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
  3702. SDValue Target, ArgListTy &&ArgsList,
  3703. const CallBase &Call) {
  3704. RetTy = ResultType;
  3705. IsInReg = Call.hasRetAttr(Attribute::InReg);
  3706. DoesNotReturn =
  3707. Call.doesNotReturn() ||
  3708. (!isa<InvokeInst>(Call) && isa<UnreachableInst>(Call.getNextNode()));
  3709. IsVarArg = FTy->isVarArg();
  3710. IsReturnValueUsed = !Call.use_empty();
  3711. RetSExt = Call.hasRetAttr(Attribute::SExt);
  3712. RetZExt = Call.hasRetAttr(Attribute::ZExt);
  3713. NoMerge = Call.hasFnAttr(Attribute::NoMerge);
  3714. Callee = Target;
  3715. CallConv = Call.getCallingConv();
  3716. NumFixedArgs = FTy->getNumParams();
  3717. Args = std::move(ArgsList);
  3718. CB = &Call;
  3719. return *this;
  3720. }
  3721. CallLoweringInfo &setInRegister(bool Value = true) {
  3722. IsInReg = Value;
  3723. return *this;
  3724. }
  3725. CallLoweringInfo &setNoReturn(bool Value = true) {
  3726. DoesNotReturn = Value;
  3727. return *this;
  3728. }
  3729. CallLoweringInfo &setVarArg(bool Value = true) {
  3730. IsVarArg = Value;
  3731. return *this;
  3732. }
  3733. CallLoweringInfo &setTailCall(bool Value = true) {
  3734. IsTailCall = Value;
  3735. return *this;
  3736. }
  3737. CallLoweringInfo &setDiscardResult(bool Value = true) {
  3738. IsReturnValueUsed = !Value;
  3739. return *this;
  3740. }
  3741. CallLoweringInfo &setConvergent(bool Value = true) {
  3742. IsConvergent = Value;
  3743. return *this;
  3744. }
  3745. CallLoweringInfo &setSExtResult(bool Value = true) {
  3746. RetSExt = Value;
  3747. return *this;
  3748. }
  3749. CallLoweringInfo &setZExtResult(bool Value = true) {
  3750. RetZExt = Value;
  3751. return *this;
  3752. }
  3753. CallLoweringInfo &setIsPatchPoint(bool Value = true) {
  3754. IsPatchPoint = Value;
  3755. return *this;
  3756. }
  3757. CallLoweringInfo &setIsPreallocated(bool Value = true) {
  3758. IsPreallocated = Value;
  3759. return *this;
  3760. }
  3761. CallLoweringInfo &setIsPostTypeLegalization(bool Value=true) {
  3762. IsPostTypeLegalization = Value;
  3763. return *this;
  3764. }
  3765. CallLoweringInfo &setCFIType(const ConstantInt *Type) {
  3766. CFIType = Type;
  3767. return *this;
  3768. }
  3769. ArgListTy &getArgs() {
  3770. return Args;
  3771. }
  3772. };
  3773. /// This structure is used to pass arguments to makeLibCall function.
  3774. struct MakeLibCallOptions {
  3775. // By passing type list before soften to makeLibCall, the target hook
  3776. // shouldExtendTypeInLibCall can get the original type before soften.
  3777. ArrayRef<EVT> OpsVTBeforeSoften;
  3778. EVT RetVTBeforeSoften;
  3779. bool IsSExt : 1;
  3780. bool DoesNotReturn : 1;
  3781. bool IsReturnValueUsed : 1;
  3782. bool IsPostTypeLegalization : 1;
  3783. bool IsSoften : 1;
  3784. MakeLibCallOptions()
  3785. : IsSExt(false), DoesNotReturn(false), IsReturnValueUsed(true),
  3786. IsPostTypeLegalization(false), IsSoften(false) {}
  3787. MakeLibCallOptions &setSExt(bool Value = true) {
  3788. IsSExt = Value;
  3789. return *this;
  3790. }
  3791. MakeLibCallOptions &setNoReturn(bool Value = true) {
  3792. DoesNotReturn = Value;
  3793. return *this;
  3794. }
  3795. MakeLibCallOptions &setDiscardResult(bool Value = true) {
  3796. IsReturnValueUsed = !Value;
  3797. return *this;
  3798. }
  3799. MakeLibCallOptions &setIsPostTypeLegalization(bool Value = true) {
  3800. IsPostTypeLegalization = Value;
  3801. return *this;
  3802. }
  3803. MakeLibCallOptions &setTypeListBeforeSoften(ArrayRef<EVT> OpsVT, EVT RetVT,
  3804. bool Value = true) {
  3805. OpsVTBeforeSoften = OpsVT;
  3806. RetVTBeforeSoften = RetVT;
  3807. IsSoften = Value;
  3808. return *this;
  3809. }
  3810. };
  3811. /// This function lowers an abstract call to a function into an actual call.
  3812. /// This returns a pair of operands. The first element is the return value
  3813. /// for the function (if RetTy is not VoidTy). The second element is the
  3814. /// outgoing token chain. It calls LowerCall to do the actual lowering.
  3815. std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
  3816. /// This hook must be implemented to lower calls into the specified
  3817. /// DAG. The outgoing arguments to the call are described by the Outs array,
  3818. /// and the values to be returned by the call are described by the Ins
  3819. /// array. The implementation should fill in the InVals array with legal-type
  3820. /// return values from the call, and return the resulting token chain value.
  3821. virtual SDValue
  3822. LowerCall(CallLoweringInfo &/*CLI*/,
  3823. SmallVectorImpl<SDValue> &/*InVals*/) const {
  3824. llvm_unreachable("Not Implemented");
  3825. }
  3826. /// Target-specific cleanup for formal ByVal parameters.
  3827. virtual void HandleByVal(CCState *, unsigned &, Align) const {}
  3828. /// This hook should be implemented to check whether the return values
  3829. /// described by the Outs array can fit into the return registers. If false
  3830. /// is returned, an sret-demotion is performed.
  3831. virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
  3832. MachineFunction &/*MF*/, bool /*isVarArg*/,
  3833. const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
  3834. LLVMContext &/*Context*/) const
  3835. {
  3836. // Return true by default to get preexisting behavior.
  3837. return true;
  3838. }
  3839. /// This hook must be implemented to lower outgoing return values, described
  3840. /// by the Outs array, into the specified DAG. The implementation should
  3841. /// return the resulting token chain value.
  3842. virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
  3843. bool /*isVarArg*/,
  3844. const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
  3845. const SmallVectorImpl<SDValue> & /*OutVals*/,
  3846. const SDLoc & /*dl*/,
  3847. SelectionDAG & /*DAG*/) const {
  3848. llvm_unreachable("Not Implemented");
  3849. }
  3850. /// Return true if result of the specified node is used by a return node
  3851. /// only. It also compute and return the input chain for the tail call.
  3852. ///
  3853. /// This is used to determine whether it is possible to codegen a libcall as
  3854. /// tail call at legalization time.
  3855. virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
  3856. return false;
  3857. }
  3858. /// Return true if the target may be able emit the call instruction as a tail
  3859. /// call. This is used by optimization passes to determine if it's profitable
  3860. /// to duplicate return instructions to enable tailcall optimization.
  3861. virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
  3862. return false;
  3863. }
  3864. /// Return the builtin name for the __builtin___clear_cache intrinsic
  3865. /// Default is to invoke the clear cache library call
  3866. virtual const char * getClearCacheBuiltinName() const {
  3867. return "__clear_cache";
  3868. }
  3869. /// Return the register ID of the name passed in. Used by named register
  3870. /// global variables extension. There is no target-independent behaviour
  3871. /// so the default action is to bail.
  3872. virtual Register getRegisterByName(const char* RegName, LLT Ty,
  3873. const MachineFunction &MF) const {
  3874. report_fatal_error("Named registers not implemented for this target");
  3875. }
  3876. /// Return the type that should be used to zero or sign extend a
  3877. /// zeroext/signext integer return value. FIXME: Some C calling conventions
  3878. /// require the return type to be promoted, but this is not true all the time,
  3879. /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
  3880. /// conventions. The frontend should handle this and include all of the
  3881. /// necessary information.
  3882. virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT,
  3883. ISD::NodeType /*ExtendKind*/) const {
  3884. EVT MinVT = getRegisterType(Context, MVT::i32);
  3885. return VT.bitsLT(MinVT) ? MinVT : VT;
  3886. }
  3887. /// For some targets, an LLVM struct type must be broken down into multiple
  3888. /// simple types, but the calling convention specifies that the entire struct
  3889. /// must be passed in a block of consecutive registers.
  3890. virtual bool
  3891. functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
  3892. bool isVarArg,
  3893. const DataLayout &DL) const {
  3894. return false;
  3895. }
  3896. /// For most targets, an LLVM type must be broken down into multiple
  3897. /// smaller types. Usually the halves are ordered according to the endianness
  3898. /// but for some platform that would break. So this method will default to
  3899. /// matching the endianness but can be overridden.
  3900. virtual bool
  3901. shouldSplitFunctionArgumentsAsLittleEndian(const DataLayout &DL) const {
  3902. return DL.isLittleEndian();
  3903. }
  3904. /// Returns a 0 terminated array of registers that can be safely used as
  3905. /// scratch registers.
  3906. virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
  3907. return nullptr;
  3908. }
  3909. /// This callback is used to prepare for a volatile or atomic load.
  3910. /// It takes a chain node as input and returns the chain for the load itself.
  3911. ///
  3912. /// Having a callback like this is necessary for targets like SystemZ,
  3913. /// which allows a CPU to reuse the result of a previous load indefinitely,
  3914. /// even if a cache-coherent store is performed by another CPU. The default
  3915. /// implementation does nothing.
  3916. virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL,
  3917. SelectionDAG &DAG) const {
  3918. return Chain;
  3919. }
  3920. /// Should SelectionDAG lower an atomic store of the given kind as a normal
  3921. /// StoreSDNode (as opposed to an AtomicSDNode)? NOTE: The intention is to
  3922. /// eventually migrate all targets to the using StoreSDNodes, but porting is
  3923. /// being done target at a time.
  3924. virtual bool lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
  3925. assert(SI.isAtomic() && "violated precondition");
  3926. return false;
  3927. }
  3928. /// Should SelectionDAG lower an atomic load of the given kind as a normal
  3929. /// LoadSDNode (as opposed to an AtomicSDNode)? NOTE: The intention is to
  3930. /// eventually migrate all targets to the using LoadSDNodes, but porting is
  3931. /// being done target at a time.
  3932. virtual bool lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
  3933. assert(LI.isAtomic() && "violated precondition");
  3934. return false;
  3935. }
  3936. /// This callback is invoked by the type legalizer to legalize nodes with an
  3937. /// illegal operand type but legal result types. It replaces the
  3938. /// LowerOperation callback in the type Legalizer. The reason we can not do
  3939. /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
  3940. /// use this callback.
  3941. ///
  3942. /// TODO: Consider merging with ReplaceNodeResults.
  3943. ///
  3944. /// The target places new result values for the node in Results (their number
  3945. /// and types must exactly match those of the original return values of
  3946. /// the node), or leaves Results empty, which indicates that the node is not
  3947. /// to be custom lowered after all.
  3948. /// The default implementation calls LowerOperation.
  3949. virtual void LowerOperationWrapper(SDNode *N,
  3950. SmallVectorImpl<SDValue> &Results,
  3951. SelectionDAG &DAG) const;
  3952. /// This callback is invoked for operations that are unsupported by the
  3953. /// target, which are registered to use 'custom' lowering, and whose defined
  3954. /// values are all legal. If the target has no operations that require custom
  3955. /// lowering, it need not implement this. The default implementation of this
  3956. /// aborts.
  3957. virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
  3958. /// This callback is invoked when a node result type is illegal for the
  3959. /// target, and the operation was registered to use 'custom' lowering for that
  3960. /// result type. The target places new result values for the node in Results
  3961. /// (their number and types must exactly match those of the original return
  3962. /// values of the node), or leaves Results empty, which indicates that the
  3963. /// node is not to be custom lowered after all.
  3964. ///
  3965. /// If the target has no operations that require custom lowering, it need not
  3966. /// implement this. The default implementation aborts.
  3967. virtual void ReplaceNodeResults(SDNode * /*N*/,
  3968. SmallVectorImpl<SDValue> &/*Results*/,
  3969. SelectionDAG &/*DAG*/) const {
  3970. llvm_unreachable("ReplaceNodeResults not implemented for this target!");
  3971. }
  3972. /// This method returns the name of a target specific DAG node.
  3973. virtual const char *getTargetNodeName(unsigned Opcode) const;
  3974. /// This method returns a target specific FastISel object, or null if the
  3975. /// target does not support "fast" ISel.
  3976. virtual FastISel *createFastISel(FunctionLoweringInfo &,
  3977. const TargetLibraryInfo *) const {
  3978. return nullptr;
  3979. }
  3980. bool verifyReturnAddressArgumentIsConstant(SDValue Op,
  3981. SelectionDAG &DAG) const;
  3982. //===--------------------------------------------------------------------===//
  3983. // Inline Asm Support hooks
  3984. //
  3985. /// This hook allows the target to expand an inline asm call to be explicit
  3986. /// llvm code if it wants to. This is useful for turning simple inline asms
  3987. /// into LLVM intrinsics, which gives the compiler more information about the
  3988. /// behavior of the code.
  3989. virtual bool ExpandInlineAsm(CallInst *) const {
  3990. return false;
  3991. }
  3992. enum ConstraintType {
  3993. C_Register, // Constraint represents specific register(s).
  3994. C_RegisterClass, // Constraint represents any of register(s) in class.
  3995. C_Memory, // Memory constraint.
  3996. C_Address, // Address constraint.
  3997. C_Immediate, // Requires an immediate.
  3998. C_Other, // Something else.
  3999. C_Unknown // Unsupported constraint.
  4000. };
  4001. enum ConstraintWeight {
  4002. // Generic weights.
  4003. CW_Invalid = -1, // No match.
  4004. CW_Okay = 0, // Acceptable.
  4005. CW_Good = 1, // Good weight.
  4006. CW_Better = 2, // Better weight.
  4007. CW_Best = 3, // Best weight.
  4008. // Well-known weights.
  4009. CW_SpecificReg = CW_Okay, // Specific register operands.
  4010. CW_Register = CW_Good, // Register operands.
  4011. CW_Memory = CW_Better, // Memory operands.
  4012. CW_Constant = CW_Best, // Constant operand.
  4013. CW_Default = CW_Okay // Default or don't know type.
  4014. };
  4015. /// This contains information for each constraint that we are lowering.
  4016. struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
  4017. /// This contains the actual string for the code, like "m". TargetLowering
  4018. /// picks the 'best' code from ConstraintInfo::Codes that most closely
  4019. /// matches the operand.
  4020. std::string ConstraintCode;
  4021. /// Information about the constraint code, e.g. Register, RegisterClass,
  4022. /// Memory, Other, Unknown.
  4023. TargetLowering::ConstraintType ConstraintType = TargetLowering::C_Unknown;
  4024. /// If this is the result output operand or a clobber, this is null,
  4025. /// otherwise it is the incoming operand to the CallInst. This gets
  4026. /// modified as the asm is processed.
  4027. Value *CallOperandVal = nullptr;
  4028. /// The ValueType for the operand value.
  4029. MVT ConstraintVT = MVT::Other;
  4030. /// Copy constructor for copying from a ConstraintInfo.
  4031. AsmOperandInfo(InlineAsm::ConstraintInfo Info)
  4032. : InlineAsm::ConstraintInfo(std::move(Info)) {}
  4033. /// Return true of this is an input operand that is a matching constraint
  4034. /// like "4".
  4035. bool isMatchingInputConstraint() const;
  4036. /// If this is an input matching constraint, this method returns the output
  4037. /// operand it matches.
  4038. unsigned getMatchedOperand() const;
  4039. };
  4040. using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
  4041. /// Split up the constraint string from the inline assembly value into the
  4042. /// specific constraints and their prefixes, and also tie in the associated
  4043. /// operand values. If this returns an empty vector, and if the constraint
  4044. /// string itself isn't empty, there was an error parsing.
  4045. virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
  4046. const TargetRegisterInfo *TRI,
  4047. const CallBase &Call) const;
  4048. /// Examine constraint type and operand type and determine a weight value.
  4049. /// The operand object must already have been set up with the operand type.
  4050. virtual ConstraintWeight getMultipleConstraintMatchWeight(
  4051. AsmOperandInfo &info, int maIndex) const;
  4052. /// Examine constraint string and operand type and determine a weight value.
  4053. /// The operand object must already have been set up with the operand type.
  4054. virtual ConstraintWeight getSingleConstraintMatchWeight(
  4055. AsmOperandInfo &info, const char *constraint) const;
  4056. /// Determines the constraint code and constraint type to use for the specific
  4057. /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
  4058. /// If the actual operand being passed in is available, it can be passed in as
  4059. /// Op, otherwise an empty SDValue can be passed.
  4060. virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
  4061. SDValue Op,
  4062. SelectionDAG *DAG = nullptr) const;
  4063. /// Given a constraint, return the type of constraint it is for this target.
  4064. virtual ConstraintType getConstraintType(StringRef Constraint) const;
  4065. /// Given a physical register constraint (e.g. {edx}), return the register
  4066. /// number and the register class for the register.
  4067. ///
  4068. /// Given a register class constraint, like 'r', if this corresponds directly
  4069. /// to an LLVM register class, return a register of 0 and the register class
  4070. /// pointer.
  4071. ///
  4072. /// This should only be used for C_Register constraints. On error, this
  4073. /// returns a register number of 0 and a null register class pointer.
  4074. virtual std::pair<unsigned, const TargetRegisterClass *>
  4075. getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
  4076. StringRef Constraint, MVT VT) const;
  4077. virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
  4078. if (ConstraintCode == "m")
  4079. return InlineAsm::Constraint_m;
  4080. if (ConstraintCode == "o")
  4081. return InlineAsm::Constraint_o;
  4082. if (ConstraintCode == "X")
  4083. return InlineAsm::Constraint_X;
  4084. if (ConstraintCode == "p")
  4085. return InlineAsm::Constraint_p;
  4086. return InlineAsm::Constraint_Unknown;
  4087. }
  4088. /// Try to replace an X constraint, which matches anything, with another that
  4089. /// has more specific requirements based on the type of the corresponding
  4090. /// operand. This returns null if there is no replacement to make.
  4091. virtual const char *LowerXConstraint(EVT ConstraintVT) const;
  4092. /// Lower the specified operand into the Ops vector. If it is invalid, don't
  4093. /// add anything to Ops.
  4094. virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
  4095. std::vector<SDValue> &Ops,
  4096. SelectionDAG &DAG) const;
  4097. // Lower custom output constraints. If invalid, return SDValue().
  4098. virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag,
  4099. const SDLoc &DL,
  4100. const AsmOperandInfo &OpInfo,
  4101. SelectionDAG &DAG) const;
  4102. // Targets may override this function to collect operands from the CallInst
  4103. // and for example, lower them into the SelectionDAG operands.
  4104. virtual void CollectTargetIntrinsicOperands(const CallInst &I,
  4105. SmallVectorImpl<SDValue> &Ops,
  4106. SelectionDAG &DAG) const;
  4107. //===--------------------------------------------------------------------===//
  4108. // Div utility functions
  4109. //
  4110. SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
  4111. SmallVectorImpl<SDNode *> &Created) const;
  4112. SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
  4113. SmallVectorImpl<SDNode *> &Created) const;
  4114. /// Targets may override this function to provide custom SDIV lowering for
  4115. /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
  4116. /// assumes SDIV is expensive and replaces it with a series of other integer
  4117. /// operations.
  4118. virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
  4119. SelectionDAG &DAG,
  4120. SmallVectorImpl<SDNode *> &Created) const;
  4121. /// Targets may override this function to provide custom SREM lowering for
  4122. /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
  4123. /// assumes SREM is expensive and replaces it with a series of other integer
  4124. /// operations.
  4125. virtual SDValue BuildSREMPow2(SDNode *N, const APInt &Divisor,
  4126. SelectionDAG &DAG,
  4127. SmallVectorImpl<SDNode *> &Created) const;
  4128. /// Indicate whether this target prefers to combine FDIVs with the same
  4129. /// divisor. If the transform should never be done, return zero. If the
  4130. /// transform should be done, return the minimum number of divisor uses
  4131. /// that must exist.
  4132. virtual unsigned combineRepeatedFPDivisors() const {
  4133. return 0;
  4134. }
  4135. /// Hooks for building estimates in place of slower divisions and square
  4136. /// roots.
  4137. /// Return either a square root or its reciprocal estimate value for the input
  4138. /// operand.
  4139. /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
  4140. /// 'Enabled' as set by a potential default override attribute.
  4141. /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
  4142. /// refinement iterations required to generate a sufficient (though not
  4143. /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
  4144. /// The boolean UseOneConstNR output is used to select a Newton-Raphson
  4145. /// algorithm implementation that uses either one or two constants.
  4146. /// The boolean Reciprocal is used to select whether the estimate is for the
  4147. /// square root of the input operand or the reciprocal of its square root.
  4148. /// A target may choose to implement its own refinement within this function.
  4149. /// If that's true, then return '0' as the number of RefinementSteps to avoid
  4150. /// any further refinement of the estimate.
  4151. /// An empty SDValue return means no estimate sequence can be created.
  4152. virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
  4153. int Enabled, int &RefinementSteps,
  4154. bool &UseOneConstNR, bool Reciprocal) const {
  4155. return SDValue();
  4156. }
  4157. /// Try to convert the fminnum/fmaxnum to a compare/select sequence. This is
  4158. /// required for correctness since InstCombine might have canonicalized a
  4159. /// fcmp+select sequence to a FMINNUM/FMAXNUM intrinsic. If we were to fall
  4160. /// through to the default expansion/soften to libcall, we might introduce a
  4161. /// link-time dependency on libm into a file that originally did not have one.
  4162. SDValue createSelectForFMINNUM_FMAXNUM(SDNode *Node, SelectionDAG &DAG) const;
  4163. /// Return a reciprocal estimate value for the input operand.
  4164. /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
  4165. /// 'Enabled' as set by a potential default override attribute.
  4166. /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
  4167. /// refinement iterations required to generate a sufficient (though not
  4168. /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
  4169. /// A target may choose to implement its own refinement within this function.
  4170. /// If that's true, then return '0' as the number of RefinementSteps to avoid
  4171. /// any further refinement of the estimate.
  4172. /// An empty SDValue return means no estimate sequence can be created.
  4173. virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
  4174. int Enabled, int &RefinementSteps) const {
  4175. return SDValue();
  4176. }
  4177. /// Return a target-dependent comparison result if the input operand is
  4178. /// suitable for use with a square root estimate calculation. For example, the
  4179. /// comparison may check if the operand is NAN, INF, zero, normal, etc. The
  4180. /// result should be used as the condition operand for a select or branch.
  4181. virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG,
  4182. const DenormalMode &Mode) const;
  4183. /// Return a target-dependent result if the input operand is not suitable for
  4184. /// use with a square root estimate calculation.
  4185. virtual SDValue getSqrtResultForDenormInput(SDValue Operand,
  4186. SelectionDAG &DAG) const {
  4187. return DAG.getConstantFP(0.0, SDLoc(Operand), Operand.getValueType());
  4188. }
  4189. //===--------------------------------------------------------------------===//
  4190. // Legalization utility functions
  4191. //
  4192. /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
  4193. /// respectively, each computing an n/2-bit part of the result.
  4194. /// \param Result A vector that will be filled with the parts of the result
  4195. /// in little-endian order.
  4196. /// \param LL Low bits of the LHS of the MUL. You can use this parameter
  4197. /// if you want to control how low bits are extracted from the LHS.
  4198. /// \param LH High bits of the LHS of the MUL. See LL for meaning.
  4199. /// \param RL Low bits of the RHS of the MUL. See LL for meaning
  4200. /// \param RH High bits of the RHS of the MUL. See LL for meaning.
  4201. /// \returns true if the node has been expanded, false if it has not
  4202. bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS,
  4203. SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
  4204. SelectionDAG &DAG, MulExpansionKind Kind,
  4205. SDValue LL = SDValue(), SDValue LH = SDValue(),
  4206. SDValue RL = SDValue(), SDValue RH = SDValue()) const;
  4207. /// Expand a MUL into two nodes. One that computes the high bits of
  4208. /// the result and one that computes the low bits.
  4209. /// \param HiLoVT The value type to use for the Lo and Hi nodes.
  4210. /// \param LL Low bits of the LHS of the MUL. You can use this parameter
  4211. /// if you want to control how low bits are extracted from the LHS.
  4212. /// \param LH High bits of the LHS of the MUL. See LL for meaning.
  4213. /// \param RL Low bits of the RHS of the MUL. See LL for meaning
  4214. /// \param RH High bits of the RHS of the MUL. See LL for meaning.
  4215. /// \returns true if the node has been expanded. false if it has not
  4216. bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
  4217. SelectionDAG &DAG, MulExpansionKind Kind,
  4218. SDValue LL = SDValue(), SDValue LH = SDValue(),
  4219. SDValue RL = SDValue(), SDValue RH = SDValue()) const;
  4220. /// Attempt to expand an n-bit div/rem/divrem by constant using a n/2-bit
  4221. /// urem by constant and other arithmetic ops. The n/2-bit urem by constant
  4222. /// will be expanded by DAGCombiner. This is not possible for all constant
  4223. /// divisors.
  4224. /// \param N Node to expand
  4225. /// \param Result A vector that will be filled with the lo and high parts of
  4226. /// the results. For *DIVREM, this will be the quotient parts followed
  4227. /// by the remainder parts.
  4228. /// \param HiLoVT The value type to use for the Lo and Hi parts. Should be
  4229. /// half of VT.
  4230. /// \param LL Low bits of the LHS of the operation. You can use this
  4231. /// parameter if you want to control how low bits are extracted from
  4232. /// the LHS.
  4233. /// \param LH High bits of the LHS of the operation. See LL for meaning.
  4234. /// \returns true if the node has been expanded, false if it has not.
  4235. bool expandDIVREMByConstant(SDNode *N, SmallVectorImpl<SDValue> &Result,
  4236. EVT HiLoVT, SelectionDAG &DAG,
  4237. SDValue LL = SDValue(),
  4238. SDValue LH = SDValue()) const;
  4239. /// Expand funnel shift.
  4240. /// \param N Node to expand
  4241. /// \returns The expansion if successful, SDValue() otherwise
  4242. SDValue expandFunnelShift(SDNode *N, SelectionDAG &DAG) const;
  4243. /// Expand rotations.
  4244. /// \param N Node to expand
  4245. /// \param AllowVectorOps expand vector rotate, this should only be performed
  4246. /// if the legalization is happening outside of LegalizeVectorOps
  4247. /// \returns The expansion if successful, SDValue() otherwise
  4248. SDValue expandROT(SDNode *N, bool AllowVectorOps, SelectionDAG &DAG) const;
  4249. /// Expand shift-by-parts.
  4250. /// \param N Node to expand
  4251. /// \param Lo lower-output-part after conversion
  4252. /// \param Hi upper-output-part after conversion
  4253. void expandShiftParts(SDNode *N, SDValue &Lo, SDValue &Hi,
  4254. SelectionDAG &DAG) const;
  4255. /// Expand float(f32) to SINT(i64) conversion
  4256. /// \param N Node to expand
  4257. /// \param Result output after conversion
  4258. /// \returns True, if the expansion was successful, false otherwise
  4259. bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
  4260. /// Expand float to UINT conversion
  4261. /// \param N Node to expand
  4262. /// \param Result output after conversion
  4263. /// \param Chain output chain after conversion
  4264. /// \returns True, if the expansion was successful, false otherwise
  4265. bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain,
  4266. SelectionDAG &DAG) const;
  4267. /// Expand UINT(i64) to double(f64) conversion
  4268. /// \param N Node to expand
  4269. /// \param Result output after conversion
  4270. /// \param Chain output chain after conversion
  4271. /// \returns True, if the expansion was successful, false otherwise
  4272. bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain,
  4273. SelectionDAG &DAG) const;
  4274. /// Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
  4275. SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const;
  4276. /// Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
  4277. /// \param N Node to expand
  4278. /// \returns The expansion result
  4279. SDValue expandFP_TO_INT_SAT(SDNode *N, SelectionDAG &DAG) const;
  4280. /// Expand check for floating point class.
  4281. /// \param ResultVT The type of intrinsic call result.
  4282. /// \param Op The tested value.
  4283. /// \param Test The test to perform.
  4284. /// \param Flags The optimization flags.
  4285. /// \returns The expansion result or SDValue() if it fails.
  4286. SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, unsigned Test,
  4287. SDNodeFlags Flags, const SDLoc &DL,
  4288. SelectionDAG &DAG) const;
  4289. /// Expand CTPOP nodes. Expands vector/scalar CTPOP nodes,
  4290. /// vector nodes can only succeed if all operations are legal/custom.
  4291. /// \param N Node to expand
  4292. /// \returns The expansion result or SDValue() if it fails.
  4293. SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const;
  4294. /// Expand VP_CTPOP nodes.
  4295. /// \returns The expansion result or SDValue() if it fails.
  4296. SDValue expandVPCTPOP(SDNode *N, SelectionDAG &DAG) const;
  4297. /// Expand CTLZ/CTLZ_ZERO_UNDEF nodes. Expands vector/scalar CTLZ nodes,
  4298. /// vector nodes can only succeed if all operations are legal/custom.
  4299. /// \param N Node to expand
  4300. /// \returns The expansion result or SDValue() if it fails.
  4301. SDValue expandCTLZ(SDNode *N, SelectionDAG &DAG) const;
  4302. /// Expand VP_CTLZ/VP_CTLZ_ZERO_UNDEF nodes.
  4303. /// \param N Node to expand
  4304. /// \returns The expansion result or SDValue() if it fails.
  4305. SDValue expandVPCTLZ(SDNode *N, SelectionDAG &DAG) const;
  4306. /// Expand CTTZ via Table Lookup.
  4307. /// \param N Node to expand
  4308. /// \returns The expansion result or SDValue() if it fails.
  4309. SDValue CTTZTableLookup(SDNode *N, SelectionDAG &DAG, const SDLoc &DL, EVT VT,
  4310. SDValue Op, unsigned NumBitsPerElt) const;
  4311. /// Expand CTTZ/CTTZ_ZERO_UNDEF nodes. Expands vector/scalar CTTZ nodes,
  4312. /// vector nodes can only succeed if all operations are legal/custom.
  4313. /// \param N Node to expand
  4314. /// \returns The expansion result or SDValue() if it fails.
  4315. SDValue expandCTTZ(SDNode *N, SelectionDAG &DAG) const;
  4316. /// Expand VP_CTTZ/VP_CTTZ_ZERO_UNDEF nodes.
  4317. /// \param N Node to expand
  4318. /// \returns The expansion result or SDValue() if it fails.
  4319. SDValue expandVPCTTZ(SDNode *N, SelectionDAG &DAG) const;
  4320. /// Expand ABS nodes. Expands vector/scalar ABS nodes,
  4321. /// vector nodes can only succeed if all operations are legal/custom.
  4322. /// (ABS x) -> (XOR (ADD x, (SRA x, type_size)), (SRA x, type_size))
  4323. /// \param N Node to expand
  4324. /// \param IsNegative indicate negated abs
  4325. /// \returns The expansion result or SDValue() if it fails.
  4326. SDValue expandABS(SDNode *N, SelectionDAG &DAG,
  4327. bool IsNegative = false) const;
  4328. /// Expand BSWAP nodes. Expands scalar/vector BSWAP nodes with i16/i32/i64
  4329. /// scalar types. Returns SDValue() if expand fails.
  4330. /// \param N Node to expand
  4331. /// \returns The expansion result or SDValue() if it fails.
  4332. SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const;
  4333. /// Expand VP_BSWAP nodes. Expands VP_BSWAP nodes with
  4334. /// i16/i32/i64 scalar types. Returns SDValue() if expand fails. \param N Node
  4335. /// to expand \returns The expansion result or SDValue() if it fails.
  4336. SDValue expandVPBSWAP(SDNode *N, SelectionDAG &DAG) const;
  4337. /// Expand BITREVERSE nodes. Expands scalar/vector BITREVERSE nodes.
  4338. /// Returns SDValue() if expand fails.
  4339. /// \param N Node to expand
  4340. /// \returns The expansion result or SDValue() if it fails.
  4341. SDValue expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const;
  4342. /// Expand VP_BITREVERSE nodes. Expands VP_BITREVERSE nodes with
  4343. /// i8/i16/i32/i64 scalar types. \param N Node to expand \returns The
  4344. /// expansion result or SDValue() if it fails.
  4345. SDValue expandVPBITREVERSE(SDNode *N, SelectionDAG &DAG) const;
  4346. /// Turn load of vector type into a load of the individual elements.
  4347. /// \param LD load to expand
  4348. /// \returns BUILD_VECTOR and TokenFactor nodes.
  4349. std::pair<SDValue, SDValue> scalarizeVectorLoad(LoadSDNode *LD,
  4350. SelectionDAG &DAG) const;
  4351. // Turn a store of a vector type into stores of the individual elements.
  4352. /// \param ST Store with a vector value type
  4353. /// \returns TokenFactor of the individual store chains.
  4354. SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const;
  4355. /// Expands an unaligned load to 2 half-size loads for an integer, and
  4356. /// possibly more for vectors.
  4357. std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
  4358. SelectionDAG &DAG) const;
  4359. /// Expands an unaligned store to 2 half-size stores for integer values, and
  4360. /// possibly more for vectors.
  4361. SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
  4362. /// Increments memory address \p Addr according to the type of the value
  4363. /// \p DataVT that should be stored. If the data is stored in compressed
  4364. /// form, the memory address should be incremented according to the number of
  4365. /// the stored elements. This number is equal to the number of '1's bits
  4366. /// in the \p Mask.
  4367. /// \p DataVT is a vector type. \p Mask is a vector value.
  4368. /// \p DataVT and \p Mask have the same number of vector elements.
  4369. SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
  4370. EVT DataVT, SelectionDAG &DAG,
  4371. bool IsCompressedMemory) const;
  4372. /// Get a pointer to vector element \p Idx located in memory for a vector of
  4373. /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
  4374. /// bounds the returned pointer is unspecified, but will be within the vector
  4375. /// bounds.
  4376. SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
  4377. SDValue Index) const;
  4378. /// Get a pointer to a sub-vector of type \p SubVecVT at index \p Idx located
  4379. /// in memory for a vector of type \p VecVT starting at a base address of
  4380. /// \p VecPtr. If \p Idx plus the size of \p SubVecVT is out of bounds the
  4381. /// returned pointer is unspecified, but the value returned will be such that
  4382. /// the entire subvector would be within the vector bounds.
  4383. SDValue getVectorSubVecPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
  4384. EVT SubVecVT, SDValue Index) const;
  4385. /// Method for building the DAG expansion of ISD::[US][MIN|MAX]. This
  4386. /// method accepts integers as its arguments.
  4387. SDValue expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const;
  4388. /// Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT. This
  4389. /// method accepts integers as its arguments.
  4390. SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const;
  4391. /// Method for building the DAG expansion of ISD::[US]SHLSAT. This
  4392. /// method accepts integers as its arguments.
  4393. SDValue expandShlSat(SDNode *Node, SelectionDAG &DAG) const;
  4394. /// Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT]. This
  4395. /// method accepts integers as its arguments.
  4396. SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const;
  4397. /// Method for building the DAG expansion of ISD::[US]DIVFIX[SAT]. This
  4398. /// method accepts integers as its arguments.
  4399. /// Note: This method may fail if the division could not be performed
  4400. /// within the type. Clients must retry with a wider type if this happens.
  4401. SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
  4402. SDValue LHS, SDValue RHS,
  4403. unsigned Scale, SelectionDAG &DAG) const;
  4404. /// Method for building the DAG expansion of ISD::U(ADD|SUB)O. Expansion
  4405. /// always suceeds and populates the Result and Overflow arguments.
  4406. void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
  4407. SelectionDAG &DAG) const;
  4408. /// Method for building the DAG expansion of ISD::S(ADD|SUB)O. Expansion
  4409. /// always suceeds and populates the Result and Overflow arguments.
  4410. void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
  4411. SelectionDAG &DAG) const;
  4412. /// Method for building the DAG expansion of ISD::[US]MULO. Returns whether
  4413. /// expansion was successful and populates the Result and Overflow arguments.
  4414. bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow,
  4415. SelectionDAG &DAG) const;
  4416. /// Expand a VECREDUCE_* into an explicit calculation. If Count is specified,
  4417. /// only the first Count elements of the vector are used.
  4418. SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const;
  4419. /// Expand a VECREDUCE_SEQ_* into an explicit ordered calculation.
  4420. SDValue expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const;
  4421. /// Expand an SREM or UREM using SDIV/UDIV or SDIVREM/UDIVREM, if legal.
  4422. /// Returns true if the expansion was successful.
  4423. bool expandREM(SDNode *Node, SDValue &Result, SelectionDAG &DAG) const;
  4424. /// Method for building the DAG expansion of ISD::VECTOR_SPLICE. This
  4425. /// method accepts vectors as its arguments.
  4426. SDValue expandVectorSplice(SDNode *Node, SelectionDAG &DAG) const;
  4427. /// Legalize a SETCC or VP_SETCC with given LHS and RHS and condition code CC
  4428. /// on the current target. A VP_SETCC will additionally be given a Mask
  4429. /// and/or EVL not equal to SDValue().
  4430. ///
  4431. /// If the SETCC has been legalized using AND / OR, then the legalized node
  4432. /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
  4433. /// will be set to false. This will also hold if the VP_SETCC has been
  4434. /// legalized using VP_AND / VP_OR.
  4435. ///
  4436. /// If the SETCC / VP_SETCC has been legalized by using
  4437. /// getSetCCSwappedOperands(), then the values of LHS and RHS will be
  4438. /// swapped, CC will be set to the new condition, and NeedInvert will be set
  4439. /// to false.
  4440. ///
  4441. /// If the SETCC / VP_SETCC has been legalized using the inverse condcode,
  4442. /// then LHS and RHS will be unchanged, CC will set to the inverted condcode,
  4443. /// and NeedInvert will be set to true. The caller must invert the result of
  4444. /// the SETCC with SelectionDAG::getLogicalNOT() or take equivalent action to
  4445. /// swap the effect of a true/false result.
  4446. ///
  4447. /// \returns true if the SETCC / VP_SETCC has been legalized, false if it
  4448. /// hasn't.
  4449. bool LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, SDValue &LHS,
  4450. SDValue &RHS, SDValue &CC, SDValue Mask,
  4451. SDValue EVL, bool &NeedInvert, const SDLoc &dl,
  4452. SDValue &Chain, bool IsSignaling = false) const;
  4453. //===--------------------------------------------------------------------===//
  4454. // Instruction Emitting Hooks
  4455. //
  4456. /// This method should be implemented by targets that mark instructions with
  4457. /// the 'usesCustomInserter' flag. These instructions are special in various
  4458. /// ways, which require special support to insert. The specified MachineInstr
  4459. /// is created but not inserted into any basic blocks, and this method is
  4460. /// called to expand it into a sequence of instructions, potentially also
  4461. /// creating new basic blocks and control flow.
  4462. /// As long as the returned basic block is different (i.e., we created a new
  4463. /// one), the custom inserter is free to modify the rest of \p MBB.
  4464. virtual MachineBasicBlock *
  4465. EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
  4466. /// This method should be implemented by targets that mark instructions with
  4467. /// the 'hasPostISelHook' flag. These instructions must be adjusted after
  4468. /// instruction selection by target hooks. e.g. To fill in optional defs for
  4469. /// ARM 's' setting instructions.
  4470. virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
  4471. SDNode *Node) const;
  4472. /// If this function returns true, SelectionDAGBuilder emits a
  4473. /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
  4474. virtual bool useLoadStackGuardNode() const {
  4475. return false;
  4476. }
  4477. virtual SDValue emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
  4478. const SDLoc &DL) const {
  4479. llvm_unreachable("not implemented for this target");
  4480. }
  4481. /// Lower TLS global address SDNode for target independent emulated TLS model.
  4482. virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
  4483. SelectionDAG &DAG) const;
  4484. /// Expands target specific indirect branch for the case of JumpTable
  4485. /// expanasion.
  4486. virtual SDValue expandIndirectJTBranch(const SDLoc& dl, SDValue Value, SDValue Addr,
  4487. SelectionDAG &DAG) const {
  4488. return DAG.getNode(ISD::BRIND, dl, MVT::Other, Value, Addr);
  4489. }
  4490. // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
  4491. // If we're comparing for equality to zero and isCtlzFast is true, expose the
  4492. // fact that this can be implemented as a ctlz/srl pair, so that the dag
  4493. // combiner can fold the new nodes.
  4494. SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
  4495. private:
  4496. SDValue foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
  4497. const SDLoc &DL, DAGCombinerInfo &DCI) const;
  4498. SDValue foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
  4499. const SDLoc &DL, DAGCombinerInfo &DCI) const;
  4500. SDValue optimizeSetCCOfSignedTruncationCheck(EVT SCCVT, SDValue N0,
  4501. SDValue N1, ISD::CondCode Cond,
  4502. DAGCombinerInfo &DCI,
  4503. const SDLoc &DL) const;
  4504. // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
  4505. SDValue optimizeSetCCByHoistingAndByConstFromLogicalShift(
  4506. EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
  4507. DAGCombinerInfo &DCI, const SDLoc &DL) const;
  4508. SDValue prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
  4509. SDValue CompTargetNode, ISD::CondCode Cond,
  4510. DAGCombinerInfo &DCI, const SDLoc &DL,
  4511. SmallVectorImpl<SDNode *> &Created) const;
  4512. SDValue buildUREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
  4513. ISD::CondCode Cond, DAGCombinerInfo &DCI,
  4514. const SDLoc &DL) const;
  4515. SDValue prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
  4516. SDValue CompTargetNode, ISD::CondCode Cond,
  4517. DAGCombinerInfo &DCI, const SDLoc &DL,
  4518. SmallVectorImpl<SDNode *> &Created) const;
  4519. SDValue buildSREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
  4520. ISD::CondCode Cond, DAGCombinerInfo &DCI,
  4521. const SDLoc &DL) const;
  4522. };
  4523. /// Given an LLVM IR type and return type attributes, compute the return value
  4524. /// EVTs and flags, and optionally also the offsets, if the return value is
  4525. /// being lowered to memory.
  4526. void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr,
  4527. SmallVectorImpl<ISD::OutputArg> &Outs,
  4528. const TargetLowering &TLI, const DataLayout &DL);
  4529. } // end namespace llvm
  4530. #endif // LLVM_CODEGEN_TARGETLOWERING_H
  4531. #ifdef __GNUC__
  4532. #pragma GCC diagnostic pop
  4533. #endif