TargetLoweringBase.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  1. //===- TargetLoweringBase.cpp - Implement the TargetLoweringBase class ----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements the TargetLoweringBase class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/BitVector.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/ADT/Twine.h"
  19. #include "llvm/CodeGen/Analysis.h"
  20. #include "llvm/CodeGen/ISDOpcodes.h"
  21. #include "llvm/CodeGen/MachineBasicBlock.h"
  22. #include "llvm/CodeGen/MachineFrameInfo.h"
  23. #include "llvm/CodeGen/MachineFunction.h"
  24. #include "llvm/CodeGen/MachineInstr.h"
  25. #include "llvm/CodeGen/MachineInstrBuilder.h"
  26. #include "llvm/CodeGen/MachineMemOperand.h"
  27. #include "llvm/CodeGen/MachineOperand.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/RuntimeLibcalls.h"
  30. #include "llvm/CodeGen/StackMaps.h"
  31. #include "llvm/CodeGen/TargetLowering.h"
  32. #include "llvm/CodeGen/TargetOpcodes.h"
  33. #include "llvm/CodeGen/TargetRegisterInfo.h"
  34. #include "llvm/CodeGen/ValueTypes.h"
  35. #include "llvm/IR/Attributes.h"
  36. #include "llvm/IR/CallingConv.h"
  37. #include "llvm/IR/DataLayout.h"
  38. #include "llvm/IR/DerivedTypes.h"
  39. #include "llvm/IR/Function.h"
  40. #include "llvm/IR/GlobalValue.h"
  41. #include "llvm/IR/GlobalVariable.h"
  42. #include "llvm/IR/IRBuilder.h"
  43. #include "llvm/IR/Module.h"
  44. #include "llvm/IR/Type.h"
  45. #include "llvm/Support/BranchProbability.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/CommandLine.h"
  48. #include "llvm/Support/Compiler.h"
  49. #include "llvm/Support/ErrorHandling.h"
  50. #include "llvm/Support/MachineValueType.h"
  51. #include "llvm/Support/MathExtras.h"
  52. #include "llvm/Target/TargetMachine.h"
  53. #include <algorithm>
  54. #include <cassert>
  55. #include <cstddef>
  56. #include <cstdint>
  57. #include <cstring>
  58. #include <iterator>
  59. #include <string>
  60. #include <tuple>
  61. #include <utility>
  62. using namespace llvm;
  63. static cl::opt<bool> JumpIsExpensiveOverride(
  64. "jump-is-expensive", cl::init(false),
  65. cl::desc("Do not create extra branches to split comparison logic."),
  66. cl::Hidden);
  67. static cl::opt<unsigned> MinimumJumpTableEntries
  68. ("min-jump-table-entries", cl::init(4), cl::Hidden,
  69. cl::desc("Set minimum number of entries to use a jump table."));
  70. static cl::opt<unsigned> MaximumJumpTableSize
  71. ("max-jump-table-size", cl::init(UINT_MAX), cl::Hidden,
  72. cl::desc("Set maximum size of jump tables."));
  73. /// Minimum jump table density for normal functions.
  74. static cl::opt<unsigned>
  75. JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden,
  76. cl::desc("Minimum density for building a jump table in "
  77. "a normal function"));
  78. /// Minimum jump table density for -Os or -Oz functions.
  79. static cl::opt<unsigned> OptsizeJumpTableDensity(
  80. "optsize-jump-table-density", cl::init(40), cl::Hidden,
  81. cl::desc("Minimum density for building a jump table in "
  82. "an optsize function"));
  83. static bool darwinHasSinCos(const Triple &TT) {
  84. assert(TT.isOSDarwin() && "should be called with darwin triple");
  85. // Don't bother with 32 bit x86.
  86. if (TT.getArch() == Triple::x86)
  87. return false;
  88. // Macos < 10.9 has no sincos_stret.
  89. if (TT.isMacOSX())
  90. return !TT.isMacOSXVersionLT(10, 9) && TT.isArch64Bit();
  91. // iOS < 7.0 has no sincos_stret.
  92. if (TT.isiOS())
  93. return !TT.isOSVersionLT(7, 0);
  94. // Any other darwin such as WatchOS/TvOS is new enough.
  95. return true;
  96. }
  97. // Although this default value is arbitrary, it is not random. It is assumed
  98. // that a condition that evaluates the same way by a higher percentage than this
  99. // is best represented as control flow. Therefore, the default value N should be
  100. // set such that the win from N% correct executions is greater than the loss
  101. // from (100 - N)% mispredicted executions for the majority of intended targets.
  102. static cl::opt<int> MinPercentageForPredictableBranch(
  103. "min-predictable-branch", cl::init(99),
  104. cl::desc("Minimum percentage (0-100) that a condition must be either true "
  105. "or false to assume that the condition is predictable"),
  106. cl::Hidden);
  107. void TargetLoweringBase::InitLibcalls(const Triple &TT) {
  108. #define HANDLE_LIBCALL(code, name) \
  109. setLibcallName(RTLIB::code, name);
  110. #include "llvm/IR/RuntimeLibcalls.def"
  111. #undef HANDLE_LIBCALL
  112. // Initialize calling conventions to their default.
  113. for (int LC = 0; LC < RTLIB::UNKNOWN_LIBCALL; ++LC)
  114. setLibcallCallingConv((RTLIB::Libcall)LC, CallingConv::C);
  115. // A few names are different on particular architectures or environments.
  116. if (TT.isOSDarwin()) {
  117. // For f16/f32 conversions, Darwin uses the standard naming scheme, instead
  118. // of the gnueabi-style __gnu_*_ieee.
  119. // FIXME: What about other targets?
  120. setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
  121. setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
  122. // Some darwins have an optimized __bzero/bzero function.
  123. switch (TT.getArch()) {
  124. case Triple::x86:
  125. case Triple::x86_64:
  126. if (TT.isMacOSX() && !TT.isMacOSXVersionLT(10, 6))
  127. setLibcallName(RTLIB::BZERO, "__bzero");
  128. break;
  129. case Triple::aarch64:
  130. setLibcallName(RTLIB::BZERO, "bzero");
  131. break;
  132. default:
  133. break;
  134. }
  135. if (darwinHasSinCos(TT)) {
  136. setLibcallName(RTLIB::SINCOS_STRET_F32, "__sincosf_stret");
  137. setLibcallName(RTLIB::SINCOS_STRET_F64, "__sincos_stret");
  138. if (TT.isWatchABI()) {
  139. setLibcallCallingConv(RTLIB::SINCOS_STRET_F32,
  140. CallingConv::ARM_AAPCS_VFP);
  141. setLibcallCallingConv(RTLIB::SINCOS_STRET_F64,
  142. CallingConv::ARM_AAPCS_VFP);
  143. }
  144. }
  145. } else {
  146. setLibcallName(RTLIB::FPEXT_F16_F32, "__gnu_h2f_ieee");
  147. setLibcallName(RTLIB::FPROUND_F32_F16, "__gnu_f2h_ieee");
  148. }
  149. if (TT.isGNUEnvironment() || TT.isOSFuchsia() ||
  150. (TT.isAndroid() && !TT.isAndroidVersionLT(9))) {
  151. setLibcallName(RTLIB::SINCOS_F32, "sincosf");
  152. setLibcallName(RTLIB::SINCOS_F64, "sincos");
  153. setLibcallName(RTLIB::SINCOS_F80, "sincosl");
  154. setLibcallName(RTLIB::SINCOS_F128, "sincosl");
  155. setLibcallName(RTLIB::SINCOS_PPCF128, "sincosl");
  156. }
  157. if (TT.isOSOpenBSD()) {
  158. setLibcallName(RTLIB::STACKPROTECTOR_CHECK_FAIL, nullptr);
  159. }
  160. }
  161. /// getFPEXT - Return the FPEXT_*_* value for the given types, or
  162. /// UNKNOWN_LIBCALL if there is none.
  163. RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
  164. if (OpVT == MVT::f16) {
  165. if (RetVT == MVT::f32)
  166. return FPEXT_F16_F32;
  167. } else if (OpVT == MVT::f32) {
  168. if (RetVT == MVT::f64)
  169. return FPEXT_F32_F64;
  170. if (RetVT == MVT::f128)
  171. return FPEXT_F32_F128;
  172. if (RetVT == MVT::ppcf128)
  173. return FPEXT_F32_PPCF128;
  174. } else if (OpVT == MVT::f64) {
  175. if (RetVT == MVT::f128)
  176. return FPEXT_F64_F128;
  177. else if (RetVT == MVT::ppcf128)
  178. return FPEXT_F64_PPCF128;
  179. } else if (OpVT == MVT::f80) {
  180. if (RetVT == MVT::f128)
  181. return FPEXT_F80_F128;
  182. }
  183. return UNKNOWN_LIBCALL;
  184. }
  185. /// getFPROUND - Return the FPROUND_*_* value for the given types, or
  186. /// UNKNOWN_LIBCALL if there is none.
  187. RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
  188. if (RetVT == MVT::f16) {
  189. if (OpVT == MVT::f32)
  190. return FPROUND_F32_F16;
  191. if (OpVT == MVT::f64)
  192. return FPROUND_F64_F16;
  193. if (OpVT == MVT::f80)
  194. return FPROUND_F80_F16;
  195. if (OpVT == MVT::f128)
  196. return FPROUND_F128_F16;
  197. if (OpVT == MVT::ppcf128)
  198. return FPROUND_PPCF128_F16;
  199. } else if (RetVT == MVT::f32) {
  200. if (OpVT == MVT::f64)
  201. return FPROUND_F64_F32;
  202. if (OpVT == MVT::f80)
  203. return FPROUND_F80_F32;
  204. if (OpVT == MVT::f128)
  205. return FPROUND_F128_F32;
  206. if (OpVT == MVT::ppcf128)
  207. return FPROUND_PPCF128_F32;
  208. } else if (RetVT == MVT::f64) {
  209. if (OpVT == MVT::f80)
  210. return FPROUND_F80_F64;
  211. if (OpVT == MVT::f128)
  212. return FPROUND_F128_F64;
  213. if (OpVT == MVT::ppcf128)
  214. return FPROUND_PPCF128_F64;
  215. } else if (RetVT == MVT::f80) {
  216. if (OpVT == MVT::f128)
  217. return FPROUND_F128_F80;
  218. }
  219. return UNKNOWN_LIBCALL;
  220. }
  221. /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
  222. /// UNKNOWN_LIBCALL if there is none.
  223. RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
  224. if (OpVT == MVT::f32) {
  225. if (RetVT == MVT::i32)
  226. return FPTOSINT_F32_I32;
  227. if (RetVT == MVT::i64)
  228. return FPTOSINT_F32_I64;
  229. if (RetVT == MVT::i128)
  230. return FPTOSINT_F32_I128;
  231. } else if (OpVT == MVT::f64) {
  232. if (RetVT == MVT::i32)
  233. return FPTOSINT_F64_I32;
  234. if (RetVT == MVT::i64)
  235. return FPTOSINT_F64_I64;
  236. if (RetVT == MVT::i128)
  237. return FPTOSINT_F64_I128;
  238. } else if (OpVT == MVT::f80) {
  239. if (RetVT == MVT::i32)
  240. return FPTOSINT_F80_I32;
  241. if (RetVT == MVT::i64)
  242. return FPTOSINT_F80_I64;
  243. if (RetVT == MVT::i128)
  244. return FPTOSINT_F80_I128;
  245. } else if (OpVT == MVT::f128) {
  246. if (RetVT == MVT::i32)
  247. return FPTOSINT_F128_I32;
  248. if (RetVT == MVT::i64)
  249. return FPTOSINT_F128_I64;
  250. if (RetVT == MVT::i128)
  251. return FPTOSINT_F128_I128;
  252. } else if (OpVT == MVT::ppcf128) {
  253. if (RetVT == MVT::i32)
  254. return FPTOSINT_PPCF128_I32;
  255. if (RetVT == MVT::i64)
  256. return FPTOSINT_PPCF128_I64;
  257. if (RetVT == MVT::i128)
  258. return FPTOSINT_PPCF128_I128;
  259. }
  260. return UNKNOWN_LIBCALL;
  261. }
  262. /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
  263. /// UNKNOWN_LIBCALL if there is none.
  264. RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
  265. if (OpVT == MVT::f32) {
  266. if (RetVT == MVT::i32)
  267. return FPTOUINT_F32_I32;
  268. if (RetVT == MVT::i64)
  269. return FPTOUINT_F32_I64;
  270. if (RetVT == MVT::i128)
  271. return FPTOUINT_F32_I128;
  272. } else if (OpVT == MVT::f64) {
  273. if (RetVT == MVT::i32)
  274. return FPTOUINT_F64_I32;
  275. if (RetVT == MVT::i64)
  276. return FPTOUINT_F64_I64;
  277. if (RetVT == MVT::i128)
  278. return FPTOUINT_F64_I128;
  279. } else if (OpVT == MVT::f80) {
  280. if (RetVT == MVT::i32)
  281. return FPTOUINT_F80_I32;
  282. if (RetVT == MVT::i64)
  283. return FPTOUINT_F80_I64;
  284. if (RetVT == MVT::i128)
  285. return FPTOUINT_F80_I128;
  286. } else if (OpVT == MVT::f128) {
  287. if (RetVT == MVT::i32)
  288. return FPTOUINT_F128_I32;
  289. if (RetVT == MVT::i64)
  290. return FPTOUINT_F128_I64;
  291. if (RetVT == MVT::i128)
  292. return FPTOUINT_F128_I128;
  293. } else if (OpVT == MVT::ppcf128) {
  294. if (RetVT == MVT::i32)
  295. return FPTOUINT_PPCF128_I32;
  296. if (RetVT == MVT::i64)
  297. return FPTOUINT_PPCF128_I64;
  298. if (RetVT == MVT::i128)
  299. return FPTOUINT_PPCF128_I128;
  300. }
  301. return UNKNOWN_LIBCALL;
  302. }
  303. /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
  304. /// UNKNOWN_LIBCALL if there is none.
  305. RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
  306. if (OpVT == MVT::i32) {
  307. if (RetVT == MVT::f32)
  308. return SINTTOFP_I32_F32;
  309. if (RetVT == MVT::f64)
  310. return SINTTOFP_I32_F64;
  311. if (RetVT == MVT::f80)
  312. return SINTTOFP_I32_F80;
  313. if (RetVT == MVT::f128)
  314. return SINTTOFP_I32_F128;
  315. if (RetVT == MVT::ppcf128)
  316. return SINTTOFP_I32_PPCF128;
  317. } else if (OpVT == MVT::i64) {
  318. if (RetVT == MVT::f32)
  319. return SINTTOFP_I64_F32;
  320. if (RetVT == MVT::f64)
  321. return SINTTOFP_I64_F64;
  322. if (RetVT == MVT::f80)
  323. return SINTTOFP_I64_F80;
  324. if (RetVT == MVT::f128)
  325. return SINTTOFP_I64_F128;
  326. if (RetVT == MVT::ppcf128)
  327. return SINTTOFP_I64_PPCF128;
  328. } else if (OpVT == MVT::i128) {
  329. if (RetVT == MVT::f32)
  330. return SINTTOFP_I128_F32;
  331. if (RetVT == MVT::f64)
  332. return SINTTOFP_I128_F64;
  333. if (RetVT == MVT::f80)
  334. return SINTTOFP_I128_F80;
  335. if (RetVT == MVT::f128)
  336. return SINTTOFP_I128_F128;
  337. if (RetVT == MVT::ppcf128)
  338. return SINTTOFP_I128_PPCF128;
  339. }
  340. return UNKNOWN_LIBCALL;
  341. }
  342. /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
  343. /// UNKNOWN_LIBCALL if there is none.
  344. RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
  345. if (OpVT == MVT::i32) {
  346. if (RetVT == MVT::f32)
  347. return UINTTOFP_I32_F32;
  348. if (RetVT == MVT::f64)
  349. return UINTTOFP_I32_F64;
  350. if (RetVT == MVT::f80)
  351. return UINTTOFP_I32_F80;
  352. if (RetVT == MVT::f128)
  353. return UINTTOFP_I32_F128;
  354. if (RetVT == MVT::ppcf128)
  355. return UINTTOFP_I32_PPCF128;
  356. } else if (OpVT == MVT::i64) {
  357. if (RetVT == MVT::f32)
  358. return UINTTOFP_I64_F32;
  359. if (RetVT == MVT::f64)
  360. return UINTTOFP_I64_F64;
  361. if (RetVT == MVT::f80)
  362. return UINTTOFP_I64_F80;
  363. if (RetVT == MVT::f128)
  364. return UINTTOFP_I64_F128;
  365. if (RetVT == MVT::ppcf128)
  366. return UINTTOFP_I64_PPCF128;
  367. } else if (OpVT == MVT::i128) {
  368. if (RetVT == MVT::f32)
  369. return UINTTOFP_I128_F32;
  370. if (RetVT == MVT::f64)
  371. return UINTTOFP_I128_F64;
  372. if (RetVT == MVT::f80)
  373. return UINTTOFP_I128_F80;
  374. if (RetVT == MVT::f128)
  375. return UINTTOFP_I128_F128;
  376. if (RetVT == MVT::ppcf128)
  377. return UINTTOFP_I128_PPCF128;
  378. }
  379. return UNKNOWN_LIBCALL;
  380. }
  381. RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) {
  382. #define OP_TO_LIBCALL(Name, Enum) \
  383. case Name: \
  384. switch (VT.SimpleTy) { \
  385. default: \
  386. return UNKNOWN_LIBCALL; \
  387. case MVT::i8: \
  388. return Enum##_1; \
  389. case MVT::i16: \
  390. return Enum##_2; \
  391. case MVT::i32: \
  392. return Enum##_4; \
  393. case MVT::i64: \
  394. return Enum##_8; \
  395. case MVT::i128: \
  396. return Enum##_16; \
  397. }
  398. switch (Opc) {
  399. OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET)
  400. OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP)
  401. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD)
  402. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB)
  403. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND)
  404. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR)
  405. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR)
  406. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND)
  407. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX)
  408. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX)
  409. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN)
  410. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN)
  411. }
  412. #undef OP_TO_LIBCALL
  413. return UNKNOWN_LIBCALL;
  414. }
  415. RTLIB::Libcall RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
  416. switch (ElementSize) {
  417. case 1:
  418. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_1;
  419. case 2:
  420. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_2;
  421. case 4:
  422. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_4;
  423. case 8:
  424. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_8;
  425. case 16:
  426. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_16;
  427. default:
  428. return UNKNOWN_LIBCALL;
  429. }
  430. }
  431. RTLIB::Libcall RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
  432. switch (ElementSize) {
  433. case 1:
  434. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_1;
  435. case 2:
  436. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_2;
  437. case 4:
  438. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_4;
  439. case 8:
  440. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_8;
  441. case 16:
  442. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_16;
  443. default:
  444. return UNKNOWN_LIBCALL;
  445. }
  446. }
  447. RTLIB::Libcall RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
  448. switch (ElementSize) {
  449. case 1:
  450. return MEMSET_ELEMENT_UNORDERED_ATOMIC_1;
  451. case 2:
  452. return MEMSET_ELEMENT_UNORDERED_ATOMIC_2;
  453. case 4:
  454. return MEMSET_ELEMENT_UNORDERED_ATOMIC_4;
  455. case 8:
  456. return MEMSET_ELEMENT_UNORDERED_ATOMIC_8;
  457. case 16:
  458. return MEMSET_ELEMENT_UNORDERED_ATOMIC_16;
  459. default:
  460. return UNKNOWN_LIBCALL;
  461. }
  462. }
  463. /// InitCmpLibcallCCs - Set default comparison libcall CC.
  464. static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
  465. memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
  466. CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
  467. CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
  468. CCs[RTLIB::OEQ_F128] = ISD::SETEQ;
  469. CCs[RTLIB::OEQ_PPCF128] = ISD::SETEQ;
  470. CCs[RTLIB::UNE_F32] = ISD::SETNE;
  471. CCs[RTLIB::UNE_F64] = ISD::SETNE;
  472. CCs[RTLIB::UNE_F128] = ISD::SETNE;
  473. CCs[RTLIB::UNE_PPCF128] = ISD::SETNE;
  474. CCs[RTLIB::OGE_F32] = ISD::SETGE;
  475. CCs[RTLIB::OGE_F64] = ISD::SETGE;
  476. CCs[RTLIB::OGE_F128] = ISD::SETGE;
  477. CCs[RTLIB::OGE_PPCF128] = ISD::SETGE;
  478. CCs[RTLIB::OLT_F32] = ISD::SETLT;
  479. CCs[RTLIB::OLT_F64] = ISD::SETLT;
  480. CCs[RTLIB::OLT_F128] = ISD::SETLT;
  481. CCs[RTLIB::OLT_PPCF128] = ISD::SETLT;
  482. CCs[RTLIB::OLE_F32] = ISD::SETLE;
  483. CCs[RTLIB::OLE_F64] = ISD::SETLE;
  484. CCs[RTLIB::OLE_F128] = ISD::SETLE;
  485. CCs[RTLIB::OLE_PPCF128] = ISD::SETLE;
  486. CCs[RTLIB::OGT_F32] = ISD::SETGT;
  487. CCs[RTLIB::OGT_F64] = ISD::SETGT;
  488. CCs[RTLIB::OGT_F128] = ISD::SETGT;
  489. CCs[RTLIB::OGT_PPCF128] = ISD::SETGT;
  490. CCs[RTLIB::UO_F32] = ISD::SETNE;
  491. CCs[RTLIB::UO_F64] = ISD::SETNE;
  492. CCs[RTLIB::UO_F128] = ISD::SETNE;
  493. CCs[RTLIB::UO_PPCF128] = ISD::SETNE;
  494. CCs[RTLIB::O_F32] = ISD::SETEQ;
  495. CCs[RTLIB::O_F64] = ISD::SETEQ;
  496. CCs[RTLIB::O_F128] = ISD::SETEQ;
  497. CCs[RTLIB::O_PPCF128] = ISD::SETEQ;
  498. }
  499. /// NOTE: The TargetMachine owns TLOF.
  500. TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm) : TM(tm) {
  501. initActions();
  502. // Perform these initializations only once.
  503. MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove =
  504. MaxLoadsPerMemcmp = 8;
  505. MaxGluedStoresPerMemcpy = 0;
  506. MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize =
  507. MaxStoresPerMemmoveOptSize = MaxLoadsPerMemcmpOptSize = 4;
  508. UseUnderscoreSetJmp = false;
  509. UseUnderscoreLongJmp = false;
  510. HasMultipleConditionRegisters = false;
  511. HasExtractBitsInsn = false;
  512. JumpIsExpensive = JumpIsExpensiveOverride;
  513. PredictableSelectIsExpensive = false;
  514. EnableExtLdPromotion = false;
  515. StackPointerRegisterToSaveRestore = 0;
  516. BooleanContents = UndefinedBooleanContent;
  517. BooleanFloatContents = UndefinedBooleanContent;
  518. BooleanVectorContents = UndefinedBooleanContent;
  519. SchedPreferenceInfo = Sched::ILP;
  520. JumpBufSize = 0;
  521. JumpBufAlignment = 0;
  522. MinFunctionAlignment = 0;
  523. PrefFunctionAlignment = 0;
  524. PrefLoopAlignment = 0;
  525. GatherAllAliasesMaxDepth = 18;
  526. MinStackArgumentAlignment = 1;
  527. // TODO: the default will be switched to 0 in the next commit, along
  528. // with the Target-specific changes necessary.
  529. MaxAtomicSizeInBitsSupported = 1024;
  530. MinCmpXchgSizeInBits = 0;
  531. SupportsUnalignedAtomics = false;
  532. std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr);
  533. InitLibcalls(TM.getTargetTriple());
  534. InitCmpLibcallCCs(CmpLibcallCCs);
  535. }
  536. void TargetLoweringBase::initActions() {
  537. // All operations default to being supported.
  538. memset(OpActions, 0, sizeof(OpActions));
  539. memset(LoadExtActions, 0, sizeof(LoadExtActions));
  540. memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
  541. memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
  542. memset(CondCodeActions, 0, sizeof(CondCodeActions));
  543. std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr);
  544. std::fill(std::begin(TargetDAGCombineArray),
  545. std::end(TargetDAGCombineArray), 0);
  546. for (MVT VT : MVT::fp_valuetypes()) {
  547. MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
  548. if (IntVT.isValid()) {
  549. setOperationAction(ISD::ATOMIC_SWAP, VT, Promote);
  550. AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT);
  551. }
  552. }
  553. // Set default actions for various operations.
  554. for (MVT VT : MVT::all_valuetypes()) {
  555. // Default all indexed load / store to expand.
  556. for (unsigned IM = (unsigned)ISD::PRE_INC;
  557. IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
  558. setIndexedLoadAction(IM, VT, Expand);
  559. setIndexedStoreAction(IM, VT, Expand);
  560. }
  561. // Most backends expect to see the node which just returns the value loaded.
  562. setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand);
  563. // These operations default to expand.
  564. setOperationAction(ISD::FGETSIGN, VT, Expand);
  565. setOperationAction(ISD::CONCAT_VECTORS, VT, Expand);
  566. setOperationAction(ISD::FMINNUM, VT, Expand);
  567. setOperationAction(ISD::FMAXNUM, VT, Expand);
  568. setOperationAction(ISD::FMINNUM_IEEE, VT, Expand);
  569. setOperationAction(ISD::FMAXNUM_IEEE, VT, Expand);
  570. setOperationAction(ISD::FMINIMUM, VT, Expand);
  571. setOperationAction(ISD::FMAXIMUM, VT, Expand);
  572. setOperationAction(ISD::FMAD, VT, Expand);
  573. setOperationAction(ISD::SMIN, VT, Expand);
  574. setOperationAction(ISD::SMAX, VT, Expand);
  575. setOperationAction(ISD::UMIN, VT, Expand);
  576. setOperationAction(ISD::UMAX, VT, Expand);
  577. setOperationAction(ISD::ABS, VT, Expand);
  578. setOperationAction(ISD::FSHL, VT, Expand);
  579. setOperationAction(ISD::FSHR, VT, Expand);
  580. setOperationAction(ISD::SADDSAT, VT, Expand);
  581. setOperationAction(ISD::UADDSAT, VT, Expand);
  582. setOperationAction(ISD::SSUBSAT, VT, Expand);
  583. setOperationAction(ISD::USUBSAT, VT, Expand);
  584. setOperationAction(ISD::SMULFIX, VT, Expand);
  585. setOperationAction(ISD::UMULFIX, VT, Expand);
  586. // Overflow operations default to expand
  587. setOperationAction(ISD::SADDO, VT, Expand);
  588. setOperationAction(ISD::SSUBO, VT, Expand);
  589. setOperationAction(ISD::UADDO, VT, Expand);
  590. setOperationAction(ISD::USUBO, VT, Expand);
  591. setOperationAction(ISD::SMULO, VT, Expand);
  592. setOperationAction(ISD::UMULO, VT, Expand);
  593. // ADDCARRY operations default to expand
  594. setOperationAction(ISD::ADDCARRY, VT, Expand);
  595. setOperationAction(ISD::SUBCARRY, VT, Expand);
  596. setOperationAction(ISD::SETCCCARRY, VT, Expand);
  597. // ADDC/ADDE/SUBC/SUBE default to expand.
  598. setOperationAction(ISD::ADDC, VT, Expand);
  599. setOperationAction(ISD::ADDE, VT, Expand);
  600. setOperationAction(ISD::SUBC, VT, Expand);
  601. setOperationAction(ISD::SUBE, VT, Expand);
  602. // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
  603. setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
  604. setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
  605. setOperationAction(ISD::BITREVERSE, VT, Expand);
  606. // These library functions default to expand.
  607. setOperationAction(ISD::FROUND, VT, Expand);
  608. setOperationAction(ISD::FPOWI, VT, Expand);
  609. // These operations default to expand for vector types.
  610. if (VT.isVector()) {
  611. setOperationAction(ISD::FCOPYSIGN, VT, Expand);
  612. setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, VT, Expand);
  613. setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Expand);
  614. setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand);
  615. }
  616. // For most targets @llvm.get.dynamic.area.offset just returns 0.
  617. setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
  618. // Vector reduction default to expand.
  619. setOperationAction(ISD::VECREDUCE_FADD, VT, Expand);
  620. setOperationAction(ISD::VECREDUCE_FMUL, VT, Expand);
  621. setOperationAction(ISD::VECREDUCE_ADD, VT, Expand);
  622. setOperationAction(ISD::VECREDUCE_MUL, VT, Expand);
  623. setOperationAction(ISD::VECREDUCE_AND, VT, Expand);
  624. setOperationAction(ISD::VECREDUCE_OR, VT, Expand);
  625. setOperationAction(ISD::VECREDUCE_XOR, VT, Expand);
  626. setOperationAction(ISD::VECREDUCE_SMAX, VT, Expand);
  627. setOperationAction(ISD::VECREDUCE_SMIN, VT, Expand);
  628. setOperationAction(ISD::VECREDUCE_UMAX, VT, Expand);
  629. setOperationAction(ISD::VECREDUCE_UMIN, VT, Expand);
  630. setOperationAction(ISD::VECREDUCE_FMAX, VT, Expand);
  631. setOperationAction(ISD::VECREDUCE_FMIN, VT, Expand);
  632. }
  633. // Most targets ignore the @llvm.prefetch intrinsic.
  634. setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
  635. // Most targets also ignore the @llvm.readcyclecounter intrinsic.
  636. setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
  637. // ConstantFP nodes default to expand. Targets can either change this to
  638. // Legal, in which case all fp constants are legal, or use isFPImmLegal()
  639. // to optimize expansions for certain constants.
  640. setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
  641. setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
  642. setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
  643. setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
  644. setOperationAction(ISD::ConstantFP, MVT::f128, Expand);
  645. // These library functions default to expand.
  646. for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
  647. setOperationAction(ISD::FCBRT, VT, Expand);
  648. setOperationAction(ISD::FLOG , VT, Expand);
  649. setOperationAction(ISD::FLOG2, VT, Expand);
  650. setOperationAction(ISD::FLOG10, VT, Expand);
  651. setOperationAction(ISD::FEXP , VT, Expand);
  652. setOperationAction(ISD::FEXP2, VT, Expand);
  653. setOperationAction(ISD::FFLOOR, VT, Expand);
  654. setOperationAction(ISD::FNEARBYINT, VT, Expand);
  655. setOperationAction(ISD::FCEIL, VT, Expand);
  656. setOperationAction(ISD::FRINT, VT, Expand);
  657. setOperationAction(ISD::FTRUNC, VT, Expand);
  658. setOperationAction(ISD::FROUND, VT, Expand);
  659. }
  660. // Default ISD::TRAP to expand (which turns it into abort).
  661. setOperationAction(ISD::TRAP, MVT::Other, Expand);
  662. // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
  663. // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
  664. setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
  665. }
  666. MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
  667. EVT) const {
  668. return MVT::getIntegerVT(8 * DL.getPointerSize(0));
  669. }
  670. EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
  671. bool LegalTypes) const {
  672. assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
  673. if (LHSTy.isVector())
  674. return LHSTy;
  675. return LegalTypes ? getScalarShiftAmountTy(DL, LHSTy)
  676. : getPointerTy(DL);
  677. }
  678. bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
  679. assert(isTypeLegal(VT));
  680. switch (Op) {
  681. default:
  682. return false;
  683. case ISD::SDIV:
  684. case ISD::UDIV:
  685. case ISD::SREM:
  686. case ISD::UREM:
  687. return true;
  688. }
  689. }
  690. void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
  691. // If the command-line option was specified, ignore this request.
  692. if (!JumpIsExpensiveOverride.getNumOccurrences())
  693. JumpIsExpensive = isExpensive;
  694. }
  695. TargetLoweringBase::LegalizeKind
  696. TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
  697. // If this is a simple type, use the ComputeRegisterProp mechanism.
  698. if (VT.isSimple()) {
  699. MVT SVT = VT.getSimpleVT();
  700. assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
  701. MVT NVT = TransformToType[SVT.SimpleTy];
  702. LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
  703. assert((LA == TypeLegal || LA == TypeSoftenFloat ||
  704. ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger) &&
  705. "Promote may not follow Expand or Promote");
  706. if (LA == TypeSplitVector)
  707. return LegalizeKind(LA,
  708. EVT::getVectorVT(Context, SVT.getVectorElementType(),
  709. SVT.getVectorNumElements() / 2));
  710. if (LA == TypeScalarizeVector)
  711. return LegalizeKind(LA, SVT.getVectorElementType());
  712. return LegalizeKind(LA, NVT);
  713. }
  714. // Handle Extended Scalar Types.
  715. if (!VT.isVector()) {
  716. assert(VT.isInteger() && "Float types must be simple");
  717. unsigned BitSize = VT.getSizeInBits();
  718. // First promote to a power-of-two size, then expand if necessary.
  719. if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
  720. EVT NVT = VT.getRoundIntegerType(Context);
  721. assert(NVT != VT && "Unable to round integer VT");
  722. LegalizeKind NextStep = getTypeConversion(Context, NVT);
  723. // Avoid multi-step promotion.
  724. if (NextStep.first == TypePromoteInteger)
  725. return NextStep;
  726. // Return rounded integer type.
  727. return LegalizeKind(TypePromoteInteger, NVT);
  728. }
  729. return LegalizeKind(TypeExpandInteger,
  730. EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
  731. }
  732. // Handle vector types.
  733. unsigned NumElts = VT.getVectorNumElements();
  734. EVT EltVT = VT.getVectorElementType();
  735. // Vectors with only one element are always scalarized.
  736. if (NumElts == 1)
  737. return LegalizeKind(TypeScalarizeVector, EltVT);
  738. // Try to widen vector elements until the element type is a power of two and
  739. // promote it to a legal type later on, for example:
  740. // <3 x i8> -> <4 x i8> -> <4 x i32>
  741. if (EltVT.isInteger()) {
  742. // Vectors with a number of elements that is not a power of two are always
  743. // widened, for example <3 x i8> -> <4 x i8>.
  744. if (!VT.isPow2VectorType()) {
  745. NumElts = (unsigned)NextPowerOf2(NumElts);
  746. EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
  747. return LegalizeKind(TypeWidenVector, NVT);
  748. }
  749. // Examine the element type.
  750. LegalizeKind LK = getTypeConversion(Context, EltVT);
  751. // If type is to be expanded, split the vector.
  752. // <4 x i140> -> <2 x i140>
  753. if (LK.first == TypeExpandInteger)
  754. return LegalizeKind(TypeSplitVector,
  755. EVT::getVectorVT(Context, EltVT, NumElts / 2));
  756. // Promote the integer element types until a legal vector type is found
  757. // or until the element integer type is too big. If a legal type was not
  758. // found, fallback to the usual mechanism of widening/splitting the
  759. // vector.
  760. EVT OldEltVT = EltVT;
  761. while (true) {
  762. // Increase the bitwidth of the element to the next pow-of-two
  763. // (which is greater than 8 bits).
  764. EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
  765. .getRoundIntegerType(Context);
  766. // Stop trying when getting a non-simple element type.
  767. // Note that vector elements may be greater than legal vector element
  768. // types. Example: X86 XMM registers hold 64bit element on 32bit
  769. // systems.
  770. if (!EltVT.isSimple())
  771. break;
  772. // Build a new vector type and check if it is legal.
  773. MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
  774. // Found a legal promoted vector type.
  775. if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
  776. return LegalizeKind(TypePromoteInteger,
  777. EVT::getVectorVT(Context, EltVT, NumElts));
  778. }
  779. // Reset the type to the unexpanded type if we did not find a legal vector
  780. // type with a promoted vector element type.
  781. EltVT = OldEltVT;
  782. }
  783. // Try to widen the vector until a legal type is found.
  784. // If there is no wider legal type, split the vector.
  785. while (true) {
  786. // Round up to the next power of 2.
  787. NumElts = (unsigned)NextPowerOf2(NumElts);
  788. // If there is no simple vector type with this many elements then there
  789. // cannot be a larger legal vector type. Note that this assumes that
  790. // there are no skipped intermediate vector types in the simple types.
  791. if (!EltVT.isSimple())
  792. break;
  793. MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
  794. if (LargerVector == MVT())
  795. break;
  796. // If this type is legal then widen the vector.
  797. if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
  798. return LegalizeKind(TypeWidenVector, LargerVector);
  799. }
  800. // Widen odd vectors to next power of two.
  801. if (!VT.isPow2VectorType()) {
  802. EVT NVT = VT.getPow2VectorType(Context);
  803. return LegalizeKind(TypeWidenVector, NVT);
  804. }
  805. // Vectors with illegal element types are expanded.
  806. EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
  807. return LegalizeKind(TypeSplitVector, NVT);
  808. }
  809. static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
  810. unsigned &NumIntermediates,
  811. MVT &RegisterVT,
  812. TargetLoweringBase *TLI) {
  813. // Figure out the right, legal destination reg to copy into.
  814. unsigned NumElts = VT.getVectorNumElements();
  815. MVT EltTy = VT.getVectorElementType();
  816. unsigned NumVectorRegs = 1;
  817. // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
  818. // could break down into LHS/RHS like LegalizeDAG does.
  819. if (!isPowerOf2_32(NumElts)) {
  820. NumVectorRegs = NumElts;
  821. NumElts = 1;
  822. }
  823. // Divide the input until we get to a supported size. This will always
  824. // end with a scalar if the target doesn't support vectors.
  825. while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
  826. NumElts >>= 1;
  827. NumVectorRegs <<= 1;
  828. }
  829. NumIntermediates = NumVectorRegs;
  830. MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
  831. if (!TLI->isTypeLegal(NewVT))
  832. NewVT = EltTy;
  833. IntermediateVT = NewVT;
  834. unsigned NewVTSize = NewVT.getSizeInBits();
  835. // Convert sizes such as i33 to i64.
  836. if (!isPowerOf2_32(NewVTSize))
  837. NewVTSize = NextPowerOf2(NewVTSize);
  838. MVT DestVT = TLI->getRegisterType(NewVT);
  839. RegisterVT = DestVT;
  840. if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
  841. return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
  842. // Otherwise, promotion or legal types use the same number of registers as
  843. // the vector decimated to the appropriate level.
  844. return NumVectorRegs;
  845. }
  846. /// isLegalRC - Return true if the value types that can be represented by the
  847. /// specified register class are all legal.
  848. bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
  849. const TargetRegisterClass &RC) const {
  850. for (auto I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
  851. if (isTypeLegal(*I))
  852. return true;
  853. return false;
  854. }
  855. /// Replace/modify any TargetFrameIndex operands with a targte-dependent
  856. /// sequence of memory operands that is recognized by PrologEpilogInserter.
  857. MachineBasicBlock *
  858. TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
  859. MachineBasicBlock *MBB) const {
  860. MachineInstr *MI = &InitialMI;
  861. MachineFunction &MF = *MI->getMF();
  862. MachineFrameInfo &MFI = MF.getFrameInfo();
  863. // We're handling multiple types of operands here:
  864. // PATCHPOINT MetaArgs - live-in, read only, direct
  865. // STATEPOINT Deopt Spill - live-through, read only, indirect
  866. // STATEPOINT Deopt Alloca - live-through, read only, direct
  867. // (We're currently conservative and mark the deopt slots read/write in
  868. // practice.)
  869. // STATEPOINT GC Spill - live-through, read/write, indirect
  870. // STATEPOINT GC Alloca - live-through, read/write, direct
  871. // The live-in vs live-through is handled already (the live through ones are
  872. // all stack slots), but we need to handle the different type of stackmap
  873. // operands and memory effects here.
  874. // MI changes inside this loop as we grow operands.
  875. for(unsigned OperIdx = 0; OperIdx != MI->getNumOperands(); ++OperIdx) {
  876. MachineOperand &MO = MI->getOperand(OperIdx);
  877. if (!MO.isFI())
  878. continue;
  879. // foldMemoryOperand builds a new MI after replacing a single FI operand
  880. // with the canonical set of five x86 addressing-mode operands.
  881. int FI = MO.getIndex();
  882. MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
  883. // Copy operands before the frame-index.
  884. for (unsigned i = 0; i < OperIdx; ++i)
  885. MIB.add(MI->getOperand(i));
  886. // Add frame index operands recognized by stackmaps.cpp
  887. if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
  888. // indirect-mem-ref tag, size, #FI, offset.
  889. // Used for spills inserted by StatepointLowering. This codepath is not
  890. // used for patchpoints/stackmaps at all, for these spilling is done via
  891. // foldMemoryOperand callback only.
  892. assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
  893. MIB.addImm(StackMaps::IndirectMemRefOp);
  894. MIB.addImm(MFI.getObjectSize(FI));
  895. MIB.add(MI->getOperand(OperIdx));
  896. MIB.addImm(0);
  897. } else {
  898. // direct-mem-ref tag, #FI, offset.
  899. // Used by patchpoint, and direct alloca arguments to statepoints
  900. MIB.addImm(StackMaps::DirectMemRefOp);
  901. MIB.add(MI->getOperand(OperIdx));
  902. MIB.addImm(0);
  903. }
  904. // Copy the operands after the frame index.
  905. for (unsigned i = OperIdx + 1; i != MI->getNumOperands(); ++i)
  906. MIB.add(MI->getOperand(i));
  907. // Inherit previous memory operands.
  908. MIB.cloneMemRefs(*MI);
  909. assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
  910. // Add a new memory operand for this FI.
  911. assert(MFI.getObjectOffset(FI) != -1);
  912. // Note: STATEPOINT MMOs are added during SelectionDAG. STACKMAP, and
  913. // PATCHPOINT should be updated to do the same. (TODO)
  914. if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
  915. auto Flags = MachineMemOperand::MOLoad;
  916. MachineMemOperand *MMO = MF.getMachineMemOperand(
  917. MachinePointerInfo::getFixedStack(MF, FI), Flags,
  918. MF.getDataLayout().getPointerSize(), MFI.getObjectAlignment(FI));
  919. MIB->addMemOperand(MF, MMO);
  920. }
  921. // Replace the instruction and update the operand index.
  922. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  923. OperIdx += (MIB->getNumOperands() - MI->getNumOperands()) - 1;
  924. MI->eraseFromParent();
  925. MI = MIB;
  926. }
  927. return MBB;
  928. }
  929. MachineBasicBlock *
  930. TargetLoweringBase::emitXRayCustomEvent(MachineInstr &MI,
  931. MachineBasicBlock *MBB) const {
  932. assert(MI.getOpcode() == TargetOpcode::PATCHABLE_EVENT_CALL &&
  933. "Called emitXRayCustomEvent on the wrong MI!");
  934. auto &MF = *MI.getMF();
  935. auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
  936. for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
  937. MIB.add(MI.getOperand(OpIdx));
  938. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  939. MI.eraseFromParent();
  940. return MBB;
  941. }
  942. MachineBasicBlock *
  943. TargetLoweringBase::emitXRayTypedEvent(MachineInstr &MI,
  944. MachineBasicBlock *MBB) const {
  945. assert(MI.getOpcode() == TargetOpcode::PATCHABLE_TYPED_EVENT_CALL &&
  946. "Called emitXRayTypedEvent on the wrong MI!");
  947. auto &MF = *MI.getMF();
  948. auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
  949. for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
  950. MIB.add(MI.getOperand(OpIdx));
  951. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  952. MI.eraseFromParent();
  953. return MBB;
  954. }
  955. /// findRepresentativeClass - Return the largest legal super-reg register class
  956. /// of the register class for the specified type and its associated "cost".
  957. // This function is in TargetLowering because it uses RegClassForVT which would
  958. // need to be moved to TargetRegisterInfo and would necessitate moving
  959. // isTypeLegal over as well - a massive change that would just require
  960. // TargetLowering having a TargetRegisterInfo class member that it would use.
  961. std::pair<const TargetRegisterClass *, uint8_t>
  962. TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
  963. MVT VT) const {
  964. const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
  965. if (!RC)
  966. return std::make_pair(RC, 0);
  967. // Compute the set of all super-register classes.
  968. BitVector SuperRegRC(TRI->getNumRegClasses());
  969. for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
  970. SuperRegRC.setBitsInMask(RCI.getMask());
  971. // Find the first legal register class with the largest spill size.
  972. const TargetRegisterClass *BestRC = RC;
  973. for (unsigned i : SuperRegRC.set_bits()) {
  974. const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
  975. // We want the largest possible spill size.
  976. if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
  977. continue;
  978. if (!isLegalRC(*TRI, *SuperRC))
  979. continue;
  980. BestRC = SuperRC;
  981. }
  982. return std::make_pair(BestRC, 1);
  983. }
  984. /// computeRegisterProperties - Once all of the register classes are added,
  985. /// this allows us to compute derived properties we expose.
  986. void TargetLoweringBase::computeRegisterProperties(
  987. const TargetRegisterInfo *TRI) {
  988. static_assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE,
  989. "Too many value types for ValueTypeActions to hold!");
  990. // Everything defaults to needing one register.
  991. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
  992. NumRegistersForVT[i] = 1;
  993. RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
  994. }
  995. // ...except isVoid, which doesn't need any registers.
  996. NumRegistersForVT[MVT::isVoid] = 0;
  997. // Find the largest integer register class.
  998. unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
  999. for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
  1000. assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
  1001. // Every integer value type larger than this largest register takes twice as
  1002. // many registers to represent as the previous ValueType.
  1003. for (unsigned ExpandedReg = LargestIntReg + 1;
  1004. ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
  1005. NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
  1006. RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
  1007. TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
  1008. ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
  1009. TypeExpandInteger);
  1010. }
  1011. // Inspect all of the ValueType's smaller than the largest integer
  1012. // register to see which ones need promotion.
  1013. unsigned LegalIntReg = LargestIntReg;
  1014. for (unsigned IntReg = LargestIntReg - 1;
  1015. IntReg >= (unsigned)MVT::i1; --IntReg) {
  1016. MVT IVT = (MVT::SimpleValueType)IntReg;
  1017. if (isTypeLegal(IVT)) {
  1018. LegalIntReg = IntReg;
  1019. } else {
  1020. RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
  1021. (MVT::SimpleValueType)LegalIntReg;
  1022. ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
  1023. }
  1024. }
  1025. // ppcf128 type is really two f64's.
  1026. if (!isTypeLegal(MVT::ppcf128)) {
  1027. if (isTypeLegal(MVT::f64)) {
  1028. NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
  1029. RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
  1030. TransformToType[MVT::ppcf128] = MVT::f64;
  1031. ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
  1032. } else {
  1033. NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
  1034. RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
  1035. TransformToType[MVT::ppcf128] = MVT::i128;
  1036. ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
  1037. }
  1038. }
  1039. // Decide how to handle f128. If the target does not have native f128 support,
  1040. // expand it to i128 and we will be generating soft float library calls.
  1041. if (!isTypeLegal(MVT::f128)) {
  1042. NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
  1043. RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
  1044. TransformToType[MVT::f128] = MVT::i128;
  1045. ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
  1046. }
  1047. // Decide how to handle f64. If the target does not have native f64 support,
  1048. // expand it to i64 and we will be generating soft float library calls.
  1049. if (!isTypeLegal(MVT::f64)) {
  1050. NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
  1051. RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
  1052. TransformToType[MVT::f64] = MVT::i64;
  1053. ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
  1054. }
  1055. // Decide how to handle f32. If the target does not have native f32 support,
  1056. // expand it to i32 and we will be generating soft float library calls.
  1057. if (!isTypeLegal(MVT::f32)) {
  1058. NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
  1059. RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
  1060. TransformToType[MVT::f32] = MVT::i32;
  1061. ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
  1062. }
  1063. // Decide how to handle f16. If the target does not have native f16 support,
  1064. // promote it to f32, because there are no f16 library calls (except for
  1065. // conversions).
  1066. if (!isTypeLegal(MVT::f16)) {
  1067. NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
  1068. RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
  1069. TransformToType[MVT::f16] = MVT::f32;
  1070. ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
  1071. }
  1072. // Loop over all of the vector value types to see which need transformations.
  1073. for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
  1074. i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
  1075. MVT VT = (MVT::SimpleValueType) i;
  1076. if (isTypeLegal(VT))
  1077. continue;
  1078. MVT EltVT = VT.getVectorElementType();
  1079. unsigned NElts = VT.getVectorNumElements();
  1080. bool IsLegalWiderType = false;
  1081. LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
  1082. switch (PreferredAction) {
  1083. case TypePromoteInteger:
  1084. // Try to promote the elements of integer vectors. If no legal
  1085. // promotion was found, fall through to the widen-vector method.
  1086. for (unsigned nVT = i + 1; nVT <= MVT::LAST_INTEGER_VECTOR_VALUETYPE; ++nVT) {
  1087. MVT SVT = (MVT::SimpleValueType) nVT;
  1088. // Promote vectors of integers to vectors with the same number
  1089. // of elements, with a wider element type.
  1090. if (SVT.getScalarSizeInBits() > EltVT.getSizeInBits() &&
  1091. SVT.getVectorNumElements() == NElts && isTypeLegal(SVT)) {
  1092. TransformToType[i] = SVT;
  1093. RegisterTypeForVT[i] = SVT;
  1094. NumRegistersForVT[i] = 1;
  1095. ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
  1096. IsLegalWiderType = true;
  1097. break;
  1098. }
  1099. }
  1100. if (IsLegalWiderType)
  1101. break;
  1102. LLVM_FALLTHROUGH;
  1103. case TypeWidenVector:
  1104. // Try to widen the vector.
  1105. for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
  1106. MVT SVT = (MVT::SimpleValueType) nVT;
  1107. if (SVT.getVectorElementType() == EltVT
  1108. && SVT.getVectorNumElements() > NElts && isTypeLegal(SVT)) {
  1109. TransformToType[i] = SVT;
  1110. RegisterTypeForVT[i] = SVT;
  1111. NumRegistersForVT[i] = 1;
  1112. ValueTypeActions.setTypeAction(VT, TypeWidenVector);
  1113. IsLegalWiderType = true;
  1114. break;
  1115. }
  1116. }
  1117. if (IsLegalWiderType)
  1118. break;
  1119. LLVM_FALLTHROUGH;
  1120. case TypeSplitVector:
  1121. case TypeScalarizeVector: {
  1122. MVT IntermediateVT;
  1123. MVT RegisterVT;
  1124. unsigned NumIntermediates;
  1125. NumRegistersForVT[i] = getVectorTypeBreakdownMVT(VT, IntermediateVT,
  1126. NumIntermediates, RegisterVT, this);
  1127. RegisterTypeForVT[i] = RegisterVT;
  1128. MVT NVT = VT.getPow2VectorType();
  1129. if (NVT == VT) {
  1130. // Type is already a power of 2. The default action is to split.
  1131. TransformToType[i] = MVT::Other;
  1132. if (PreferredAction == TypeScalarizeVector)
  1133. ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
  1134. else if (PreferredAction == TypeSplitVector)
  1135. ValueTypeActions.setTypeAction(VT, TypeSplitVector);
  1136. else
  1137. // Set type action according to the number of elements.
  1138. ValueTypeActions.setTypeAction(VT, NElts == 1 ? TypeScalarizeVector
  1139. : TypeSplitVector);
  1140. } else {
  1141. TransformToType[i] = NVT;
  1142. ValueTypeActions.setTypeAction(VT, TypeWidenVector);
  1143. }
  1144. break;
  1145. }
  1146. default:
  1147. llvm_unreachable("Unknown vector legalization action!");
  1148. }
  1149. }
  1150. // Determine the 'representative' register class for each value type.
  1151. // An representative register class is the largest (meaning one which is
  1152. // not a sub-register class / subreg register class) legal register class for
  1153. // a group of value types. For example, on i386, i8, i16, and i32
  1154. // representative would be GR32; while on x86_64 it's GR64.
  1155. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
  1156. const TargetRegisterClass* RRC;
  1157. uint8_t Cost;
  1158. std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
  1159. RepRegClassForVT[i] = RRC;
  1160. RepRegClassCostForVT[i] = Cost;
  1161. }
  1162. }
  1163. EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
  1164. EVT VT) const {
  1165. assert(!VT.isVector() && "No default SetCC type for vectors!");
  1166. return getPointerTy(DL).SimpleTy;
  1167. }
  1168. MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
  1169. return MVT::i32; // return the default value
  1170. }
  1171. /// getVectorTypeBreakdown - Vector types are broken down into some number of
  1172. /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
  1173. /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
  1174. /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
  1175. ///
  1176. /// This method returns the number of registers needed, and the VT for each
  1177. /// register. It also returns the VT and quantity of the intermediate values
  1178. /// before they are promoted/expanded.
  1179. unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
  1180. EVT &IntermediateVT,
  1181. unsigned &NumIntermediates,
  1182. MVT &RegisterVT) const {
  1183. unsigned NumElts = VT.getVectorNumElements();
  1184. // If there is a wider vector type with the same element type as this one,
  1185. // or a promoted vector type that has the same number of elements which
  1186. // are wider, then we should convert to that legal vector type.
  1187. // This handles things like <2 x float> -> <4 x float> and
  1188. // <4 x i1> -> <4 x i32>.
  1189. LegalizeTypeAction TA = getTypeAction(Context, VT);
  1190. if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) {
  1191. EVT RegisterEVT = getTypeToTransformTo(Context, VT);
  1192. if (isTypeLegal(RegisterEVT)) {
  1193. IntermediateVT = RegisterEVT;
  1194. RegisterVT = RegisterEVT.getSimpleVT();
  1195. NumIntermediates = 1;
  1196. return 1;
  1197. }
  1198. }
  1199. // Figure out the right, legal destination reg to copy into.
  1200. EVT EltTy = VT.getVectorElementType();
  1201. unsigned NumVectorRegs = 1;
  1202. // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
  1203. // could break down into LHS/RHS like LegalizeDAG does.
  1204. if (!isPowerOf2_32(NumElts)) {
  1205. NumVectorRegs = NumElts;
  1206. NumElts = 1;
  1207. }
  1208. // Divide the input until we get to a supported size. This will always
  1209. // end with a scalar if the target doesn't support vectors.
  1210. while (NumElts > 1 && !isTypeLegal(
  1211. EVT::getVectorVT(Context, EltTy, NumElts))) {
  1212. NumElts >>= 1;
  1213. NumVectorRegs <<= 1;
  1214. }
  1215. NumIntermediates = NumVectorRegs;
  1216. EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
  1217. if (!isTypeLegal(NewVT))
  1218. NewVT = EltTy;
  1219. IntermediateVT = NewVT;
  1220. MVT DestVT = getRegisterType(Context, NewVT);
  1221. RegisterVT = DestVT;
  1222. unsigned NewVTSize = NewVT.getSizeInBits();
  1223. // Convert sizes such as i33 to i64.
  1224. if (!isPowerOf2_32(NewVTSize))
  1225. NewVTSize = NextPowerOf2(NewVTSize);
  1226. if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
  1227. return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
  1228. // Otherwise, promotion or legal types use the same number of registers as
  1229. // the vector decimated to the appropriate level.
  1230. return NumVectorRegs;
  1231. }
  1232. /// Get the EVTs and ArgFlags collections that represent the legalized return
  1233. /// type of the given function. This does not require a DAG or a return value,
  1234. /// and is suitable for use before any DAGs for the function are constructed.
  1235. /// TODO: Move this out of TargetLowering.cpp.
  1236. void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
  1237. AttributeList attr,
  1238. SmallVectorImpl<ISD::OutputArg> &Outs,
  1239. const TargetLowering &TLI, const DataLayout &DL) {
  1240. SmallVector<EVT, 4> ValueVTs;
  1241. ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
  1242. unsigned NumValues = ValueVTs.size();
  1243. if (NumValues == 0) return;
  1244. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  1245. EVT VT = ValueVTs[j];
  1246. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1247. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
  1248. ExtendKind = ISD::SIGN_EXTEND;
  1249. else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
  1250. ExtendKind = ISD::ZERO_EXTEND;
  1251. // FIXME: C calling convention requires the return type to be promoted to
  1252. // at least 32-bit. But this is not necessary for non-C calling
  1253. // conventions. The frontend should mark functions whose return values
  1254. // require promoting with signext or zeroext attributes.
  1255. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
  1256. MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
  1257. if (VT.bitsLT(MinVT))
  1258. VT = MinVT;
  1259. }
  1260. unsigned NumParts =
  1261. TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT);
  1262. MVT PartVT =
  1263. TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT);
  1264. // 'inreg' on function refers to return value
  1265. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1266. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::InReg))
  1267. Flags.setInReg();
  1268. // Propagate extension type if any
  1269. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
  1270. Flags.setSExt();
  1271. else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
  1272. Flags.setZExt();
  1273. for (unsigned i = 0; i < NumParts; ++i)
  1274. Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isFixed=*/true, 0, 0));
  1275. }
  1276. }
  1277. /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
  1278. /// function arguments in the caller parameter area. This is the actual
  1279. /// alignment, not its logarithm.
  1280. unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty,
  1281. const DataLayout &DL) const {
  1282. return DL.getABITypeAlignment(Ty);
  1283. }
  1284. bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
  1285. const DataLayout &DL, EVT VT,
  1286. unsigned AddrSpace,
  1287. unsigned Alignment,
  1288. bool *Fast) const {
  1289. // Check if the specified alignment is sufficient based on the data layout.
  1290. // TODO: While using the data layout works in practice, a better solution
  1291. // would be to implement this check directly (make this a virtual function).
  1292. // For example, the ABI alignment may change based on software platform while
  1293. // this function should only be affected by hardware implementation.
  1294. Type *Ty = VT.getTypeForEVT(Context);
  1295. if (Alignment >= DL.getABITypeAlignment(Ty)) {
  1296. // Assume that an access that meets the ABI-specified alignment is fast.
  1297. if (Fast != nullptr)
  1298. *Fast = true;
  1299. return true;
  1300. }
  1301. // This is a misaligned access.
  1302. return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Fast);
  1303. }
  1304. BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const {
  1305. return BranchProbability(MinPercentageForPredictableBranch, 100);
  1306. }
  1307. //===----------------------------------------------------------------------===//
  1308. // TargetTransformInfo Helpers
  1309. //===----------------------------------------------------------------------===//
  1310. int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
  1311. enum InstructionOpcodes {
  1312. #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
  1313. #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
  1314. #include "llvm/IR/Instruction.def"
  1315. };
  1316. switch (static_cast<InstructionOpcodes>(Opcode)) {
  1317. case Ret: return 0;
  1318. case Br: return 0;
  1319. case Switch: return 0;
  1320. case IndirectBr: return 0;
  1321. case Invoke: return 0;
  1322. case CallBr: return 0;
  1323. case Resume: return 0;
  1324. case Unreachable: return 0;
  1325. case CleanupRet: return 0;
  1326. case CatchRet: return 0;
  1327. case CatchPad: return 0;
  1328. case CatchSwitch: return 0;
  1329. case CleanupPad: return 0;
  1330. case FNeg: return ISD::FNEG;
  1331. case Add: return ISD::ADD;
  1332. case FAdd: return ISD::FADD;
  1333. case Sub: return ISD::SUB;
  1334. case FSub: return ISD::FSUB;
  1335. case Mul: return ISD::MUL;
  1336. case FMul: return ISD::FMUL;
  1337. case UDiv: return ISD::UDIV;
  1338. case SDiv: return ISD::SDIV;
  1339. case FDiv: return ISD::FDIV;
  1340. case URem: return ISD::UREM;
  1341. case SRem: return ISD::SREM;
  1342. case FRem: return ISD::FREM;
  1343. case Shl: return ISD::SHL;
  1344. case LShr: return ISD::SRL;
  1345. case AShr: return ISD::SRA;
  1346. case And: return ISD::AND;
  1347. case Or: return ISD::OR;
  1348. case Xor: return ISD::XOR;
  1349. case Alloca: return 0;
  1350. case Load: return ISD::LOAD;
  1351. case Store: return ISD::STORE;
  1352. case GetElementPtr: return 0;
  1353. case Fence: return 0;
  1354. case AtomicCmpXchg: return 0;
  1355. case AtomicRMW: return 0;
  1356. case Trunc: return ISD::TRUNCATE;
  1357. case ZExt: return ISD::ZERO_EXTEND;
  1358. case SExt: return ISD::SIGN_EXTEND;
  1359. case FPToUI: return ISD::FP_TO_UINT;
  1360. case FPToSI: return ISD::FP_TO_SINT;
  1361. case UIToFP: return ISD::UINT_TO_FP;
  1362. case SIToFP: return ISD::SINT_TO_FP;
  1363. case FPTrunc: return ISD::FP_ROUND;
  1364. case FPExt: return ISD::FP_EXTEND;
  1365. case PtrToInt: return ISD::BITCAST;
  1366. case IntToPtr: return ISD::BITCAST;
  1367. case BitCast: return ISD::BITCAST;
  1368. case AddrSpaceCast: return ISD::ADDRSPACECAST;
  1369. case ICmp: return ISD::SETCC;
  1370. case FCmp: return ISD::SETCC;
  1371. case PHI: return 0;
  1372. case Call: return 0;
  1373. case Select: return ISD::SELECT;
  1374. case UserOp1: return 0;
  1375. case UserOp2: return 0;
  1376. case VAArg: return 0;
  1377. case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
  1378. case InsertElement: return ISD::INSERT_VECTOR_ELT;
  1379. case ShuffleVector: return ISD::VECTOR_SHUFFLE;
  1380. case ExtractValue: return ISD::MERGE_VALUES;
  1381. case InsertValue: return ISD::MERGE_VALUES;
  1382. case LandingPad: return 0;
  1383. }
  1384. llvm_unreachable("Unknown instruction type encountered!");
  1385. }
  1386. std::pair<int, MVT>
  1387. TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL,
  1388. Type *Ty) const {
  1389. LLVMContext &C = Ty->getContext();
  1390. EVT MTy = getValueType(DL, Ty);
  1391. int Cost = 1;
  1392. // We keep legalizing the type until we find a legal kind. We assume that
  1393. // the only operation that costs anything is the split. After splitting
  1394. // we need to handle two types.
  1395. while (true) {
  1396. LegalizeKind LK = getTypeConversion(C, MTy);
  1397. if (LK.first == TypeLegal)
  1398. return std::make_pair(Cost, MTy.getSimpleVT());
  1399. if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
  1400. Cost *= 2;
  1401. // Do not loop with f128 type.
  1402. if (MTy == LK.second)
  1403. return std::make_pair(Cost, MTy.getSimpleVT());
  1404. // Keep legalizing the type.
  1405. MTy = LK.second;
  1406. }
  1407. }
  1408. Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
  1409. bool UseTLS) const {
  1410. // compiler-rt provides a variable with a magic name. Targets that do not
  1411. // link with compiler-rt may also provide such a variable.
  1412. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  1413. const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
  1414. auto UnsafeStackPtr =
  1415. dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
  1416. Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
  1417. if (!UnsafeStackPtr) {
  1418. auto TLSModel = UseTLS ?
  1419. GlobalValue::InitialExecTLSModel :
  1420. GlobalValue::NotThreadLocal;
  1421. // The global variable is not defined yet, define it ourselves.
  1422. // We use the initial-exec TLS model because we do not support the
  1423. // variable living anywhere other than in the main executable.
  1424. UnsafeStackPtr = new GlobalVariable(
  1425. *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
  1426. UnsafeStackPtrVar, nullptr, TLSModel);
  1427. } else {
  1428. // The variable exists, check its type and attributes.
  1429. if (UnsafeStackPtr->getValueType() != StackPtrTy)
  1430. report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
  1431. if (UseTLS != UnsafeStackPtr->isThreadLocal())
  1432. report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
  1433. (UseTLS ? "" : "not ") + "be thread-local");
  1434. }
  1435. return UnsafeStackPtr;
  1436. }
  1437. Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
  1438. if (!TM.getTargetTriple().isAndroid())
  1439. return getDefaultSafeStackPointerLocation(IRB, true);
  1440. // Android provides a libc function to retrieve the address of the current
  1441. // thread's unsafe stack pointer.
  1442. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  1443. Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
  1444. FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address",
  1445. StackPtrTy->getPointerTo(0));
  1446. return IRB.CreateCall(Fn);
  1447. }
  1448. //===----------------------------------------------------------------------===//
  1449. // Loop Strength Reduction hooks
  1450. //===----------------------------------------------------------------------===//
  1451. /// isLegalAddressingMode - Return true if the addressing mode represented
  1452. /// by AM is legal for this target, for a load/store of the specified type.
  1453. bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
  1454. const AddrMode &AM, Type *Ty,
  1455. unsigned AS, Instruction *I) const {
  1456. // The default implementation of this implements a conservative RISCy, r+r and
  1457. // r+i addr mode.
  1458. // Allows a sign-extended 16-bit immediate field.
  1459. if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
  1460. return false;
  1461. // No global is ever allowed as a base.
  1462. if (AM.BaseGV)
  1463. return false;
  1464. // Only support r+r,
  1465. switch (AM.Scale) {
  1466. case 0: // "r+i" or just "i", depending on HasBaseReg.
  1467. break;
  1468. case 1:
  1469. if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
  1470. return false;
  1471. // Otherwise we have r+r or r+i.
  1472. break;
  1473. case 2:
  1474. if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
  1475. return false;
  1476. // Allow 2*r as r+r.
  1477. break;
  1478. default: // Don't allow n * r
  1479. return false;
  1480. }
  1481. return true;
  1482. }
  1483. //===----------------------------------------------------------------------===//
  1484. // Stack Protector
  1485. //===----------------------------------------------------------------------===//
  1486. // For OpenBSD return its special guard variable. Otherwise return nullptr,
  1487. // so that SelectionDAG handle SSP.
  1488. Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const {
  1489. if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
  1490. Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
  1491. PointerType *PtrTy = Type::getInt8PtrTy(M.getContext());
  1492. return M.getOrInsertGlobal("__guard_local", PtrTy);
  1493. }
  1494. return nullptr;
  1495. }
  1496. // Currently only support "standard" __stack_chk_guard.
  1497. // TODO: add LOAD_STACK_GUARD support.
  1498. void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
  1499. if (!M.getNamedValue("__stack_chk_guard"))
  1500. new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false,
  1501. GlobalVariable::ExternalLinkage,
  1502. nullptr, "__stack_chk_guard");
  1503. }
  1504. // Currently only support "standard" __stack_chk_guard.
  1505. // TODO: add LOAD_STACK_GUARD support.
  1506. Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
  1507. return M.getNamedValue("__stack_chk_guard");
  1508. }
  1509. Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
  1510. return nullptr;
  1511. }
  1512. unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
  1513. return MinimumJumpTableEntries;
  1514. }
  1515. void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
  1516. MinimumJumpTableEntries = Val;
  1517. }
  1518. unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
  1519. return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
  1520. }
  1521. unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
  1522. return MaximumJumpTableSize;
  1523. }
  1524. void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
  1525. MaximumJumpTableSize = Val;
  1526. }
  1527. //===----------------------------------------------------------------------===//
  1528. // Reciprocal Estimates
  1529. //===----------------------------------------------------------------------===//
  1530. /// Get the reciprocal estimate attribute string for a function that will
  1531. /// override the target defaults.
  1532. static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
  1533. const Function &F = MF.getFunction();
  1534. return F.getFnAttribute("reciprocal-estimates").getValueAsString();
  1535. }
  1536. /// Construct a string for the given reciprocal operation of the given type.
  1537. /// This string should match the corresponding option to the front-end's
  1538. /// "-mrecip" flag assuming those strings have been passed through in an
  1539. /// attribute string. For example, "vec-divf" for a division of a vXf32.
  1540. static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
  1541. std::string Name = VT.isVector() ? "vec-" : "";
  1542. Name += IsSqrt ? "sqrt" : "div";
  1543. // TODO: Handle "half" or other float types?
  1544. if (VT.getScalarType() == MVT::f64) {
  1545. Name += "d";
  1546. } else {
  1547. assert(VT.getScalarType() == MVT::f32 &&
  1548. "Unexpected FP type for reciprocal estimate");
  1549. Name += "f";
  1550. }
  1551. return Name;
  1552. }
  1553. /// Return the character position and value (a single numeric character) of a
  1554. /// customized refinement operation in the input string if it exists. Return
  1555. /// false if there is no customized refinement step count.
  1556. static bool parseRefinementStep(StringRef In, size_t &Position,
  1557. uint8_t &Value) {
  1558. const char RefStepToken = ':';
  1559. Position = In.find(RefStepToken);
  1560. if (Position == StringRef::npos)
  1561. return false;
  1562. StringRef RefStepString = In.substr(Position + 1);
  1563. // Allow exactly one numeric character for the additional refinement
  1564. // step parameter.
  1565. if (RefStepString.size() == 1) {
  1566. char RefStepChar = RefStepString[0];
  1567. if (RefStepChar >= '0' && RefStepChar <= '9') {
  1568. Value = RefStepChar - '0';
  1569. return true;
  1570. }
  1571. }
  1572. report_fatal_error("Invalid refinement step for -recip.");
  1573. }
  1574. /// For the input attribute string, return one of the ReciprocalEstimate enum
  1575. /// status values (enabled, disabled, or not specified) for this operation on
  1576. /// the specified data type.
  1577. static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
  1578. if (Override.empty())
  1579. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1580. SmallVector<StringRef, 4> OverrideVector;
  1581. Override.split(OverrideVector, ',');
  1582. unsigned NumArgs = OverrideVector.size();
  1583. // Check if "all", "none", or "default" was specified.
  1584. if (NumArgs == 1) {
  1585. // Look for an optional setting of the number of refinement steps needed
  1586. // for this type of reciprocal operation.
  1587. size_t RefPos;
  1588. uint8_t RefSteps;
  1589. if (parseRefinementStep(Override, RefPos, RefSteps)) {
  1590. // Split the string for further processing.
  1591. Override = Override.substr(0, RefPos);
  1592. }
  1593. // All reciprocal types are enabled.
  1594. if (Override == "all")
  1595. return TargetLoweringBase::ReciprocalEstimate::Enabled;
  1596. // All reciprocal types are disabled.
  1597. if (Override == "none")
  1598. return TargetLoweringBase::ReciprocalEstimate::Disabled;
  1599. // Target defaults for enablement are used.
  1600. if (Override == "default")
  1601. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1602. }
  1603. // The attribute string may omit the size suffix ('f'/'d').
  1604. std::string VTName = getReciprocalOpName(IsSqrt, VT);
  1605. std::string VTNameNoSize = VTName;
  1606. VTNameNoSize.pop_back();
  1607. static const char DisabledPrefix = '!';
  1608. for (StringRef RecipType : OverrideVector) {
  1609. size_t RefPos;
  1610. uint8_t RefSteps;
  1611. if (parseRefinementStep(RecipType, RefPos, RefSteps))
  1612. RecipType = RecipType.substr(0, RefPos);
  1613. // Ignore the disablement token for string matching.
  1614. bool IsDisabled = RecipType[0] == DisabledPrefix;
  1615. if (IsDisabled)
  1616. RecipType = RecipType.substr(1);
  1617. if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
  1618. return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
  1619. : TargetLoweringBase::ReciprocalEstimate::Enabled;
  1620. }
  1621. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1622. }
  1623. /// For the input attribute string, return the customized refinement step count
  1624. /// for this operation on the specified data type. If the step count does not
  1625. /// exist, return the ReciprocalEstimate enum value for unspecified.
  1626. static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
  1627. if (Override.empty())
  1628. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1629. SmallVector<StringRef, 4> OverrideVector;
  1630. Override.split(OverrideVector, ',');
  1631. unsigned NumArgs = OverrideVector.size();
  1632. // Check if "all", "default", or "none" was specified.
  1633. if (NumArgs == 1) {
  1634. // Look for an optional setting of the number of refinement steps needed
  1635. // for this type of reciprocal operation.
  1636. size_t RefPos;
  1637. uint8_t RefSteps;
  1638. if (!parseRefinementStep(Override, RefPos, RefSteps))
  1639. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1640. // Split the string for further processing.
  1641. Override = Override.substr(0, RefPos);
  1642. assert(Override != "none" &&
  1643. "Disabled reciprocals, but specifed refinement steps?");
  1644. // If this is a general override, return the specified number of steps.
  1645. if (Override == "all" || Override == "default")
  1646. return RefSteps;
  1647. }
  1648. // The attribute string may omit the size suffix ('f'/'d').
  1649. std::string VTName = getReciprocalOpName(IsSqrt, VT);
  1650. std::string VTNameNoSize = VTName;
  1651. VTNameNoSize.pop_back();
  1652. for (StringRef RecipType : OverrideVector) {
  1653. size_t RefPos;
  1654. uint8_t RefSteps;
  1655. if (!parseRefinementStep(RecipType, RefPos, RefSteps))
  1656. continue;
  1657. RecipType = RecipType.substr(0, RefPos);
  1658. if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
  1659. return RefSteps;
  1660. }
  1661. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1662. }
  1663. int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
  1664. MachineFunction &MF) const {
  1665. return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
  1666. }
  1667. int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
  1668. MachineFunction &MF) const {
  1669. return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
  1670. }
  1671. int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
  1672. MachineFunction &MF) const {
  1673. return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
  1674. }
  1675. int TargetLoweringBase::getDivRefinementSteps(EVT VT,
  1676. MachineFunction &MF) const {
  1677. return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
  1678. }
  1679. void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
  1680. MF.getRegInfo().freezeReservedRegs(MF);
  1681. }