TargetLowering.h 200 KB

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