TargetLoweringBase.cpp 70 KB

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