TargetLowering.h 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835
  1. //===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// This file describes how to lower LLVM code to machine code. This has two
  12. /// main components:
  13. ///
  14. /// 1. Which ValueTypes are natively supported by the target.
  15. /// 2. Which operations are supported for supported ValueTypes.
  16. /// 3. Cost thresholds for alternative implementations of certain operations.
  17. ///
  18. /// In addition it has a few other components, like information about FP
  19. /// immediates.
  20. ///
  21. //===----------------------------------------------------------------------===//
  22. #ifndef LLVM_TARGET_TARGETLOWERING_H
  23. #define LLVM_TARGET_TARGETLOWERING_H
  24. #include "llvm/ADT/DenseMap.h"
  25. #include "llvm/CodeGen/DAGCombine.h"
  26. #include "llvm/CodeGen/RuntimeLibcalls.h"
  27. #include "llvm/CodeGen/SelectionDAGNodes.h"
  28. #include "llvm/IR/Attributes.h"
  29. #include "llvm/IR/CallSite.h"
  30. #include "llvm/IR/CallingConv.h"
  31. #include "llvm/IR/IRBuilder.h"
  32. #include "llvm/IR/InlineAsm.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/MC/MCRegisterInfo.h"
  35. #include "llvm/Target/TargetCallingConv.h"
  36. #include "llvm/Target/TargetMachine.h"
  37. #include <climits>
  38. #include <map>
  39. #include <vector>
  40. namespace llvm {
  41. class CallInst;
  42. class CCState;
  43. class FastISel;
  44. class FunctionLoweringInfo;
  45. class ImmutableCallSite;
  46. class IntrinsicInst;
  47. class MachineBasicBlock;
  48. class MachineFunction;
  49. class MachineInstr;
  50. class MachineJumpTableInfo;
  51. class MachineLoop;
  52. class Mangler;
  53. class MCContext;
  54. class MCExpr;
  55. class MCSymbol;
  56. template<typename T> class SmallVectorImpl;
  57. class DataLayout;
  58. class TargetRegisterClass;
  59. class TargetLibraryInfo;
  60. class TargetLoweringObjectFile;
  61. class Value;
  62. namespace Sched {
  63. enum Preference {
  64. None, // No preference
  65. Source, // Follow source order.
  66. RegPressure, // Scheduling for lowest register pressure.
  67. Hybrid, // Scheduling for both latency and register pressure.
  68. ILP, // Scheduling for ILP in low register pressure mode.
  69. VLIW // Scheduling for VLIW targets.
  70. };
  71. }
  72. /// This base class for TargetLowering contains the SelectionDAG-independent
  73. /// parts that can be used from the rest of CodeGen.
  74. class TargetLoweringBase {
  75. TargetLoweringBase(const TargetLoweringBase&) = delete;
  76. void operator=(const TargetLoweringBase&) = delete;
  77. public:
  78. /// This enum indicates whether operations are valid for a target, and if not,
  79. /// what action should be used to make them valid.
  80. enum LegalizeAction {
  81. Legal, // The target natively supports this operation.
  82. Promote, // This operation should be executed in a larger type.
  83. Expand, // Try to expand this to other ops, otherwise use a libcall.
  84. Custom // Use the LowerOperation hook to implement custom lowering.
  85. };
  86. /// This enum indicates whether a types are legal for a target, and if not,
  87. /// what action should be used to make them valid.
  88. enum LegalizeTypeAction {
  89. TypeLegal, // The target natively supports this type.
  90. TypePromoteInteger, // Replace this integer with a larger one.
  91. TypeExpandInteger, // Split this integer into two of half the size.
  92. TypeSoftenFloat, // Convert this float to a same size integer type.
  93. TypeExpandFloat, // Split this float into two of half the size.
  94. TypeScalarizeVector, // Replace this one-element vector with its element.
  95. TypeSplitVector, // Split this vector into two of half the size.
  96. TypeWidenVector, // This vector should be widened into a larger vector.
  97. TypePromoteFloat // Replace this float with a larger one.
  98. };
  99. /// LegalizeKind holds the legalization kind that needs to happen to EVT
  100. /// in order to type-legalize it.
  101. typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
  102. /// Enum that describes how the target represents true/false values.
  103. enum BooleanContent {
  104. UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
  105. ZeroOrOneBooleanContent, // All bits zero except for bit 0.
  106. ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
  107. };
  108. /// Enum that describes what type of support for selects the target has.
  109. enum SelectSupportKind {
  110. ScalarValSelect, // The target supports scalar selects (ex: cmov).
  111. ScalarCondVectorVal, // The target supports selects with a scalar condition
  112. // and vector values (ex: cmov).
  113. VectorMaskSelect // The target supports vector selects with a vector
  114. // mask (ex: x86 blends).
  115. };
  116. /// Enum that specifies what a AtomicRMWInst is expanded to, if at all. Exists
  117. /// because different targets have different levels of support for these
  118. /// atomic RMW instructions, and also have different options w.r.t. what they
  119. /// should expand to.
  120. enum class AtomicRMWExpansionKind {
  121. None, // Don't expand the instruction.
  122. LLSC, // Expand the instruction into loadlinked/storeconditional; used
  123. // by ARM/AArch64. Implies `hasLoadLinkedStoreConditional`
  124. // returns true.
  125. CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
  126. };
  127. static ISD::NodeType getExtendForContent(BooleanContent Content) {
  128. switch (Content) {
  129. case UndefinedBooleanContent:
  130. // Extend by adding rubbish bits.
  131. return ISD::ANY_EXTEND;
  132. case ZeroOrOneBooleanContent:
  133. // Extend by adding zero bits.
  134. return ISD::ZERO_EXTEND;
  135. case ZeroOrNegativeOneBooleanContent:
  136. // Extend by copying the sign bit.
  137. return ISD::SIGN_EXTEND;
  138. }
  139. llvm_unreachable("Invalid content kind");
  140. }
  141. /// NOTE: The TargetMachine owns TLOF.
  142. explicit TargetLoweringBase(const TargetMachine &TM);
  143. virtual ~TargetLoweringBase() {}
  144. protected:
  145. /// \brief Initialize all of the actions to default values.
  146. void initActions();
  147. public:
  148. const TargetMachine &getTargetMachine() const { return TM; }
  149. virtual bool useSoftFloat() const { return false; }
  150. /// Return the pointer type for the given address space, defaults to
  151. /// the pointer type from the data layout.
  152. /// FIXME: The default needs to be removed once all the code is updated.
  153. MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
  154. return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  155. }
  156. /// EVT is not used in-tree, but is used by out-of-tree target.
  157. /// A documentation for this function would be nice...
  158. virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
  159. EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const;
  160. /// Returns the type to be used for the index operand of:
  161. /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
  162. /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
  163. virtual MVT getVectorIdxTy(const DataLayout &DL) const {
  164. return getPointerTy(DL);
  165. }
  166. /// Return true if the select operation is expensive for this target.
  167. bool isSelectExpensive() const { return SelectIsExpensive; }
  168. virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
  169. return true;
  170. }
  171. /// Return true if multiple condition registers are available.
  172. bool hasMultipleConditionRegisters() const {
  173. return HasMultipleConditionRegisters;
  174. }
  175. /// Return true if the target has BitExtract instructions.
  176. bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
  177. /// Return the preferred vector type legalization action.
  178. virtual TargetLoweringBase::LegalizeTypeAction
  179. getPreferredVectorAction(EVT VT) const {
  180. // The default action for one element vectors is to scalarize
  181. if (VT.getVectorNumElements() == 1)
  182. return TypeScalarizeVector;
  183. // The default action for other vectors is to promote
  184. return TypePromoteInteger;
  185. }
  186. // There are two general methods for expanding a BUILD_VECTOR node:
  187. // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
  188. // them together.
  189. // 2. Build the vector on the stack and then load it.
  190. // If this function returns true, then method (1) will be used, subject to
  191. // the constraint that all of the necessary shuffles are legal (as determined
  192. // by isShuffleMaskLegal). If this function returns false, then method (2) is
  193. // always used. The vector type, and the number of defined values, are
  194. // provided.
  195. virtual bool
  196. shouldExpandBuildVectorWithShuffles(EVT /* VT */,
  197. unsigned DefinedValues) const {
  198. return DefinedValues < 3;
  199. }
  200. /// Return true if integer divide is usually cheaper than a sequence of
  201. /// several shifts, adds, and multiplies for this target.
  202. bool isIntDivCheap() const { return IntDivIsCheap; }
  203. /// Return true if sqrt(x) is as cheap or cheaper than 1 / rsqrt(x)
  204. bool isFsqrtCheap() const {
  205. return FsqrtIsCheap;
  206. }
  207. /// Returns true if target has indicated at least one type should be bypassed.
  208. bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
  209. /// Returns map of slow types for division or remainder with corresponding
  210. /// fast types
  211. const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
  212. return BypassSlowDivWidths;
  213. }
  214. /// Return true if pow2 sdiv is cheaper than a chain of sra/srl/add/sra.
  215. bool isPow2SDivCheap() const { return Pow2SDivIsCheap; }
  216. /// Return true if Flow Control is an expensive operation that should be
  217. /// avoided.
  218. bool isJumpExpensive() const { return JumpIsExpensive; }
  219. /// Return true if selects are only cheaper than branches if the branch is
  220. /// unlikely to be predicted right.
  221. bool isPredictableSelectExpensive() const {
  222. return PredictableSelectIsExpensive;
  223. }
  224. /// isLoadBitCastBeneficial() - Return true if the following transform
  225. /// is beneficial.
  226. /// fold (conv (load x)) -> (load (conv*)x)
  227. /// On architectures that don't natively support some vector loads
  228. /// efficiently, casting the load to a smaller vector of larger types and
  229. /// loading is more efficient, however, this can be undone by optimizations in
  230. /// dag combiner.
  231. virtual bool isLoadBitCastBeneficial(EVT /* Load */,
  232. EVT /* Bitcast */) const {
  233. return true;
  234. }
  235. /// Return true if it is expected to be cheaper to do a store of a non-zero
  236. /// vector constant with the given size and type for the address space than to
  237. /// store the individual scalar element constants.
  238. virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
  239. unsigned NumElem,
  240. unsigned AddrSpace) const {
  241. return false;
  242. }
  243. /// \brief Return true if it is cheap to speculate a call to intrinsic cttz.
  244. virtual bool isCheapToSpeculateCttz() const {
  245. return false;
  246. }
  247. /// \brief Return true if it is cheap to speculate a call to intrinsic ctlz.
  248. virtual bool isCheapToSpeculateCtlz() const {
  249. return false;
  250. }
  251. /// \brief Return if the target supports combining a
  252. /// chain like:
  253. /// \code
  254. /// %andResult = and %val1, #imm-with-one-bit-set;
  255. /// %icmpResult = icmp %andResult, 0
  256. /// br i1 %icmpResult, label %dest1, label %dest2
  257. /// \endcode
  258. /// into a single machine instruction of a form like:
  259. /// \code
  260. /// brOnBitSet %register, #bitNumber, dest
  261. /// \endcode
  262. bool isMaskAndBranchFoldingLegal() const {
  263. return MaskAndBranchFoldingIsLegal;
  264. }
  265. /// \brief Return true if the target wants to use the optimization that
  266. /// turns ext(promotableInst1(...(promotableInstN(load)))) into
  267. /// promotedInst1(...(promotedInstN(ext(load)))).
  268. bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
  269. /// Return true if the target can combine store(extractelement VectorTy,
  270. /// Idx).
  271. /// \p Cost[out] gives the cost of that transformation when this is true.
  272. virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
  273. unsigned &Cost) const {
  274. return false;
  275. }
  276. /// Return true if target supports floating point exceptions.
  277. bool hasFloatingPointExceptions() const {
  278. return HasFloatingPointExceptions;
  279. }
  280. /// Return true if target always beneficiates from combining into FMA for a
  281. /// given value type. This must typically return false on targets where FMA
  282. /// takes more cycles to execute than FADD.
  283. virtual bool enableAggressiveFMAFusion(EVT VT) const {
  284. return false;
  285. }
  286. /// Return the ValueType of the result of SETCC operations.
  287. virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
  288. EVT VT) const;
  289. /// Return the ValueType for comparison libcalls. Comparions libcalls include
  290. /// floating point comparion calls, and Ordered/Unordered check calls on
  291. /// floating point numbers.
  292. virtual
  293. MVT::SimpleValueType getCmpLibcallReturnType() const;
  294. /// For targets without i1 registers, this gives the nature of the high-bits
  295. /// of boolean values held in types wider than i1.
  296. ///
  297. /// "Boolean values" are special true/false values produced by nodes like
  298. /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
  299. /// Not to be confused with general values promoted from i1. Some cpus
  300. /// distinguish between vectors of boolean and scalars; the isVec parameter
  301. /// selects between the two kinds. For example on X86 a scalar boolean should
  302. /// be zero extended from i1, while the elements of a vector of booleans
  303. /// should be sign extended from i1.
  304. ///
  305. /// Some cpus also treat floating point types the same way as they treat
  306. /// vectors instead of the way they treat scalars.
  307. BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
  308. if (isVec)
  309. return BooleanVectorContents;
  310. return isFloat ? BooleanFloatContents : BooleanContents;
  311. }
  312. BooleanContent getBooleanContents(EVT Type) const {
  313. return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
  314. }
  315. /// Return target scheduling preference.
  316. Sched::Preference getSchedulingPreference() const {
  317. return SchedPreferenceInfo;
  318. }
  319. /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
  320. /// for different nodes. This function returns the preference (or none) for
  321. /// the given node.
  322. virtual Sched::Preference getSchedulingPreference(SDNode *) const {
  323. return Sched::None;
  324. }
  325. /// Return the register class that should be used for the specified value
  326. /// type.
  327. virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
  328. const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
  329. assert(RC && "This value type is not natively supported!");
  330. return RC;
  331. }
  332. /// Return the 'representative' register class for the specified value
  333. /// type.
  334. ///
  335. /// The 'representative' register class is the largest legal super-reg
  336. /// register class for the register class of the value type. For example, on
  337. /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
  338. /// register class is GR64 on x86_64.
  339. virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
  340. const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
  341. return RC;
  342. }
  343. /// Return the cost of the 'representative' register class for the specified
  344. /// value type.
  345. virtual uint8_t getRepRegClassCostFor(MVT VT) const {
  346. return RepRegClassCostForVT[VT.SimpleTy];
  347. }
  348. /// Return true if the target has native support for the specified value type.
  349. /// This means that it has a register that directly holds it without
  350. /// promotions or expansions.
  351. bool isTypeLegal(EVT VT) const {
  352. assert(!VT.isSimple() ||
  353. (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
  354. return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
  355. }
  356. class ValueTypeActionImpl {
  357. /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
  358. /// that indicates how instruction selection should deal with the type.
  359. uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
  360. public:
  361. ValueTypeActionImpl() {
  362. std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions), 0);
  363. }
  364. LegalizeTypeAction getTypeAction(MVT VT) const {
  365. return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
  366. }
  367. void setTypeAction(MVT VT, LegalizeTypeAction Action) {
  368. unsigned I = VT.SimpleTy;
  369. ValueTypeActions[I] = Action;
  370. }
  371. };
  372. const ValueTypeActionImpl &getValueTypeActions() const {
  373. return ValueTypeActions;
  374. }
  375. /// Return how we should legalize values of this type, either it is already
  376. /// legal (return 'Legal') or we need to promote it to a larger type (return
  377. /// 'Promote'), or we need to expand it into multiple registers of smaller
  378. /// integer type (return 'Expand'). 'Custom' is not an option.
  379. LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
  380. return getTypeConversion(Context, VT).first;
  381. }
  382. LegalizeTypeAction getTypeAction(MVT VT) const {
  383. return ValueTypeActions.getTypeAction(VT);
  384. }
  385. /// For types supported by the target, this is an identity function. For
  386. /// types that must be promoted to larger types, this returns the larger type
  387. /// to promote to. For integer types that are larger than the largest integer
  388. /// register, this contains one step in the expansion to get to the smaller
  389. /// register. For illegal floating point types, this returns the integer type
  390. /// to transform to.
  391. EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
  392. return getTypeConversion(Context, VT).second;
  393. }
  394. /// For types supported by the target, this is an identity function. For
  395. /// types that must be expanded (i.e. integer types that are larger than the
  396. /// largest integer register or illegal floating point types), this returns
  397. /// the largest legal type it will be expanded to.
  398. EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
  399. assert(!VT.isVector());
  400. while (true) {
  401. switch (getTypeAction(Context, VT)) {
  402. case TypeLegal:
  403. return VT;
  404. case TypeExpandInteger:
  405. VT = getTypeToTransformTo(Context, VT);
  406. break;
  407. default:
  408. llvm_unreachable("Type is not legal nor is it to be expanded!");
  409. }
  410. }
  411. }
  412. /// Vector types are broken down into some number of legal first class types.
  413. /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
  414. /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
  415. /// turns into 4 EVT::i32 values with both PPC and X86.
  416. ///
  417. /// This method returns the number of registers needed, and the VT for each
  418. /// register. It also returns the VT and quantity of the intermediate values
  419. /// before they are promoted/expanded.
  420. unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
  421. EVT &IntermediateVT,
  422. unsigned &NumIntermediates,
  423. MVT &RegisterVT) const;
  424. struct IntrinsicInfo {
  425. unsigned opc; // target opcode
  426. EVT memVT; // memory VT
  427. const Value* ptrVal; // value representing memory location
  428. int offset; // offset off of ptrVal
  429. unsigned size; // the size of the memory location
  430. // (taken from memVT if zero)
  431. unsigned align; // alignment
  432. bool vol; // is volatile?
  433. bool readMem; // reads memory?
  434. bool writeMem; // writes memory?
  435. IntrinsicInfo() : opc(0), ptrVal(nullptr), offset(0), size(0), align(1),
  436. vol(false), readMem(false), writeMem(false) {}
  437. };
  438. /// Given an intrinsic, checks if on the target the intrinsic will need to map
  439. /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
  440. /// true and store the intrinsic information into the IntrinsicInfo that was
  441. /// passed to the function.
  442. virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
  443. unsigned /*Intrinsic*/) const {
  444. return false;
  445. }
  446. /// Returns true if the target can instruction select the specified FP
  447. /// immediate natively. If false, the legalizer will materialize the FP
  448. /// immediate as a load from a constant pool.
  449. virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
  450. return false;
  451. }
  452. /// Targets can use this to indicate that they only support *some*
  453. /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
  454. /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
  455. /// legal.
  456. virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
  457. EVT /*VT*/) const {
  458. return true;
  459. }
  460. /// Returns true if the operation can trap for the value type.
  461. ///
  462. /// VT must be a legal type. By default, we optimistically assume most
  463. /// operations don't trap except for divide and remainder.
  464. virtual bool canOpTrap(unsigned Op, EVT VT) const;
  465. /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
  466. /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
  467. /// a VAND with a constant pool entry.
  468. virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
  469. EVT /*VT*/) const {
  470. return false;
  471. }
  472. /// Return how this operation should be treated: either it is legal, needs to
  473. /// be promoted to a larger size, needs to be expanded to some other code
  474. /// sequence, or the target has a custom expander for it.
  475. LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
  476. if (VT.isExtended()) return Expand;
  477. // If a target-specific SDNode requires legalization, require the target
  478. // to provide custom legalization for it.
  479. if (Op > array_lengthof(OpActions[0])) return Custom;
  480. unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
  481. return (LegalizeAction)OpActions[I][Op];
  482. }
  483. /// Return true if the specified operation is legal on this target or can be
  484. /// made legal with custom lowering. This is used to help guide high-level
  485. /// lowering decisions.
  486. bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
  487. return (VT == MVT::Other || isTypeLegal(VT)) &&
  488. (getOperationAction(Op, VT) == Legal ||
  489. getOperationAction(Op, VT) == Custom);
  490. }
  491. /// Return true if the specified operation is legal on this target or can be
  492. /// made legal using promotion. This is used to help guide high-level lowering
  493. /// decisions.
  494. bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
  495. return (VT == MVT::Other || isTypeLegal(VT)) &&
  496. (getOperationAction(Op, VT) == Legal ||
  497. getOperationAction(Op, VT) == Promote);
  498. }
  499. /// Return true if the specified operation is illegal on this target or
  500. /// unlikely to be made legal with custom lowering. This is used to help guide
  501. /// high-level lowering decisions.
  502. bool isOperationExpand(unsigned Op, EVT VT) const {
  503. return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
  504. }
  505. /// Return true if the specified operation is legal on this target.
  506. bool isOperationLegal(unsigned Op, EVT VT) const {
  507. return (VT == MVT::Other || isTypeLegal(VT)) &&
  508. getOperationAction(Op, VT) == Legal;
  509. }
  510. /// Return how this load with extension should be treated: either it is legal,
  511. /// needs to be promoted to a larger size, needs to be expanded to some other
  512. /// code sequence, or the target has a custom expander for it.
  513. LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
  514. EVT MemVT) const {
  515. if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
  516. unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
  517. unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
  518. assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&
  519. MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!");
  520. return (LegalizeAction)LoadExtActions[ValI][MemI][ExtType];
  521. }
  522. /// Return true if the specified load with extension is legal on this target.
  523. bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
  524. return ValVT.isSimple() && MemVT.isSimple() &&
  525. getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
  526. }
  527. /// Return true if the specified load with extension is legal or custom
  528. /// on this target.
  529. bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
  530. return ValVT.isSimple() && MemVT.isSimple() &&
  531. (getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
  532. getLoadExtAction(ExtType, ValVT, MemVT) == Custom);
  533. }
  534. /// Return how this store with truncation should be treated: either it is
  535. /// legal, needs to be promoted to a larger size, needs to be expanded to some
  536. /// other code sequence, or the target has a custom expander for it.
  537. LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
  538. if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
  539. unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
  540. unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
  541. assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
  542. "Table isn't big enough!");
  543. return (LegalizeAction)TruncStoreActions[ValI][MemI];
  544. }
  545. /// Return true if the specified store with truncation is legal on this
  546. /// target.
  547. bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
  548. return isTypeLegal(ValVT) && MemVT.isSimple() &&
  549. getTruncStoreAction(ValVT.getSimpleVT(), MemVT.getSimpleVT()) == Legal;
  550. }
  551. /// Return how the indexed load should be treated: either it is legal, needs
  552. /// to be promoted to a larger size, needs to be expanded to some other code
  553. /// sequence, or the target has a custom expander for it.
  554. LegalizeAction
  555. getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
  556. assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
  557. "Table isn't big enough!");
  558. unsigned Ty = (unsigned)VT.SimpleTy;
  559. return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
  560. }
  561. /// Return true if the specified indexed load is legal on this target.
  562. bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
  563. return VT.isSimple() &&
  564. (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
  565. getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
  566. }
  567. /// Return how the indexed store should be treated: either it is legal, needs
  568. /// to be promoted to a larger size, needs to be expanded to some other code
  569. /// sequence, or the target has a custom expander for it.
  570. LegalizeAction
  571. getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
  572. assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
  573. "Table isn't big enough!");
  574. unsigned Ty = (unsigned)VT.SimpleTy;
  575. return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
  576. }
  577. /// Return true if the specified indexed load is legal on this target.
  578. bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
  579. return VT.isSimple() &&
  580. (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
  581. getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
  582. }
  583. /// Return how the condition code should be treated: either it is legal, needs
  584. /// to be expanded to some other code sequence, or the target has a custom
  585. /// expander for it.
  586. LegalizeAction
  587. getCondCodeAction(ISD::CondCode CC, MVT VT) const {
  588. assert((unsigned)CC < array_lengthof(CondCodeActions) &&
  589. ((unsigned)VT.SimpleTy >> 4) < array_lengthof(CondCodeActions[0]) &&
  590. "Table isn't big enough!");
  591. // See setCondCodeAction for how this is encoded.
  592. uint32_t Shift = 2 * (VT.SimpleTy & 0xF);
  593. uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 4];
  594. LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0x3);
  595. assert(Action != Promote && "Can't promote condition code!");
  596. return Action;
  597. }
  598. /// Return true if the specified condition code is legal on this target.
  599. bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
  600. return
  601. getCondCodeAction(CC, VT) == Legal ||
  602. getCondCodeAction(CC, VT) == Custom;
  603. }
  604. /// If the action for this operation is to promote, this method returns the
  605. /// ValueType to promote to.
  606. MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
  607. assert(getOperationAction(Op, VT) == Promote &&
  608. "This operation isn't promoted!");
  609. // See if this has an explicit type specified.
  610. std::map<std::pair<unsigned, MVT::SimpleValueType>,
  611. MVT::SimpleValueType>::const_iterator PTTI =
  612. PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
  613. if (PTTI != PromoteToType.end()) return PTTI->second;
  614. assert((VT.isInteger() || VT.isFloatingPoint()) &&
  615. "Cannot autopromote this type, add it with AddPromotedToType.");
  616. MVT NVT = VT;
  617. do {
  618. NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
  619. assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
  620. "Didn't find type to promote to!");
  621. } while (!isTypeLegal(NVT) ||
  622. getOperationAction(Op, NVT) == Promote);
  623. return NVT;
  624. }
  625. /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
  626. /// operations except for the pointer size. If AllowUnknown is true, this
  627. /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
  628. /// otherwise it will assert.
  629. EVT getValueType(const DataLayout &DL, Type *Ty,
  630. bool AllowUnknown = false) const {
  631. // Lower scalar pointers to native pointer types.
  632. if (PointerType *PTy = dyn_cast<PointerType>(Ty))
  633. return getPointerTy(DL, PTy->getAddressSpace());
  634. if (Ty->isVectorTy()) {
  635. VectorType *VTy = cast<VectorType>(Ty);
  636. Type *Elm = VTy->getElementType();
  637. // Lower vectors of pointers to native pointer types.
  638. if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
  639. EVT PointerTy(getPointerTy(DL, PT->getAddressSpace()));
  640. Elm = PointerTy.getTypeForEVT(Ty->getContext());
  641. }
  642. return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
  643. VTy->getNumElements());
  644. }
  645. return EVT::getEVT(Ty, AllowUnknown);
  646. }
  647. /// Return the MVT corresponding to this LLVM type. See getValueType.
  648. MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
  649. bool AllowUnknown = false) const {
  650. return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
  651. }
  652. /// Return the desired alignment for ByVal or InAlloca aggregate function
  653. /// arguments in the caller parameter area. This is the actual alignment, not
  654. /// its logarithm.
  655. virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
  656. /// Return the type of registers that this ValueType will eventually require.
  657. MVT getRegisterType(MVT VT) const {
  658. assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
  659. return RegisterTypeForVT[VT.SimpleTy];
  660. }
  661. /// Return the type of registers that this ValueType will eventually require.
  662. MVT getRegisterType(LLVMContext &Context, EVT VT) const {
  663. if (VT.isSimple()) {
  664. assert((unsigned)VT.getSimpleVT().SimpleTy <
  665. array_lengthof(RegisterTypeForVT));
  666. return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
  667. }
  668. if (VT.isVector()) {
  669. EVT VT1;
  670. MVT RegisterVT;
  671. unsigned NumIntermediates;
  672. (void)getVectorTypeBreakdown(Context, VT, VT1,
  673. NumIntermediates, RegisterVT);
  674. return RegisterVT;
  675. }
  676. if (VT.isInteger()) {
  677. return getRegisterType(Context, getTypeToTransformTo(Context, VT));
  678. }
  679. llvm_unreachable("Unsupported extended type!");
  680. }
  681. /// Return the number of registers that this ValueType will eventually
  682. /// require.
  683. ///
  684. /// This is one for any types promoted to live in larger registers, but may be
  685. /// more than one for types (like i64) that are split into pieces. For types
  686. /// like i140, which are first promoted then expanded, it is the number of
  687. /// registers needed to hold all the bits of the original type. For an i140
  688. /// on a 32 bit machine this means 5 registers.
  689. unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
  690. if (VT.isSimple()) {
  691. assert((unsigned)VT.getSimpleVT().SimpleTy <
  692. array_lengthof(NumRegistersForVT));
  693. return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
  694. }
  695. if (VT.isVector()) {
  696. EVT VT1;
  697. MVT VT2;
  698. unsigned NumIntermediates;
  699. return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
  700. }
  701. if (VT.isInteger()) {
  702. unsigned BitWidth = VT.getSizeInBits();
  703. unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
  704. return (BitWidth + RegWidth - 1) / RegWidth;
  705. }
  706. llvm_unreachable("Unsupported extended type!");
  707. }
  708. /// If true, then instruction selection should seek to shrink the FP constant
  709. /// of the specified type to a smaller type in order to save space and / or
  710. /// reduce runtime.
  711. virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
  712. // Return true if it is profitable to reduce the given load node to a smaller
  713. // type.
  714. //
  715. // e.g. (i16 (trunc (i32 (load x))) -> i16 load x should be performed
  716. virtual bool shouldReduceLoadWidth(SDNode *Load,
  717. ISD::LoadExtType ExtTy,
  718. EVT NewVT) const {
  719. return true;
  720. }
  721. /// When splitting a value of the specified type into parts, does the Lo
  722. /// or Hi part come first? This usually follows the endianness, except
  723. /// for ppcf128, where the Hi part always comes first.
  724. bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
  725. return DL.isBigEndian() || VT == MVT::ppcf128;
  726. }
  727. /// If true, the target has custom DAG combine transformations that it can
  728. /// perform for the specified node.
  729. bool hasTargetDAGCombine(ISD::NodeType NT) const {
  730. assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
  731. return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
  732. }
  733. /// \brief Get maximum # of store operations permitted for llvm.memset
  734. ///
  735. /// This function returns the maximum number of store operations permitted
  736. /// to replace a call to llvm.memset. The value is set by the target at the
  737. /// performance threshold for such a replacement. If OptSize is true,
  738. /// return the limit for functions that have OptSize attribute.
  739. unsigned getMaxStoresPerMemset(bool OptSize) const {
  740. return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
  741. }
  742. /// \brief Get maximum # of store operations permitted for llvm.memcpy
  743. ///
  744. /// This function returns the maximum number of store operations permitted
  745. /// to replace a call to llvm.memcpy. The value is set by the target at the
  746. /// performance threshold for such a replacement. If OptSize is true,
  747. /// return the limit for functions that have OptSize attribute.
  748. unsigned getMaxStoresPerMemcpy(bool OptSize) const {
  749. return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
  750. }
  751. /// \brief Get maximum # of store operations permitted for llvm.memmove
  752. ///
  753. /// This function returns the maximum number of store operations permitted
  754. /// to replace a call to llvm.memmove. The value is set by the target at the
  755. /// performance threshold for such a replacement. If OptSize is true,
  756. /// return the limit for functions that have OptSize attribute.
  757. unsigned getMaxStoresPerMemmove(bool OptSize) const {
  758. return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
  759. }
  760. /// \brief Determine if the target supports unaligned memory accesses.
  761. ///
  762. /// This function returns true if the target allows unaligned memory accesses
  763. /// of the specified type in the given address space. If true, it also returns
  764. /// whether the unaligned memory access is "fast" in the last argument by
  765. /// reference. This is used, for example, in situations where an array
  766. /// copy/move/set is converted to a sequence of store operations. Its use
  767. /// helps to ensure that such replacements don't generate code that causes an
  768. /// alignment error (trap) on the target machine.
  769. virtual bool allowsMisalignedMemoryAccesses(EVT,
  770. unsigned AddrSpace = 0,
  771. unsigned Align = 1,
  772. bool * /*Fast*/ = nullptr) const {
  773. return false;
  774. }
  775. /// Returns the target specific optimal type for load and store operations as
  776. /// a result of memset, memcpy, and memmove lowering.
  777. ///
  778. /// If DstAlign is zero that means it's safe to destination alignment can
  779. /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
  780. /// a need to check it against alignment requirement, probably because the
  781. /// source does not need to be loaded. If 'IsMemset' is true, that means it's
  782. /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
  783. /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
  784. /// does not need to be loaded. It returns EVT::Other if the type should be
  785. /// determined using generic target-independent logic.
  786. virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
  787. unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
  788. bool /*IsMemset*/,
  789. bool /*ZeroMemset*/,
  790. bool /*MemcpyStrSrc*/,
  791. MachineFunction &/*MF*/) const {
  792. return MVT::Other;
  793. }
  794. /// Returns true if it's safe to use load / store of the specified type to
  795. /// expand memcpy / memset inline.
  796. ///
  797. /// This is mostly true for all types except for some special cases. For
  798. /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
  799. /// fstpl which also does type conversion. Note the specified type doesn't
  800. /// have to be legal as the hook is used before type legalization.
  801. virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
  802. /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
  803. bool usesUnderscoreSetJmp() const {
  804. return UseUnderscoreSetJmp;
  805. }
  806. /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
  807. bool usesUnderscoreLongJmp() const {
  808. return UseUnderscoreLongJmp;
  809. }
  810. /// Return integer threshold on number of blocks to use jump tables rather
  811. /// than if sequence.
  812. int getMinimumJumpTableEntries() const {
  813. return MinimumJumpTableEntries;
  814. }
  815. /// If a physical register, this specifies the register that
  816. /// llvm.savestack/llvm.restorestack should save and restore.
  817. unsigned getStackPointerRegisterToSaveRestore() const {
  818. return StackPointerRegisterToSaveRestore;
  819. }
  820. /// If a physical register, this returns the register that receives the
  821. /// exception address on entry to a landing pad.
  822. unsigned getExceptionPointerRegister() const {
  823. return ExceptionPointerRegister;
  824. }
  825. /// If a physical register, this returns the register that receives the
  826. /// exception typeid on entry to a landing pad.
  827. unsigned getExceptionSelectorRegister() const {
  828. return ExceptionSelectorRegister;
  829. }
  830. /// Returns the target's jmp_buf size in bytes (if never set, the default is
  831. /// 200)
  832. unsigned getJumpBufSize() const {
  833. return JumpBufSize;
  834. }
  835. /// Returns the target's jmp_buf alignment in bytes (if never set, the default
  836. /// is 0)
  837. unsigned getJumpBufAlignment() const {
  838. return JumpBufAlignment;
  839. }
  840. /// Return the minimum stack alignment of an argument.
  841. unsigned getMinStackArgumentAlignment() const {
  842. return MinStackArgumentAlignment;
  843. }
  844. /// Return the minimum function alignment.
  845. unsigned getMinFunctionAlignment() const {
  846. return MinFunctionAlignment;
  847. }
  848. /// Return the preferred function alignment.
  849. unsigned getPrefFunctionAlignment() const {
  850. return PrefFunctionAlignment;
  851. }
  852. /// Return the preferred loop alignment.
  853. virtual unsigned getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
  854. return PrefLoopAlignment;
  855. }
  856. /// Return whether the DAG builder should automatically insert fences and
  857. /// reduce ordering for atomics.
  858. bool getInsertFencesForAtomic() const {
  859. return InsertFencesForAtomic;
  860. }
  861. /// Return true if the target stores stack protector cookies at a fixed offset
  862. /// in some non-standard address space, and populates the address space and
  863. /// offset as appropriate.
  864. virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
  865. unsigned &/*Offset*/) const {
  866. return false;
  867. }
  868. /// Returns true if a cast between SrcAS and DestAS is a noop.
  869. virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
  870. return false;
  871. }
  872. /// Return true if the pointer arguments to CI should be aligned by aligning
  873. /// the object whose address is being passed. If so then MinSize is set to the
  874. /// minimum size the object must be to be aligned and PrefAlign is set to the
  875. /// preferred alignment.
  876. virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
  877. unsigned & /*PrefAlign*/) const {
  878. return false;
  879. }
  880. //===--------------------------------------------------------------------===//
  881. /// \name Helpers for TargetTransformInfo implementations
  882. /// @{
  883. /// Get the ISD node that corresponds to the Instruction class opcode.
  884. int InstructionOpcodeToISD(unsigned Opcode) const;
  885. /// Estimate the cost of type-legalization and the legalized type.
  886. std::pair<unsigned, MVT> getTypeLegalizationCost(const DataLayout &DL,
  887. Type *Ty) const;
  888. /// @}
  889. //===--------------------------------------------------------------------===//
  890. /// \name Helpers for atomic expansion.
  891. /// @{
  892. /// True if AtomicExpandPass should use emitLoadLinked/emitStoreConditional
  893. /// and expand AtomicCmpXchgInst.
  894. virtual bool hasLoadLinkedStoreConditional() const { return false; }
  895. /// Perform a load-linked operation on Addr, returning a "Value *" with the
  896. /// corresponding pointee type. This may entail some non-trivial operations to
  897. /// truncate or reconstruct types that will be illegal in the backend. See
  898. /// ARMISelLowering for an example implementation.
  899. virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
  900. AtomicOrdering Ord) const {
  901. llvm_unreachable("Load linked unimplemented on this target");
  902. }
  903. /// Perform a store-conditional operation to Addr. Return the status of the
  904. /// store. This should be 0 if the store succeeded, non-zero otherwise.
  905. virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
  906. Value *Addr, AtomicOrdering Ord) const {
  907. llvm_unreachable("Store conditional unimplemented on this target");
  908. }
  909. /// Inserts in the IR a target-specific intrinsic specifying a fence.
  910. /// It is called by AtomicExpandPass before expanding an
  911. /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad.
  912. /// RMW and CmpXchg set both IsStore and IsLoad to true.
  913. /// This function should either return a nullptr, or a pointer to an IR-level
  914. /// Instruction*. Even complex fence sequences can be represented by a
  915. /// single Instruction* through an intrinsic to be lowered later.
  916. /// Backends with !getInsertFencesForAtomic() should keep a no-op here.
  917. /// Backends should override this method to produce target-specific intrinsic
  918. /// for their fences.
  919. /// FIXME: Please note that the default implementation here in terms of
  920. /// IR-level fences exists for historical/compatibility reasons and is
  921. /// *unsound* ! Fences cannot, in general, be used to restore sequential
  922. /// consistency. For example, consider the following example:
  923. /// atomic<int> x = y = 0;
  924. /// int r1, r2, r3, r4;
  925. /// Thread 0:
  926. /// x.store(1);
  927. /// Thread 1:
  928. /// y.store(1);
  929. /// Thread 2:
  930. /// r1 = x.load();
  931. /// r2 = y.load();
  932. /// Thread 3:
  933. /// r3 = y.load();
  934. /// r4 = x.load();
  935. /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
  936. /// seq_cst. But if they are lowered to monotonic accesses, no amount of
  937. /// IR-level fences can prevent it.
  938. /// @{
  939. virtual Instruction *emitLeadingFence(IRBuilder<> &Builder,
  940. AtomicOrdering Ord, bool IsStore,
  941. bool IsLoad) const {
  942. if (!getInsertFencesForAtomic())
  943. return nullptr;
  944. if (isAtLeastRelease(Ord) && IsStore)
  945. return Builder.CreateFence(Ord);
  946. else
  947. return nullptr;
  948. }
  949. virtual Instruction *emitTrailingFence(IRBuilder<> &Builder,
  950. AtomicOrdering Ord, bool IsStore,
  951. bool IsLoad) const {
  952. if (!getInsertFencesForAtomic())
  953. return nullptr;
  954. if (isAtLeastAcquire(Ord))
  955. return Builder.CreateFence(Ord);
  956. else
  957. return nullptr;
  958. }
  959. /// @}
  960. /// Returns true if the given (atomic) store should be expanded by the
  961. /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
  962. virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
  963. return false;
  964. }
  965. /// Returns true if arguments should be sign-extended in lib calls.
  966. virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
  967. return IsSigned;
  968. }
  969. /// Returns true if the given (atomic) load should be expanded by the
  970. /// IR-level AtomicExpand pass into a load-linked instruction
  971. /// (through emitLoadLinked()).
  972. virtual bool shouldExpandAtomicLoadInIR(LoadInst *LI) const { return false; }
  973. /// Returns how the IR-level AtomicExpand pass should expand the given
  974. /// AtomicRMW, if at all. Default is to never expand.
  975. virtual AtomicRMWExpansionKind
  976. shouldExpandAtomicRMWInIR(AtomicRMWInst *) const {
  977. return AtomicRMWExpansionKind::None;
  978. }
  979. /// On some platforms, an AtomicRMW that never actually modifies the value
  980. /// (such as fetch_add of 0) can be turned into a fence followed by an
  981. /// atomic load. This may sound useless, but it makes it possible for the
  982. /// processor to keep the cacheline shared, dramatically improving
  983. /// performance. And such idempotent RMWs are useful for implementing some
  984. /// kinds of locks, see for example (justification + benchmarks):
  985. /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
  986. /// This method tries doing that transformation, returning the atomic load if
  987. /// it succeeds, and nullptr otherwise.
  988. /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
  989. /// another round of expansion.
  990. virtual LoadInst *
  991. lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
  992. return nullptr;
  993. }
  994. /// Returns true if we should normalize
  995. /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
  996. /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
  997. /// that it saves us from materializing N0 and N1 in an integer register.
  998. /// Targets that are able to perform and/or on flags should return false here.
  999. virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
  1000. EVT VT) const {
  1001. // If a target has multiple condition registers, then it likely has logical
  1002. // operations on those registers.
  1003. if (hasMultipleConditionRegisters())
  1004. return false;
  1005. // Only do the transform if the value won't be split into multiple
  1006. // registers.
  1007. LegalizeTypeAction Action = getTypeAction(Context, VT);
  1008. return Action != TypeExpandInteger && Action != TypeExpandFloat &&
  1009. Action != TypeSplitVector;
  1010. }
  1011. //===--------------------------------------------------------------------===//
  1012. // TargetLowering Configuration Methods - These methods should be invoked by
  1013. // the derived class constructor to configure this object for the target.
  1014. //
  1015. protected:
  1016. /// Specify how the target extends the result of integer and floating point
  1017. /// boolean values from i1 to a wider type. See getBooleanContents.
  1018. void setBooleanContents(BooleanContent Ty) {
  1019. BooleanContents = Ty;
  1020. BooleanFloatContents = Ty;
  1021. }
  1022. /// Specify how the target extends the result of integer and floating point
  1023. /// boolean values from i1 to a wider type. See getBooleanContents.
  1024. void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
  1025. BooleanContents = IntTy;
  1026. BooleanFloatContents = FloatTy;
  1027. }
  1028. /// Specify how the target extends the result of a vector boolean value from a
  1029. /// vector of i1 to a wider type. See getBooleanContents.
  1030. void setBooleanVectorContents(BooleanContent Ty) {
  1031. BooleanVectorContents = Ty;
  1032. }
  1033. /// Specify the target scheduling preference.
  1034. void setSchedulingPreference(Sched::Preference Pref) {
  1035. SchedPreferenceInfo = Pref;
  1036. }
  1037. /// Indicate whether this target prefers to use _setjmp to implement
  1038. /// llvm.setjmp or the version without _. Defaults to false.
  1039. void setUseUnderscoreSetJmp(bool Val) {
  1040. UseUnderscoreSetJmp = Val;
  1041. }
  1042. /// Indicate whether this target prefers to use _longjmp to implement
  1043. /// llvm.longjmp or the version without _. Defaults to false.
  1044. void setUseUnderscoreLongJmp(bool Val) {
  1045. UseUnderscoreLongJmp = Val;
  1046. }
  1047. /// Indicate the number of blocks to generate jump tables rather than if
  1048. /// sequence.
  1049. void setMinimumJumpTableEntries(int Val) {
  1050. MinimumJumpTableEntries = Val;
  1051. }
  1052. /// If set to a physical register, this specifies the register that
  1053. /// llvm.savestack/llvm.restorestack should save and restore.
  1054. void setStackPointerRegisterToSaveRestore(unsigned R) {
  1055. StackPointerRegisterToSaveRestore = R;
  1056. }
  1057. /// If set to a physical register, this sets the register that receives the
  1058. /// exception address on entry to a landing pad.
  1059. void setExceptionPointerRegister(unsigned R) {
  1060. ExceptionPointerRegister = R;
  1061. }
  1062. /// If set to a physical register, this sets the register that receives the
  1063. /// exception typeid on entry to a landing pad.
  1064. void setExceptionSelectorRegister(unsigned R) {
  1065. ExceptionSelectorRegister = R;
  1066. }
  1067. /// Tells the code generator not to expand operations into sequences that use
  1068. /// the select operations if possible.
  1069. void setSelectIsExpensive(bool isExpensive = true) {
  1070. SelectIsExpensive = isExpensive;
  1071. }
  1072. /// Tells the code generator that the target has multiple (allocatable)
  1073. /// condition registers that can be used to store the results of comparisons
  1074. /// for use by selects and conditional branches. With multiple condition
  1075. /// registers, the code generator will not aggressively sink comparisons into
  1076. /// the blocks of their users.
  1077. void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
  1078. HasMultipleConditionRegisters = hasManyRegs;
  1079. }
  1080. /// Tells the code generator that the target has BitExtract instructions.
  1081. /// The code generator will aggressively sink "shift"s into the blocks of
  1082. /// their users if the users will generate "and" instructions which can be
  1083. /// combined with "shift" to BitExtract instructions.
  1084. void setHasExtractBitsInsn(bool hasExtractInsn = true) {
  1085. HasExtractBitsInsn = hasExtractInsn;
  1086. }
  1087. /// Tells the code generator not to expand logic operations on comparison
  1088. /// predicates into separate sequences that increase the amount of flow
  1089. /// control.
  1090. void setJumpIsExpensive(bool isExpensive = true);
  1091. /// Tells the code generator that integer divide is expensive, and if
  1092. /// possible, should be replaced by an alternate sequence of instructions not
  1093. /// containing an integer divide.
  1094. void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
  1095. /// Tells the code generator that fsqrt is cheap, and should not be replaced
  1096. /// with an alternative sequence of instructions.
  1097. void setFsqrtIsCheap(bool isCheap = true) { FsqrtIsCheap = isCheap; }
  1098. /// Tells the code generator that this target supports floating point
  1099. /// exceptions and cares about preserving floating point exception behavior.
  1100. void setHasFloatingPointExceptions(bool FPExceptions = true) {
  1101. HasFloatingPointExceptions = FPExceptions;
  1102. }
  1103. /// Tells the code generator which bitwidths to bypass.
  1104. void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
  1105. BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
  1106. }
  1107. /// Tells the code generator that it shouldn't generate sra/srl/add/sra for a
  1108. /// signed divide by power of two; let the target handle it.
  1109. void setPow2SDivIsCheap(bool isCheap = true) { Pow2SDivIsCheap = isCheap; }
  1110. /// Add the specified register class as an available regclass for the
  1111. /// specified value type. This indicates the selector can handle values of
  1112. /// that class natively.
  1113. void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
  1114. assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
  1115. AvailableRegClasses.push_back(std::make_pair(VT, RC));
  1116. RegClassForVT[VT.SimpleTy] = RC;
  1117. }
  1118. /// Remove all register classes.
  1119. void clearRegisterClasses() {
  1120. memset(RegClassForVT, 0,MVT::LAST_VALUETYPE * sizeof(TargetRegisterClass*));
  1121. AvailableRegClasses.clear();
  1122. }
  1123. /// \brief Remove all operation actions.
  1124. void clearOperationActions() {
  1125. }
  1126. /// Return the largest legal super-reg register class of the register class
  1127. /// for the specified type and its associated "cost".
  1128. virtual std::pair<const TargetRegisterClass *, uint8_t>
  1129. findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
  1130. /// Once all of the register classes are added, this allows us to compute
  1131. /// derived properties we expose.
  1132. void computeRegisterProperties(const TargetRegisterInfo *TRI);
  1133. /// Indicate that the specified operation does not work with the specified
  1134. /// type and indicate what to do about it.
  1135. void setOperationAction(unsigned Op, MVT VT,
  1136. LegalizeAction Action) {
  1137. assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
  1138. OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
  1139. }
  1140. /// Indicate that the specified load with extension does not work with the
  1141. /// specified type and indicate what to do about it.
  1142. void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
  1143. LegalizeAction Action) {
  1144. assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
  1145. MemVT.isValid() && "Table isn't big enough!");
  1146. LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy][ExtType] = (uint8_t)Action;
  1147. }
  1148. /// Indicate that the specified truncating store does not work with the
  1149. /// specified type and indicate what to do about it.
  1150. void setTruncStoreAction(MVT ValVT, MVT MemVT,
  1151. LegalizeAction Action) {
  1152. assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
  1153. TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
  1154. }
  1155. /// Indicate that the specified indexed load does or does not work with the
  1156. /// specified type and indicate what to do abort it.
  1157. ///
  1158. /// NOTE: All indexed mode loads are initialized to Expand in
  1159. /// TargetLowering.cpp
  1160. void setIndexedLoadAction(unsigned IdxMode, MVT VT,
  1161. LegalizeAction Action) {
  1162. assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
  1163. (unsigned)Action < 0xf && "Table isn't big enough!");
  1164. // Load action are kept in the upper half.
  1165. IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
  1166. IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
  1167. }
  1168. /// Indicate that the specified indexed store does or does not work with the
  1169. /// specified type and indicate what to do about it.
  1170. ///
  1171. /// NOTE: All indexed mode stores are initialized to Expand in
  1172. /// TargetLowering.cpp
  1173. void setIndexedStoreAction(unsigned IdxMode, MVT VT,
  1174. LegalizeAction Action) {
  1175. assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
  1176. (unsigned)Action < 0xf && "Table isn't big enough!");
  1177. // Store action are kept in the lower half.
  1178. IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
  1179. IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
  1180. }
  1181. /// Indicate that the specified condition code is or isn't supported on the
  1182. /// target and indicate what to do about it.
  1183. void setCondCodeAction(ISD::CondCode CC, MVT VT,
  1184. LegalizeAction Action) {
  1185. assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
  1186. "Table isn't big enough!");
  1187. /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 32-bit
  1188. /// value and the upper 27 bits index into the second dimension of the array
  1189. /// to select what 32-bit value to use.
  1190. uint32_t Shift = 2 * (VT.SimpleTy & 0xF);
  1191. CondCodeActions[CC][VT.SimpleTy >> 4] &= ~((uint32_t)0x3 << Shift);
  1192. CondCodeActions[CC][VT.SimpleTy >> 4] |= (uint32_t)Action << Shift;
  1193. }
  1194. /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
  1195. /// to trying a larger integer/fp until it can find one that works. If that
  1196. /// default is insufficient, this method can be used by the target to override
  1197. /// the default.
  1198. void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
  1199. PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
  1200. }
  1201. /// Targets should invoke this method for each target independent node that
  1202. /// they want to provide a custom DAG combiner for by implementing the
  1203. /// PerformDAGCombine virtual method.
  1204. void setTargetDAGCombine(ISD::NodeType NT) {
  1205. assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
  1206. TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
  1207. }
  1208. /// Set the target's required jmp_buf buffer size (in bytes); default is 200
  1209. void setJumpBufSize(unsigned Size) {
  1210. JumpBufSize = Size;
  1211. }
  1212. /// Set the target's required jmp_buf buffer alignment (in bytes); default is
  1213. /// 0
  1214. void setJumpBufAlignment(unsigned Align) {
  1215. JumpBufAlignment = Align;
  1216. }
  1217. /// Set the target's minimum function alignment (in log2(bytes))
  1218. void setMinFunctionAlignment(unsigned Align) {
  1219. MinFunctionAlignment = Align;
  1220. }
  1221. /// Set the target's preferred function alignment. This should be set if
  1222. /// there is a performance benefit to higher-than-minimum alignment (in
  1223. /// log2(bytes))
  1224. void setPrefFunctionAlignment(unsigned Align) {
  1225. PrefFunctionAlignment = Align;
  1226. }
  1227. /// Set the target's preferred loop alignment. Default alignment is zero, it
  1228. /// means the target does not care about loop alignment. The alignment is
  1229. /// specified in log2(bytes). The target may also override
  1230. /// getPrefLoopAlignment to provide per-loop values.
  1231. void setPrefLoopAlignment(unsigned Align) {
  1232. PrefLoopAlignment = Align;
  1233. }
  1234. /// Set the minimum stack alignment of an argument (in log2(bytes)).
  1235. void setMinStackArgumentAlignment(unsigned Align) {
  1236. MinStackArgumentAlignment = Align;
  1237. }
  1238. /// Set if the DAG builder should automatically insert fences and reduce the
  1239. /// order of atomic memory operations to Monotonic.
  1240. void setInsertFencesForAtomic(bool fence) {
  1241. InsertFencesForAtomic = fence;
  1242. }
  1243. public:
  1244. //===--------------------------------------------------------------------===//
  1245. // Addressing mode description hooks (used by LSR etc).
  1246. //
  1247. /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
  1248. /// instructions reading the address. This allows as much computation as
  1249. /// possible to be done in the address mode for that operand. This hook lets
  1250. /// targets also pass back when this should be done on intrinsics which
  1251. /// load/store.
  1252. virtual bool GetAddrModeArguments(IntrinsicInst * /*I*/,
  1253. SmallVectorImpl<Value*> &/*Ops*/,
  1254. Type *&/*AccessTy*/,
  1255. unsigned AddrSpace = 0) const {
  1256. return false;
  1257. }
  1258. /// This represents an addressing mode of:
  1259. /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
  1260. /// If BaseGV is null, there is no BaseGV.
  1261. /// If BaseOffs is zero, there is no base offset.
  1262. /// If HasBaseReg is false, there is no base register.
  1263. /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
  1264. /// no scale.
  1265. struct AddrMode {
  1266. GlobalValue *BaseGV;
  1267. int64_t BaseOffs;
  1268. bool HasBaseReg;
  1269. int64_t Scale;
  1270. AddrMode() : BaseGV(nullptr), BaseOffs(0), HasBaseReg(false), Scale(0) {}
  1271. };
  1272. /// Return true if the addressing mode represented by AM is legal for this
  1273. /// target, for a load/store of the specified type.
  1274. ///
  1275. /// The type may be VoidTy, in which case only return true if the addressing
  1276. /// mode is legal for a load/store of any legal type. TODO: Handle
  1277. /// pre/postinc as well.
  1278. ///
  1279. /// If the address space cannot be determined, it will be -1.
  1280. ///
  1281. /// TODO: Remove default argument
  1282. virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
  1283. Type *Ty, unsigned AddrSpace) const;
  1284. /// \brief Return the cost of the scaling factor used in the addressing mode
  1285. /// represented by AM for this target, for a load/store of the specified type.
  1286. ///
  1287. /// If the AM is supported, the return value must be >= 0.
  1288. /// If the AM is not supported, it returns a negative value.
  1289. /// TODO: Handle pre/postinc as well.
  1290. /// TODO: Remove default argument
  1291. virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
  1292. Type *Ty, unsigned AS = 0) const {
  1293. // Default: assume that any scaling factor used in a legal AM is free.
  1294. if (isLegalAddressingMode(DL, AM, Ty, AS))
  1295. return 0;
  1296. return -1;
  1297. }
  1298. /// Return true if the specified immediate is legal icmp immediate, that is
  1299. /// the target has icmp instructions which can compare a register against the
  1300. /// immediate without having to materialize the immediate into a register.
  1301. virtual bool isLegalICmpImmediate(int64_t) const {
  1302. return true;
  1303. }
  1304. /// Return true if the specified immediate is legal add immediate, that is the
  1305. /// target has add instructions which can add a register with the immediate
  1306. /// without having to materialize the immediate into a register.
  1307. virtual bool isLegalAddImmediate(int64_t) const {
  1308. return true;
  1309. }
  1310. /// Return true if it's significantly cheaper to shift a vector by a uniform
  1311. /// scalar than by an amount which will vary across each lane. On x86, for
  1312. /// example, there is a "psllw" instruction for the former case, but no simple
  1313. /// instruction for a general "a << b" operation on vectors.
  1314. virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
  1315. return false;
  1316. }
  1317. /// Return true if it's free to truncate a value of type Ty1 to type
  1318. /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
  1319. /// by referencing its sub-register AX.
  1320. virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
  1321. return false;
  1322. }
  1323. /// Return true if a truncation from Ty1 to Ty2 is permitted when deciding
  1324. /// whether a call is in tail position. Typically this means that both results
  1325. /// would be assigned to the same register or stack slot, but it could mean
  1326. /// the target performs adequate checks of its own before proceeding with the
  1327. /// tail call.
  1328. virtual bool allowTruncateForTailCall(Type * /*Ty1*/, Type * /*Ty2*/) const {
  1329. return false;
  1330. }
  1331. virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
  1332. return false;
  1333. }
  1334. virtual bool isProfitableToHoist(Instruction *I) const { return true; }
  1335. /// Return true if the extension represented by \p I is free.
  1336. /// Unlikely the is[Z|FP]ExtFree family which is based on types,
  1337. /// this method can use the context provided by \p I to decide
  1338. /// whether or not \p I is free.
  1339. /// This method extends the behavior of the is[Z|FP]ExtFree family.
  1340. /// In other words, if is[Z|FP]Free returns true, then this method
  1341. /// returns true as well. The converse is not true.
  1342. /// The target can perform the adequate checks by overriding isExtFreeImpl.
  1343. /// \pre \p I must be a sign, zero, or fp extension.
  1344. bool isExtFree(const Instruction *I) const {
  1345. switch (I->getOpcode()) {
  1346. case Instruction::FPExt:
  1347. if (isFPExtFree(EVT::getEVT(I->getType())))
  1348. return true;
  1349. break;
  1350. case Instruction::ZExt:
  1351. if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
  1352. return true;
  1353. break;
  1354. case Instruction::SExt:
  1355. break;
  1356. default:
  1357. llvm_unreachable("Instruction is not an extension");
  1358. }
  1359. return isExtFreeImpl(I);
  1360. }
  1361. /// Return true if any actual instruction that defines a value of type Ty1
  1362. /// implicitly zero-extends the value to Ty2 in the result register.
  1363. ///
  1364. /// This does not necessarily include registers defined in unknown ways, such
  1365. /// as incoming arguments, or copies from unknown virtual registers. Also, if
  1366. /// isTruncateFree(Ty2, Ty1) is true, this does not necessarily apply to
  1367. /// truncate instructions. e.g. on x86-64, all instructions that define 32-bit
  1368. /// values implicit zero-extend the result out to 64 bits.
  1369. virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
  1370. return false;
  1371. }
  1372. virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
  1373. return false;
  1374. }
  1375. /// Return true if the target supplies and combines to a paired load
  1376. /// two loaded values of type LoadedType next to each other in memory.
  1377. /// RequiredAlignment gives the minimal alignment constraints that must be met
  1378. /// to be able to select this paired load.
  1379. ///
  1380. /// This information is *not* used to generate actual paired loads, but it is
  1381. /// used to generate a sequence of loads that is easier to combine into a
  1382. /// paired load.
  1383. /// For instance, something like this:
  1384. /// a = load i64* addr
  1385. /// b = trunc i64 a to i32
  1386. /// c = lshr i64 a, 32
  1387. /// d = trunc i64 c to i32
  1388. /// will be optimized into:
  1389. /// b = load i32* addr1
  1390. /// d = load i32* addr2
  1391. /// Where addr1 = addr2 +/- sizeof(i32).
  1392. ///
  1393. /// In other words, unless the target performs a post-isel load combining,
  1394. /// this information should not be provided because it will generate more
  1395. /// loads.
  1396. virtual bool hasPairedLoad(Type * /*LoadedType*/,
  1397. unsigned & /*RequiredAligment*/) const {
  1398. return false;
  1399. }
  1400. virtual bool hasPairedLoad(EVT /*LoadedType*/,
  1401. unsigned & /*RequiredAligment*/) const {
  1402. return false;
  1403. }
  1404. /// \brief Get the maximum supported factor for interleaved memory accesses.
  1405. /// Default to be the minimum interleave factor: 2.
  1406. virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
  1407. /// \brief Lower an interleaved load to target specific intrinsics. Return
  1408. /// true on success.
  1409. ///
  1410. /// \p LI is the vector load instruction.
  1411. /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
  1412. /// \p Indices is the corresponding indices for each shufflevector.
  1413. /// \p Factor is the interleave factor.
  1414. virtual bool lowerInterleavedLoad(LoadInst *LI,
  1415. ArrayRef<ShuffleVectorInst *> Shuffles,
  1416. ArrayRef<unsigned> Indices,
  1417. unsigned Factor) const {
  1418. return false;
  1419. }
  1420. /// \brief Lower an interleaved store to target specific intrinsics. Return
  1421. /// true on success.
  1422. ///
  1423. /// \p SI is the vector store instruction.
  1424. /// \p SVI is the shufflevector to RE-interleave the stored vector.
  1425. /// \p Factor is the interleave factor.
  1426. virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
  1427. unsigned Factor) const {
  1428. return false;
  1429. }
  1430. /// Return true if zero-extending the specific node Val to type VT2 is free
  1431. /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
  1432. /// because it's folded such as X86 zero-extending loads).
  1433. virtual bool isZExtFree(SDValue Val, EVT VT2) const {
  1434. return isZExtFree(Val.getValueType(), VT2);
  1435. }
  1436. /// Return true if an fpext operation is free (for instance, because
  1437. /// single-precision floating-point numbers are implicitly extended to
  1438. /// double-precision).
  1439. virtual bool isFPExtFree(EVT VT) const {
  1440. assert(VT.isFloatingPoint());
  1441. return false;
  1442. }
  1443. /// Return true if folding a vector load into ExtVal (a sign, zero, or any
  1444. /// extend node) is profitable.
  1445. virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
  1446. /// Return true if an fneg operation is free to the point where it is never
  1447. /// worthwhile to replace it with a bitwise operation.
  1448. virtual bool isFNegFree(EVT VT) const {
  1449. assert(VT.isFloatingPoint());
  1450. return false;
  1451. }
  1452. /// Return true if an fabs operation is free to the point where it is never
  1453. /// worthwhile to replace it with a bitwise operation.
  1454. virtual bool isFAbsFree(EVT VT) const {
  1455. assert(VT.isFloatingPoint());
  1456. return false;
  1457. }
  1458. /// Return true if an FMA operation is faster than a pair of fmul and fadd
  1459. /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
  1460. /// returns true, otherwise fmuladd is expanded to fmul + fadd.
  1461. ///
  1462. /// NOTE: This may be called before legalization on types for which FMAs are
  1463. /// not legal, but should return true if those types will eventually legalize
  1464. /// to types that support FMAs. After legalization, it will only be called on
  1465. /// types that support FMAs (via Legal or Custom actions)
  1466. virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
  1467. return false;
  1468. }
  1469. /// Return true if it's profitable to narrow operations of type VT1 to
  1470. /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
  1471. /// i32 to i16.
  1472. virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
  1473. return false;
  1474. }
  1475. /// \brief Return true if it is beneficial to convert a load of a constant to
  1476. /// just the constant itself.
  1477. /// On some targets it might be more efficient to use a combination of
  1478. /// arithmetic instructions to materialize the constant instead of loading it
  1479. /// from a constant pool.
  1480. virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
  1481. Type *Ty) const {
  1482. return false;
  1483. }
  1484. /// Return true if EXTRACT_SUBVECTOR is cheap for this result type
  1485. /// with this index. This is needed because EXTRACT_SUBVECTOR usually
  1486. /// has custom lowering that depends on the index of the first element,
  1487. /// and only the target knows which lowering is cheap.
  1488. virtual bool isExtractSubvectorCheap(EVT ResVT, unsigned Index) const {
  1489. return false;
  1490. }
  1491. //===--------------------------------------------------------------------===//
  1492. // Runtime Library hooks
  1493. //
  1494. /// Rename the default libcall routine name for the specified libcall.
  1495. void setLibcallName(RTLIB::Libcall Call, const char *Name) {
  1496. LibcallRoutineNames[Call] = Name;
  1497. }
  1498. /// Get the libcall routine name for the specified libcall.
  1499. const char *getLibcallName(RTLIB::Libcall Call) const {
  1500. return LibcallRoutineNames[Call];
  1501. }
  1502. /// Override the default CondCode to be used to test the result of the
  1503. /// comparison libcall against zero.
  1504. void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
  1505. CmpLibcallCCs[Call] = CC;
  1506. }
  1507. /// Get the CondCode that's to be used to test the result of the comparison
  1508. /// libcall against zero.
  1509. ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
  1510. return CmpLibcallCCs[Call];
  1511. }
  1512. /// Set the CallingConv that should be used for the specified libcall.
  1513. void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
  1514. LibcallCallingConvs[Call] = CC;
  1515. }
  1516. /// Get the CallingConv that should be used for the specified libcall.
  1517. CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
  1518. return LibcallCallingConvs[Call];
  1519. }
  1520. private:
  1521. const TargetMachine &TM;
  1522. /// Tells the code generator not to expand operations into sequences that use
  1523. /// the select operations if possible.
  1524. bool SelectIsExpensive;
  1525. /// Tells the code generator that the target has multiple (allocatable)
  1526. /// condition registers that can be used to store the results of comparisons
  1527. /// for use by selects and conditional branches. With multiple condition
  1528. /// registers, the code generator will not aggressively sink comparisons into
  1529. /// the blocks of their users.
  1530. bool HasMultipleConditionRegisters;
  1531. /// Tells the code generator that the target has BitExtract instructions.
  1532. /// The code generator will aggressively sink "shift"s into the blocks of
  1533. /// their users if the users will generate "and" instructions which can be
  1534. /// combined with "shift" to BitExtract instructions.
  1535. bool HasExtractBitsInsn;
  1536. /// Tells the code generator not to expand integer divides by constants into a
  1537. /// sequence of muls, adds, and shifts. This is a hack until a real cost
  1538. /// model is in place. If we ever optimize for size, this will be set to true
  1539. /// unconditionally.
  1540. bool IntDivIsCheap;
  1541. // Don't expand fsqrt with an approximation based on the inverse sqrt.
  1542. bool FsqrtIsCheap;
  1543. /// Tells the code generator to bypass slow divide or remainder
  1544. /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
  1545. /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
  1546. /// div/rem when the operands are positive and less than 256.
  1547. DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
  1548. /// Tells the code generator that it shouldn't generate sra/srl/add/sra for a
  1549. /// signed divide by power of two; let the target handle it.
  1550. bool Pow2SDivIsCheap;
  1551. /// Tells the code generator that it shouldn't generate extra flow control
  1552. /// instructions and should attempt to combine flow control instructions via
  1553. /// predication.
  1554. bool JumpIsExpensive;
  1555. /// Whether the target supports or cares about preserving floating point
  1556. /// exception behavior.
  1557. bool HasFloatingPointExceptions;
  1558. /// This target prefers to use _setjmp to implement llvm.setjmp.
  1559. ///
  1560. /// Defaults to false.
  1561. bool UseUnderscoreSetJmp;
  1562. /// This target prefers to use _longjmp to implement llvm.longjmp.
  1563. ///
  1564. /// Defaults to false.
  1565. bool UseUnderscoreLongJmp;
  1566. /// Number of blocks threshold to use jump tables.
  1567. int MinimumJumpTableEntries;
  1568. /// Information about the contents of the high-bits in boolean values held in
  1569. /// a type wider than i1. See getBooleanContents.
  1570. BooleanContent BooleanContents;
  1571. /// Information about the contents of the high-bits in boolean values held in
  1572. /// a type wider than i1. See getBooleanContents.
  1573. BooleanContent BooleanFloatContents;
  1574. /// Information about the contents of the high-bits in boolean vector values
  1575. /// when the element type is wider than i1. See getBooleanContents.
  1576. BooleanContent BooleanVectorContents;
  1577. /// The target scheduling preference: shortest possible total cycles or lowest
  1578. /// register usage.
  1579. Sched::Preference SchedPreferenceInfo;
  1580. /// The size, in bytes, of the target's jmp_buf buffers
  1581. unsigned JumpBufSize;
  1582. /// The alignment, in bytes, of the target's jmp_buf buffers
  1583. unsigned JumpBufAlignment;
  1584. /// The minimum alignment that any argument on the stack needs to have.
  1585. unsigned MinStackArgumentAlignment;
  1586. /// The minimum function alignment (used when optimizing for size, and to
  1587. /// prevent explicitly provided alignment from leading to incorrect code).
  1588. unsigned MinFunctionAlignment;
  1589. /// The preferred function alignment (used when alignment unspecified and
  1590. /// optimizing for speed).
  1591. unsigned PrefFunctionAlignment;
  1592. /// The preferred loop alignment.
  1593. unsigned PrefLoopAlignment;
  1594. /// Whether the DAG builder should automatically insert fences and reduce
  1595. /// ordering for atomics. (This will be set for for most architectures with
  1596. /// weak memory ordering.)
  1597. bool InsertFencesForAtomic;
  1598. /// If set to a physical register, this specifies the register that
  1599. /// llvm.savestack/llvm.restorestack should save and restore.
  1600. unsigned StackPointerRegisterToSaveRestore;
  1601. /// If set to a physical register, this specifies the register that receives
  1602. /// the exception address on entry to a landing pad.
  1603. unsigned ExceptionPointerRegister;
  1604. /// If set to a physical register, this specifies the register that receives
  1605. /// the exception typeid on entry to a landing pad.
  1606. unsigned ExceptionSelectorRegister;
  1607. /// This indicates the default register class to use for each ValueType the
  1608. /// target supports natively.
  1609. const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
  1610. unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
  1611. MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
  1612. /// This indicates the "representative" register class to use for each
  1613. /// ValueType the target supports natively. This information is used by the
  1614. /// scheduler to track register pressure. By default, the representative
  1615. /// register class is the largest legal super-reg register class of the
  1616. /// register class of the specified type. e.g. On x86, i8, i16, and i32's
  1617. /// representative class would be GR32.
  1618. const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
  1619. /// This indicates the "cost" of the "representative" register class for each
  1620. /// ValueType. The cost is used by the scheduler to approximate register
  1621. /// pressure.
  1622. uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
  1623. /// For any value types we are promoting or expanding, this contains the value
  1624. /// type that we are changing to. For Expanded types, this contains one step
  1625. /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
  1626. /// (e.g. i64 -> i16). For types natively supported by the system, this holds
  1627. /// the same type (e.g. i32 -> i32).
  1628. MVT TransformToType[MVT::LAST_VALUETYPE];
  1629. /// For each operation and each value type, keep a LegalizeAction that
  1630. /// indicates how instruction selection should deal with the operation. Most
  1631. /// operations are Legal (aka, supported natively by the target), but
  1632. /// operations that are not should be described. Note that operations on
  1633. /// non-legal value types are not described here.
  1634. uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
  1635. /// For each load extension type and each value type, keep a LegalizeAction
  1636. /// that indicates how instruction selection should deal with a load of a
  1637. /// specific value type and extension type.
  1638. uint8_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE]
  1639. [ISD::LAST_LOADEXT_TYPE];
  1640. /// For each value type pair keep a LegalizeAction that indicates whether a
  1641. /// truncating store of a specific value type and truncating type is legal.
  1642. uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
  1643. /// For each indexed mode and each value type, keep a pair of LegalizeAction
  1644. /// that indicates how instruction selection should deal with the load /
  1645. /// store.
  1646. ///
  1647. /// The first dimension is the value_type for the reference. The second
  1648. /// dimension represents the various modes for load store.
  1649. uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
  1650. /// For each condition code (ISD::CondCode) keep a LegalizeAction that
  1651. /// indicates how instruction selection should deal with the condition code.
  1652. ///
  1653. /// Because each CC action takes up 2 bits, we need to have the array size be
  1654. /// large enough to fit all of the value types. This can be done by rounding
  1655. /// up the MVT::LAST_VALUETYPE value to the next multiple of 16.
  1656. uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 15) / 16];
  1657. ValueTypeActionImpl ValueTypeActions;
  1658. private:
  1659. LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
  1660. private:
  1661. std::vector<std::pair<MVT, const TargetRegisterClass*> > AvailableRegClasses;
  1662. /// Targets can specify ISD nodes that they would like PerformDAGCombine
  1663. /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
  1664. /// array.
  1665. unsigned char
  1666. TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
  1667. /// For operations that must be promoted to a specific type, this holds the
  1668. /// destination type. This map should be sparse, so don't hold it as an
  1669. /// array.
  1670. ///
  1671. /// Targets add entries to this map with AddPromotedToType(..), clients access
  1672. /// this with getTypeToPromoteTo(..).
  1673. std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
  1674. PromoteToType;
  1675. /// Stores the name each libcall.
  1676. const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
  1677. /// The ISD::CondCode that should be used to test the result of each of the
  1678. /// comparison libcall against zero.
  1679. ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
  1680. /// Stores the CallingConv that should be used for each libcall.
  1681. CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
  1682. protected:
  1683. /// Return true if the extension represented by \p I is free.
  1684. /// \pre \p I is a sign, zero, or fp extension and
  1685. /// is[Z|FP]ExtFree of the related types is not true.
  1686. virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
  1687. /// \brief Specify maximum number of store instructions per memset call.
  1688. ///
  1689. /// When lowering \@llvm.memset this field specifies the maximum number of
  1690. /// store operations that may be substituted for the call to memset. Targets
  1691. /// must set this value based on the cost threshold for that target. Targets
  1692. /// should assume that the memset will be done using as many of the largest
  1693. /// store operations first, followed by smaller ones, if necessary, per
  1694. /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
  1695. /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
  1696. /// store. This only applies to setting a constant array of a constant size.
  1697. unsigned MaxStoresPerMemset;
  1698. /// Maximum number of stores operations that may be substituted for the call
  1699. /// to memset, used for functions with OptSize attribute.
  1700. unsigned MaxStoresPerMemsetOptSize;
  1701. /// \brief Specify maximum bytes of store instructions per memcpy call.
  1702. ///
  1703. /// When lowering \@llvm.memcpy this field specifies the maximum number of
  1704. /// store operations that may be substituted for a call to memcpy. Targets
  1705. /// must set this value based on the cost threshold for that target. Targets
  1706. /// should assume that the memcpy will be done using as many of the largest
  1707. /// store operations first, followed by smaller ones, if necessary, per
  1708. /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
  1709. /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
  1710. /// and one 1-byte store. This only applies to copying a constant array of
  1711. /// constant size.
  1712. unsigned MaxStoresPerMemcpy;
  1713. /// Maximum number of store operations that may be substituted for a call to
  1714. /// memcpy, used for functions with OptSize attribute.
  1715. unsigned MaxStoresPerMemcpyOptSize;
  1716. /// \brief Specify maximum bytes of store instructions per memmove call.
  1717. ///
  1718. /// When lowering \@llvm.memmove this field specifies the maximum number of
  1719. /// store instructions that may be substituted for a call to memmove. Targets
  1720. /// must set this value based on the cost threshold for that target. Targets
  1721. /// should assume that the memmove will be done using as many of the largest
  1722. /// store operations first, followed by smaller ones, if necessary, per
  1723. /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
  1724. /// with 8-bit alignment would result in nine 1-byte stores. This only
  1725. /// applies to copying a constant array of constant size.
  1726. unsigned MaxStoresPerMemmove;
  1727. /// Maximum number of store instructions that may be substituted for a call to
  1728. /// memmove, used for functions with OpSize attribute.
  1729. unsigned MaxStoresPerMemmoveOptSize;
  1730. /// Tells the code generator that select is more expensive than a branch if
  1731. /// the branch is usually predicted right.
  1732. bool PredictableSelectIsExpensive;
  1733. /// MaskAndBranchFoldingIsLegal - Indicates if the target supports folding
  1734. /// a mask of a single bit, a compare, and a branch into a single instruction.
  1735. bool MaskAndBranchFoldingIsLegal;
  1736. /// \see enableExtLdPromotion.
  1737. bool EnableExtLdPromotion;
  1738. protected:
  1739. /// Return true if the value types that can be represented by the specified
  1740. /// register class are all legal.
  1741. bool isLegalRC(const TargetRegisterClass *RC) const;
  1742. /// Replace/modify any TargetFrameIndex operands with a targte-dependent
  1743. /// sequence of memory operands that is recognized by PrologEpilogInserter.
  1744. MachineBasicBlock *emitPatchPoint(MachineInstr *MI,
  1745. MachineBasicBlock *MBB) const;
  1746. };
  1747. /// This class defines information used to lower LLVM code to legal SelectionDAG
  1748. /// operators that the target instruction selector can accept natively.
  1749. ///
  1750. /// This class also defines callbacks that targets must implement to lower
  1751. /// target-specific constructs to SelectionDAG operators.
  1752. class TargetLowering : public TargetLoweringBase {
  1753. TargetLowering(const TargetLowering&) = delete;
  1754. void operator=(const TargetLowering&) = delete;
  1755. public:
  1756. /// NOTE: The TargetMachine owns TLOF.
  1757. explicit TargetLowering(const TargetMachine &TM);
  1758. /// Returns true by value, base pointer and offset pointer and addressing mode
  1759. /// by reference if the node's address can be legally represented as
  1760. /// pre-indexed load / store address.
  1761. virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
  1762. SDValue &/*Offset*/,
  1763. ISD::MemIndexedMode &/*AM*/,
  1764. SelectionDAG &/*DAG*/) const {
  1765. return false;
  1766. }
  1767. /// Returns true by value, base pointer and offset pointer and addressing mode
  1768. /// by reference if this node can be combined with a load / store to form a
  1769. /// post-indexed load / store.
  1770. virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
  1771. SDValue &/*Base*/,
  1772. SDValue &/*Offset*/,
  1773. ISD::MemIndexedMode &/*AM*/,
  1774. SelectionDAG &/*DAG*/) const {
  1775. return false;
  1776. }
  1777. /// Return the entry encoding for a jump table in the current function. The
  1778. /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
  1779. virtual unsigned getJumpTableEncoding() const;
  1780. virtual const MCExpr *
  1781. LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
  1782. const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
  1783. MCContext &/*Ctx*/) const {
  1784. llvm_unreachable("Need to implement this hook if target has custom JTIs");
  1785. }
  1786. /// Returns relocation base for the given PIC jumptable.
  1787. virtual SDValue getPICJumpTableRelocBase(SDValue Table,
  1788. SelectionDAG &DAG) const;
  1789. /// This returns the relocation base for the given PIC jumptable, the same as
  1790. /// getPICJumpTableRelocBase, but as an MCExpr.
  1791. virtual const MCExpr *
  1792. getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
  1793. unsigned JTI, MCContext &Ctx) const;
  1794. /// Return true if folding a constant offset with the given GlobalAddress is
  1795. /// legal. It is frequently not legal in PIC relocation models.
  1796. virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
  1797. bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
  1798. SDValue &Chain) const;
  1799. void softenSetCCOperands(SelectionDAG &DAG, EVT VT,
  1800. SDValue &NewLHS, SDValue &NewRHS,
  1801. ISD::CondCode &CCCode, SDLoc DL) const;
  1802. /// Returns a pair of (return value, chain).
  1803. /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
  1804. std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
  1805. EVT RetVT, const SDValue *Ops,
  1806. unsigned NumOps, bool isSigned,
  1807. SDLoc dl, bool doesNotReturn = false,
  1808. bool isReturnValueUsed = true) const;
  1809. //===--------------------------------------------------------------------===//
  1810. // TargetLowering Optimization Methods
  1811. //
  1812. /// A convenience struct that encapsulates a DAG, and two SDValues for
  1813. /// returning information from TargetLowering to its clients that want to
  1814. /// combine.
  1815. struct TargetLoweringOpt {
  1816. SelectionDAG &DAG;
  1817. bool LegalTys;
  1818. bool LegalOps;
  1819. SDValue Old;
  1820. SDValue New;
  1821. explicit TargetLoweringOpt(SelectionDAG &InDAG,
  1822. bool LT, bool LO) :
  1823. DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
  1824. bool LegalTypes() const { return LegalTys; }
  1825. bool LegalOperations() const { return LegalOps; }
  1826. bool CombineTo(SDValue O, SDValue N) {
  1827. Old = O;
  1828. New = N;
  1829. return true;
  1830. }
  1831. /// Check to see if the specified operand of the specified instruction is a
  1832. /// constant integer. If so, check to see if there are any bits set in the
  1833. /// constant that are not demanded. If so, shrink the constant and return
  1834. /// true.
  1835. bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
  1836. /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
  1837. /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
  1838. /// generalized for targets with other types of implicit widening casts.
  1839. bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
  1840. SDLoc dl);
  1841. };
  1842. /// Look at Op. At this point, we know that only the DemandedMask bits of the
  1843. /// result of Op are ever used downstream. If we can use this information to
  1844. /// simplify Op, create a new simplified DAG node and return true, returning
  1845. /// the original and new nodes in Old and New. Otherwise, analyze the
  1846. /// expression and return a mask of KnownOne and KnownZero bits for the
  1847. /// expression (used to simplify the caller). The KnownZero/One bits may only
  1848. /// be accurate for those bits in the DemandedMask.
  1849. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
  1850. APInt &KnownZero, APInt &KnownOne,
  1851. TargetLoweringOpt &TLO, unsigned Depth = 0) const;
  1852. /// Determine which of the bits specified in Mask are known to be either zero
  1853. /// or one and return them in the KnownZero/KnownOne bitsets.
  1854. virtual void computeKnownBitsForTargetNode(const SDValue Op,
  1855. APInt &KnownZero,
  1856. APInt &KnownOne,
  1857. const SelectionDAG &DAG,
  1858. unsigned Depth = 0) const;
  1859. /// This method can be implemented by targets that want to expose additional
  1860. /// information about sign bits to the DAG Combiner.
  1861. virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
  1862. const SelectionDAG &DAG,
  1863. unsigned Depth = 0) const;
  1864. struct DAGCombinerInfo {
  1865. void *DC; // The DAG Combiner object.
  1866. CombineLevel Level;
  1867. bool CalledByLegalizer;
  1868. public:
  1869. SelectionDAG &DAG;
  1870. DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
  1871. : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
  1872. bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
  1873. bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
  1874. bool isAfterLegalizeVectorOps() const {
  1875. return Level == AfterLegalizeDAG;
  1876. }
  1877. CombineLevel getDAGCombineLevel() { return Level; }
  1878. bool isCalledByLegalizer() const { return CalledByLegalizer; }
  1879. void AddToWorklist(SDNode *N);
  1880. void RemoveFromWorklist(SDNode *N);
  1881. SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
  1882. SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
  1883. SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
  1884. void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
  1885. };
  1886. /// Return if the N is a constant or constant vector equal to the true value
  1887. /// from getBooleanContents().
  1888. bool isConstTrueVal(const SDNode *N) const;
  1889. /// Return if the N is a constant or constant vector equal to the false value
  1890. /// from getBooleanContents().
  1891. bool isConstFalseVal(const SDNode *N) const;
  1892. /// Try to simplify a setcc built with the specified operands and cc. If it is
  1893. /// unable to simplify it, return a null SDValue.
  1894. SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
  1895. ISD::CondCode Cond, bool foldBooleans,
  1896. DAGCombinerInfo &DCI, SDLoc dl) const;
  1897. /// Returns true (and the GlobalValue and the offset) if the node is a
  1898. /// GlobalAddress + offset.
  1899. virtual bool
  1900. isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
  1901. /// This method will be invoked for all target nodes and for any
  1902. /// target-independent nodes that the target has registered with invoke it
  1903. /// for.
  1904. ///
  1905. /// The semantics are as follows:
  1906. /// Return Value:
  1907. /// SDValue.Val == 0 - No change was made
  1908. /// SDValue.Val == N - N was replaced, is dead, and is already handled.
  1909. /// otherwise - N should be replaced by the returned Operand.
  1910. ///
  1911. /// In addition, methods provided by DAGCombinerInfo may be used to perform
  1912. /// more complex transformations.
  1913. ///
  1914. virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
  1915. /// Return true if it is profitable to move a following shift through this
  1916. // node, adjusting any immediate operands as necessary to preserve semantics.
  1917. // This transformation may not be desirable if it disrupts a particularly
  1918. // auspicious target-specific tree (e.g. bitfield extraction in AArch64).
  1919. // By default, it returns true.
  1920. virtual bool isDesirableToCommuteWithShift(const SDNode *N /*Op*/) const {
  1921. return true;
  1922. }
  1923. /// Return true if the target has native support for the specified value type
  1924. /// and it is 'desirable' to use the type for the given node type. e.g. On x86
  1925. /// i16 is legal, but undesirable since i16 instruction encodings are longer
  1926. /// and some i16 instructions are slow.
  1927. virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
  1928. // By default, assume all legal types are desirable.
  1929. return isTypeLegal(VT);
  1930. }
  1931. /// Return true if it is profitable for dag combiner to transform a floating
  1932. /// point op of specified opcode to a equivalent op of an integer
  1933. /// type. e.g. f32 load -> i32 load can be profitable on ARM.
  1934. virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
  1935. EVT /*VT*/) const {
  1936. return false;
  1937. }
  1938. /// This method query the target whether it is beneficial for dag combiner to
  1939. /// promote the specified node. If true, it should return the desired
  1940. /// promotion type by reference.
  1941. virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
  1942. return false;
  1943. }
  1944. //===--------------------------------------------------------------------===//
  1945. // Lowering methods - These methods must be implemented by targets so that
  1946. // the SelectionDAGBuilder code knows how to lower these.
  1947. //
  1948. /// This hook must be implemented to lower the incoming (formal) arguments,
  1949. /// described by the Ins array, into the specified DAG. The implementation
  1950. /// should fill in the InVals array with legal-type argument values, and
  1951. /// return the resulting token chain value.
  1952. ///
  1953. virtual SDValue
  1954. LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
  1955. bool /*isVarArg*/,
  1956. const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
  1957. SDLoc /*dl*/, SelectionDAG &/*DAG*/,
  1958. SmallVectorImpl<SDValue> &/*InVals*/) const {
  1959. llvm_unreachable("Not Implemented");
  1960. }
  1961. struct ArgListEntry {
  1962. SDValue Node;
  1963. Type* Ty;
  1964. bool isSExt : 1;
  1965. bool isZExt : 1;
  1966. bool isInReg : 1;
  1967. bool isSRet : 1;
  1968. bool isNest : 1;
  1969. bool isByVal : 1;
  1970. bool isInAlloca : 1;
  1971. bool isReturned : 1;
  1972. uint16_t Alignment;
  1973. ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
  1974. isSRet(false), isNest(false), isByVal(false), isInAlloca(false),
  1975. isReturned(false), Alignment(0) { }
  1976. void setAttributes(ImmutableCallSite *CS, unsigned AttrIdx);
  1977. };
  1978. typedef std::vector<ArgListEntry> ArgListTy;
  1979. /// This structure contains all information that is necessary for lowering
  1980. /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
  1981. /// needs to lower a call, and targets will see this struct in their LowerCall
  1982. /// implementation.
  1983. struct CallLoweringInfo {
  1984. SDValue Chain;
  1985. Type *RetTy;
  1986. bool RetSExt : 1;
  1987. bool RetZExt : 1;
  1988. bool IsVarArg : 1;
  1989. bool IsInReg : 1;
  1990. bool DoesNotReturn : 1;
  1991. bool IsReturnValueUsed : 1;
  1992. // IsTailCall should be modified by implementations of
  1993. // TargetLowering::LowerCall that perform tail call conversions.
  1994. bool IsTailCall;
  1995. unsigned NumFixedArgs;
  1996. CallingConv::ID CallConv;
  1997. SDValue Callee;
  1998. ArgListTy Args;
  1999. SelectionDAG &DAG;
  2000. SDLoc DL;
  2001. ImmutableCallSite *CS;
  2002. bool IsPatchPoint;
  2003. SmallVector<ISD::OutputArg, 32> Outs;
  2004. SmallVector<SDValue, 32> OutVals;
  2005. SmallVector<ISD::InputArg, 32> Ins;
  2006. CallLoweringInfo(SelectionDAG &DAG)
  2007. : RetTy(nullptr), RetSExt(false), RetZExt(false), IsVarArg(false),
  2008. IsInReg(false), DoesNotReturn(false), IsReturnValueUsed(true),
  2009. IsTailCall(false), NumFixedArgs(-1), CallConv(CallingConv::C),
  2010. DAG(DAG), CS(nullptr), IsPatchPoint(false) {}
  2011. CallLoweringInfo &setDebugLoc(SDLoc dl) {
  2012. DL = dl;
  2013. return *this;
  2014. }
  2015. CallLoweringInfo &setChain(SDValue InChain) {
  2016. Chain = InChain;
  2017. return *this;
  2018. }
  2019. CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
  2020. SDValue Target, ArgListTy &&ArgsList,
  2021. unsigned FixedArgs = -1) {
  2022. RetTy = ResultType;
  2023. Callee = Target;
  2024. CallConv = CC;
  2025. NumFixedArgs =
  2026. (FixedArgs == static_cast<unsigned>(-1) ? Args.size() : FixedArgs);
  2027. Args = std::move(ArgsList);
  2028. return *this;
  2029. }
  2030. CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
  2031. SDValue Target, ArgListTy &&ArgsList,
  2032. ImmutableCallSite &Call) {
  2033. RetTy = ResultType;
  2034. IsInReg = Call.paramHasAttr(0, Attribute::InReg);
  2035. DoesNotReturn = Call.doesNotReturn();
  2036. IsVarArg = FTy->isVarArg();
  2037. IsReturnValueUsed = !Call.getInstruction()->use_empty();
  2038. RetSExt = Call.paramHasAttr(0, Attribute::SExt);
  2039. RetZExt = Call.paramHasAttr(0, Attribute::ZExt);
  2040. Callee = Target;
  2041. CallConv = Call.getCallingConv();
  2042. NumFixedArgs = FTy->getNumParams();
  2043. Args = std::move(ArgsList);
  2044. CS = &Call;
  2045. return *this;
  2046. }
  2047. CallLoweringInfo &setInRegister(bool Value = true) {
  2048. IsInReg = Value;
  2049. return *this;
  2050. }
  2051. CallLoweringInfo &setNoReturn(bool Value = true) {
  2052. DoesNotReturn = Value;
  2053. return *this;
  2054. }
  2055. CallLoweringInfo &setVarArg(bool Value = true) {
  2056. IsVarArg = Value;
  2057. return *this;
  2058. }
  2059. CallLoweringInfo &setTailCall(bool Value = true) {
  2060. IsTailCall = Value;
  2061. return *this;
  2062. }
  2063. CallLoweringInfo &setDiscardResult(bool Value = true) {
  2064. IsReturnValueUsed = !Value;
  2065. return *this;
  2066. }
  2067. CallLoweringInfo &setSExtResult(bool Value = true) {
  2068. RetSExt = Value;
  2069. return *this;
  2070. }
  2071. CallLoweringInfo &setZExtResult(bool Value = true) {
  2072. RetZExt = Value;
  2073. return *this;
  2074. }
  2075. CallLoweringInfo &setIsPatchPoint(bool Value = true) {
  2076. IsPatchPoint = Value;
  2077. return *this;
  2078. }
  2079. ArgListTy &getArgs() {
  2080. return Args;
  2081. }
  2082. };
  2083. /// This function lowers an abstract call to a function into an actual call.
  2084. /// This returns a pair of operands. The first element is the return value
  2085. /// for the function (if RetTy is not VoidTy). The second element is the
  2086. /// outgoing token chain. It calls LowerCall to do the actual lowering.
  2087. std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
  2088. /// This hook must be implemented to lower calls into the specified
  2089. /// DAG. The outgoing arguments to the call are described by the Outs array,
  2090. /// and the values to be returned by the call are described by the Ins
  2091. /// array. The implementation should fill in the InVals array with legal-type
  2092. /// return values from the call, and return the resulting token chain value.
  2093. virtual SDValue
  2094. LowerCall(CallLoweringInfo &/*CLI*/,
  2095. SmallVectorImpl<SDValue> &/*InVals*/) const {
  2096. llvm_unreachable("Not Implemented");
  2097. }
  2098. /// Target-specific cleanup for formal ByVal parameters.
  2099. virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
  2100. /// This hook should be implemented to check whether the return values
  2101. /// described by the Outs array can fit into the return registers. If false
  2102. /// is returned, an sret-demotion is performed.
  2103. virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
  2104. MachineFunction &/*MF*/, bool /*isVarArg*/,
  2105. const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
  2106. LLVMContext &/*Context*/) const
  2107. {
  2108. // Return true by default to get preexisting behavior.
  2109. return true;
  2110. }
  2111. /// This hook must be implemented to lower outgoing return values, described
  2112. /// by the Outs array, into the specified DAG. The implementation should
  2113. /// return the resulting token chain value.
  2114. virtual SDValue
  2115. LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
  2116. bool /*isVarArg*/,
  2117. const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
  2118. const SmallVectorImpl<SDValue> &/*OutVals*/,
  2119. SDLoc /*dl*/, SelectionDAG &/*DAG*/) const {
  2120. llvm_unreachable("Not Implemented");
  2121. }
  2122. /// Return true if result of the specified node is used by a return node
  2123. /// only. It also compute and return the input chain for the tail call.
  2124. ///
  2125. /// This is used to determine whether it is possible to codegen a libcall as
  2126. /// tail call at legalization time.
  2127. virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
  2128. return false;
  2129. }
  2130. /// Return true if the target may be able emit the call instruction as a tail
  2131. /// call. This is used by optimization passes to determine if it's profitable
  2132. /// to duplicate return instructions to enable tailcall optimization.
  2133. virtual bool mayBeEmittedAsTailCall(CallInst *) const {
  2134. return false;
  2135. }
  2136. /// Return the builtin name for the __builtin___clear_cache intrinsic
  2137. /// Default is to invoke the clear cache library call
  2138. virtual const char * getClearCacheBuiltinName() const {
  2139. return "__clear_cache";
  2140. }
  2141. /// Return the register ID of the name passed in. Used by named register
  2142. /// global variables extension. There is no target-independent behaviour
  2143. /// so the default action is to bail.
  2144. virtual unsigned getRegisterByName(const char* RegName, EVT VT,
  2145. SelectionDAG &DAG) const {
  2146. report_fatal_error("Named registers not implemented for this target");
  2147. }
  2148. /// Return the type that should be used to zero or sign extend a
  2149. /// zeroext/signext integer argument or return value. FIXME: Most C calling
  2150. /// convention requires the return type to be promoted, but this is not true
  2151. /// all the time, e.g. i1 on x86-64. It is also not necessary for non-C
  2152. /// calling conventions. The frontend should handle this and include all of
  2153. /// the necessary information.
  2154. virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
  2155. ISD::NodeType /*ExtendKind*/) const {
  2156. EVT MinVT = getRegisterType(Context, MVT::i32);
  2157. return VT.bitsLT(MinVT) ? MinVT : VT;
  2158. }
  2159. /// For some targets, an LLVM struct type must be broken down into multiple
  2160. /// simple types, but the calling convention specifies that the entire struct
  2161. /// must be passed in a block of consecutive registers.
  2162. virtual bool
  2163. functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
  2164. bool isVarArg) const {
  2165. return false;
  2166. }
  2167. /// Returns a 0 terminated array of registers that can be safely used as
  2168. /// scratch registers.
  2169. virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
  2170. return nullptr;
  2171. }
  2172. /// This callback is used to prepare for a volatile or atomic load.
  2173. /// It takes a chain node as input and returns the chain for the load itself.
  2174. ///
  2175. /// Having a callback like this is necessary for targets like SystemZ,
  2176. /// which allows a CPU to reuse the result of a previous load indefinitely,
  2177. /// even if a cache-coherent store is performed by another CPU. The default
  2178. /// implementation does nothing.
  2179. virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL,
  2180. SelectionDAG &DAG) const {
  2181. return Chain;
  2182. }
  2183. /// This callback is invoked by the type legalizer to legalize nodes with an
  2184. /// illegal operand type but legal result types. It replaces the
  2185. /// LowerOperation callback in the type Legalizer. The reason we can not do
  2186. /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
  2187. /// use this callback.
  2188. ///
  2189. /// TODO: Consider merging with ReplaceNodeResults.
  2190. ///
  2191. /// The target places new result values for the node in Results (their number
  2192. /// and types must exactly match those of the original return values of
  2193. /// the node), or leaves Results empty, which indicates that the node is not
  2194. /// to be custom lowered after all.
  2195. /// The default implementation calls LowerOperation.
  2196. virtual void LowerOperationWrapper(SDNode *N,
  2197. SmallVectorImpl<SDValue> &Results,
  2198. SelectionDAG &DAG) const;
  2199. /// This callback is invoked for operations that are unsupported by the
  2200. /// target, which are registered to use 'custom' lowering, and whose defined
  2201. /// values are all legal. If the target has no operations that require custom
  2202. /// lowering, it need not implement this. The default implementation of this
  2203. /// aborts.
  2204. virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
  2205. /// This callback is invoked when a node result type is illegal for the
  2206. /// target, and the operation was registered to use 'custom' lowering for that
  2207. /// result type. The target places new result values for the node in Results
  2208. /// (their number and types must exactly match those of the original return
  2209. /// values of the node), or leaves Results empty, which indicates that the
  2210. /// node is not to be custom lowered after all.
  2211. ///
  2212. /// If the target has no operations that require custom lowering, it need not
  2213. /// implement this. The default implementation aborts.
  2214. virtual void ReplaceNodeResults(SDNode * /*N*/,
  2215. SmallVectorImpl<SDValue> &/*Results*/,
  2216. SelectionDAG &/*DAG*/) const {
  2217. llvm_unreachable("ReplaceNodeResults not implemented for this target!");
  2218. }
  2219. /// This method returns the name of a target specific DAG node.
  2220. virtual const char *getTargetNodeName(unsigned Opcode) const;
  2221. /// This method returns a target specific FastISel object, or null if the
  2222. /// target does not support "fast" ISel.
  2223. virtual FastISel *createFastISel(FunctionLoweringInfo &,
  2224. const TargetLibraryInfo *) const {
  2225. return nullptr;
  2226. }
  2227. bool verifyReturnAddressArgumentIsConstant(SDValue Op,
  2228. SelectionDAG &DAG) const;
  2229. //===--------------------------------------------------------------------===//
  2230. // Inline Asm Support hooks
  2231. //
  2232. /// This hook allows the target to expand an inline asm call to be explicit
  2233. /// llvm code if it wants to. This is useful for turning simple inline asms
  2234. /// into LLVM intrinsics, which gives the compiler more information about the
  2235. /// behavior of the code.
  2236. virtual bool ExpandInlineAsm(CallInst *) const {
  2237. return false;
  2238. }
  2239. enum ConstraintType {
  2240. C_Register, // Constraint represents specific register(s).
  2241. C_RegisterClass, // Constraint represents any of register(s) in class.
  2242. C_Memory, // Memory constraint.
  2243. C_Other, // Something else.
  2244. C_Unknown // Unsupported constraint.
  2245. };
  2246. enum ConstraintWeight {
  2247. // Generic weights.
  2248. CW_Invalid = -1, // No match.
  2249. CW_Okay = 0, // Acceptable.
  2250. CW_Good = 1, // Good weight.
  2251. CW_Better = 2, // Better weight.
  2252. CW_Best = 3, // Best weight.
  2253. // Well-known weights.
  2254. CW_SpecificReg = CW_Okay, // Specific register operands.
  2255. CW_Register = CW_Good, // Register operands.
  2256. CW_Memory = CW_Better, // Memory operands.
  2257. CW_Constant = CW_Best, // Constant operand.
  2258. CW_Default = CW_Okay // Default or don't know type.
  2259. };
  2260. /// This contains information for each constraint that we are lowering.
  2261. struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
  2262. /// This contains the actual string for the code, like "m". TargetLowering
  2263. /// picks the 'best' code from ConstraintInfo::Codes that most closely
  2264. /// matches the operand.
  2265. std::string ConstraintCode;
  2266. /// Information about the constraint code, e.g. Register, RegisterClass,
  2267. /// Memory, Other, Unknown.
  2268. TargetLowering::ConstraintType ConstraintType;
  2269. /// If this is the result output operand or a clobber, this is null,
  2270. /// otherwise it is the incoming operand to the CallInst. This gets
  2271. /// modified as the asm is processed.
  2272. Value *CallOperandVal;
  2273. /// The ValueType for the operand value.
  2274. MVT ConstraintVT;
  2275. /// Return true of this is an input operand that is a matching constraint
  2276. /// like "4".
  2277. bool isMatchingInputConstraint() const;
  2278. /// If this is an input matching constraint, this method returns the output
  2279. /// operand it matches.
  2280. unsigned getMatchedOperand() const;
  2281. /// Copy constructor for copying from a ConstraintInfo.
  2282. AsmOperandInfo(InlineAsm::ConstraintInfo Info)
  2283. : InlineAsm::ConstraintInfo(std::move(Info)),
  2284. ConstraintType(TargetLowering::C_Unknown), CallOperandVal(nullptr),
  2285. ConstraintVT(MVT::Other) {}
  2286. };
  2287. typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
  2288. /// Split up the constraint string from the inline assembly value into the
  2289. /// specific constraints and their prefixes, and also tie in the associated
  2290. /// operand values. If this returns an empty vector, and if the constraint
  2291. /// string itself isn't empty, there was an error parsing.
  2292. virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
  2293. const TargetRegisterInfo *TRI,
  2294. ImmutableCallSite CS) const;
  2295. /// Examine constraint type and operand type and determine a weight value.
  2296. /// The operand object must already have been set up with the operand type.
  2297. virtual ConstraintWeight getMultipleConstraintMatchWeight(
  2298. AsmOperandInfo &info, int maIndex) const;
  2299. /// Examine constraint string and operand type and determine a weight value.
  2300. /// The operand object must already have been set up with the operand type.
  2301. virtual ConstraintWeight getSingleConstraintMatchWeight(
  2302. AsmOperandInfo &info, const char *constraint) const;
  2303. /// Determines the constraint code and constraint type to use for the specific
  2304. /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
  2305. /// If the actual operand being passed in is available, it can be passed in as
  2306. /// Op, otherwise an empty SDValue can be passed.
  2307. virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
  2308. SDValue Op,
  2309. SelectionDAG *DAG = nullptr) const;
  2310. /// Given a constraint, return the type of constraint it is for this target.
  2311. virtual ConstraintType getConstraintType(StringRef Constraint) const;
  2312. /// Given a physical register constraint (e.g. {edx}), return the register
  2313. /// number and the register class for the register.
  2314. ///
  2315. /// Given a register class constraint, like 'r', if this corresponds directly
  2316. /// to an LLVM register class, return a register of 0 and the register class
  2317. /// pointer.
  2318. ///
  2319. /// This should only be used for C_Register constraints. On error, this
  2320. /// returns a register number of 0 and a null register class pointer.
  2321. virtual std::pair<unsigned, const TargetRegisterClass *>
  2322. getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
  2323. StringRef Constraint, MVT VT) const;
  2324. virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
  2325. if (ConstraintCode == "i")
  2326. return InlineAsm::Constraint_i;
  2327. else if (ConstraintCode == "m")
  2328. return InlineAsm::Constraint_m;
  2329. return InlineAsm::Constraint_Unknown;
  2330. }
  2331. /// Try to replace an X constraint, which matches anything, with another that
  2332. /// has more specific requirements based on the type of the corresponding
  2333. /// operand. This returns null if there is no replacement to make.
  2334. virtual const char *LowerXConstraint(EVT ConstraintVT) const;
  2335. /// Lower the specified operand into the Ops vector. If it is invalid, don't
  2336. /// add anything to Ops.
  2337. virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
  2338. std::vector<SDValue> &Ops,
  2339. SelectionDAG &DAG) const;
  2340. //===--------------------------------------------------------------------===//
  2341. // Div utility functions
  2342. //
  2343. SDValue BuildSDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
  2344. bool IsAfterLegalization,
  2345. std::vector<SDNode *> *Created) const;
  2346. SDValue BuildUDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
  2347. bool IsAfterLegalization,
  2348. std::vector<SDNode *> *Created) const;
  2349. virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
  2350. SelectionDAG &DAG,
  2351. std::vector<SDNode *> *Created) const {
  2352. return SDValue();
  2353. }
  2354. /// Indicate whether this target prefers to combine the given number of FDIVs
  2355. /// with the same divisor.
  2356. virtual bool combineRepeatedFPDivisors(unsigned NumUsers) const {
  2357. return false;
  2358. }
  2359. /// Hooks for building estimates in place of slower divisions and square
  2360. /// roots.
  2361. /// Return a reciprocal square root estimate value for the input operand.
  2362. /// The RefinementSteps output is the number of Newton-Raphson refinement
  2363. /// iterations required to generate a sufficient (though not necessarily
  2364. /// IEEE-754 compliant) estimate for the value type.
  2365. /// The boolean UseOneConstNR output is used to select a Newton-Raphson
  2366. /// algorithm implementation that uses one constant or two constants.
  2367. /// A target may choose to implement its own refinement within this function.
  2368. /// If that's true, then return '0' as the number of RefinementSteps to avoid
  2369. /// any further refinement of the estimate.
  2370. /// An empty SDValue return means no estimate sequence can be created.
  2371. virtual SDValue getRsqrtEstimate(SDValue Operand, DAGCombinerInfo &DCI,
  2372. unsigned &RefinementSteps,
  2373. bool &UseOneConstNR) const {
  2374. return SDValue();
  2375. }
  2376. /// Return a reciprocal estimate value for the input operand.
  2377. /// The RefinementSteps output is the number of Newton-Raphson refinement
  2378. /// iterations required to generate a sufficient (though not necessarily
  2379. /// IEEE-754 compliant) estimate for the value type.
  2380. /// A target may choose to implement its own refinement within this function.
  2381. /// If that's true, then return '0' as the number of RefinementSteps to avoid
  2382. /// any further refinement of the estimate.
  2383. /// An empty SDValue return means no estimate sequence can be created.
  2384. virtual SDValue getRecipEstimate(SDValue Operand, DAGCombinerInfo &DCI,
  2385. unsigned &RefinementSteps) const {
  2386. return SDValue();
  2387. }
  2388. //===--------------------------------------------------------------------===//
  2389. // Legalization utility functions
  2390. //
  2391. /// Expand a MUL into two nodes. One that computes the high bits of
  2392. /// the result and one that computes the low bits.
  2393. /// \param HiLoVT The value type to use for the Lo and Hi nodes.
  2394. /// \param LL Low bits of the LHS of the MUL. You can use this parameter
  2395. /// if you want to control how low bits are extracted from the LHS.
  2396. /// \param LH High bits of the LHS of the MUL. See LL for meaning.
  2397. /// \param RL Low bits of the RHS of the MUL. See LL for meaning
  2398. /// \param RH High bits of the RHS of the MUL. See LL for meaning.
  2399. /// \returns true if the node has been expanded. false if it has not
  2400. bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
  2401. SelectionDAG &DAG, SDValue LL = SDValue(),
  2402. SDValue LH = SDValue(), SDValue RL = SDValue(),
  2403. SDValue RH = SDValue()) const;
  2404. /// Expand float(f32) to SINT(i64) conversion
  2405. /// \param N Node to expand
  2406. /// \param Result output after conversion
  2407. /// \returns True, if the expansion was successful, false otherwise
  2408. bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
  2409. //===--------------------------------------------------------------------===//
  2410. // Instruction Emitting Hooks
  2411. //
  2412. /// This method should be implemented by targets that mark instructions with
  2413. /// the 'usesCustomInserter' flag. These instructions are special in various
  2414. /// ways, which require special support to insert. The specified MachineInstr
  2415. /// is created but not inserted into any basic blocks, and this method is
  2416. /// called to expand it into a sequence of instructions, potentially also
  2417. /// creating new basic blocks and control flow.
  2418. /// As long as the returned basic block is different (i.e., we created a new
  2419. /// one), the custom inserter is free to modify the rest of \p MBB.
  2420. virtual MachineBasicBlock *
  2421. EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
  2422. /// This method should be implemented by targets that mark instructions with
  2423. /// the 'hasPostISelHook' flag. These instructions must be adjusted after
  2424. /// instruction selection by target hooks. e.g. To fill in optional defs for
  2425. /// ARM 's' setting instructions.
  2426. virtual void
  2427. AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
  2428. /// If this function returns true, SelectionDAGBuilder emits a
  2429. /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
  2430. virtual bool useLoadStackGuardNode() const {
  2431. return false;
  2432. }
  2433. };
  2434. /// Given an LLVM IR type and return type attributes, compute the return value
  2435. /// EVTs and flags, and optionally also the offsets, if the return value is
  2436. /// being lowered to memory.
  2437. void GetReturnInfo(Type *ReturnType, AttributeSet attr,
  2438. SmallVectorImpl<ISD::OutputArg> &Outs,
  2439. const TargetLowering &TLI, const DataLayout &DL);
  2440. } // end llvm namespace
  2441. #endif