TargetLoweringBase.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  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::SMULFIXSAT, VT, Expand);
  586. setOperationAction(ISD::UMULFIX, 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. // Vector reduction default to expand.
  620. setOperationAction(ISD::VECREDUCE_FADD, VT, Expand);
  621. setOperationAction(ISD::VECREDUCE_FMUL, VT, Expand);
  622. setOperationAction(ISD::VECREDUCE_ADD, VT, Expand);
  623. setOperationAction(ISD::VECREDUCE_MUL, VT, Expand);
  624. setOperationAction(ISD::VECREDUCE_AND, VT, Expand);
  625. setOperationAction(ISD::VECREDUCE_OR, VT, Expand);
  626. setOperationAction(ISD::VECREDUCE_XOR, VT, Expand);
  627. setOperationAction(ISD::VECREDUCE_SMAX, VT, Expand);
  628. setOperationAction(ISD::VECREDUCE_SMIN, VT, Expand);
  629. setOperationAction(ISD::VECREDUCE_UMAX, VT, Expand);
  630. setOperationAction(ISD::VECREDUCE_UMIN, VT, Expand);
  631. setOperationAction(ISD::VECREDUCE_FMAX, VT, Expand);
  632. setOperationAction(ISD::VECREDUCE_FMIN, VT, Expand);
  633. }
  634. // Most targets ignore the @llvm.prefetch intrinsic.
  635. setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
  636. // Most targets also ignore the @llvm.readcyclecounter intrinsic.
  637. setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
  638. // ConstantFP nodes default to expand. Targets can either change this to
  639. // Legal, in which case all fp constants are legal, or use isFPImmLegal()
  640. // to optimize expansions for certain constants.
  641. setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
  642. setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
  643. setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
  644. setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
  645. setOperationAction(ISD::ConstantFP, MVT::f128, Expand);
  646. // These library functions default to expand.
  647. for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
  648. setOperationAction(ISD::FCBRT, VT, Expand);
  649. setOperationAction(ISD::FLOG , VT, Expand);
  650. setOperationAction(ISD::FLOG2, VT, Expand);
  651. setOperationAction(ISD::FLOG10, VT, Expand);
  652. setOperationAction(ISD::FEXP , VT, Expand);
  653. setOperationAction(ISD::FEXP2, VT, Expand);
  654. setOperationAction(ISD::FFLOOR, VT, Expand);
  655. setOperationAction(ISD::FNEARBYINT, VT, Expand);
  656. setOperationAction(ISD::FCEIL, VT, Expand);
  657. setOperationAction(ISD::FRINT, VT, Expand);
  658. setOperationAction(ISD::FTRUNC, VT, Expand);
  659. setOperationAction(ISD::FROUND, VT, Expand);
  660. setOperationAction(ISD::LROUND, VT, Expand);
  661. setOperationAction(ISD::LLROUND, VT, Expand);
  662. setOperationAction(ISD::LRINT, VT, Expand);
  663. setOperationAction(ISD::LLRINT, VT, Expand);
  664. }
  665. // Default ISD::TRAP to expand (which turns it into abort).
  666. setOperationAction(ISD::TRAP, MVT::Other, Expand);
  667. // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
  668. // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
  669. setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
  670. }
  671. MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
  672. EVT) const {
  673. return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
  674. }
  675. EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
  676. bool LegalTypes) const {
  677. assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
  678. if (LHSTy.isVector())
  679. return LHSTy;
  680. return LegalTypes ? getScalarShiftAmountTy(DL, LHSTy)
  681. : getPointerTy(DL);
  682. }
  683. bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
  684. assert(isTypeLegal(VT));
  685. switch (Op) {
  686. default:
  687. return false;
  688. case ISD::SDIV:
  689. case ISD::UDIV:
  690. case ISD::SREM:
  691. case ISD::UREM:
  692. return true;
  693. }
  694. }
  695. void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
  696. // If the command-line option was specified, ignore this request.
  697. if (!JumpIsExpensiveOverride.getNumOccurrences())
  698. JumpIsExpensive = isExpensive;
  699. }
  700. TargetLoweringBase::LegalizeKind
  701. TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
  702. // If this is a simple type, use the ComputeRegisterProp mechanism.
  703. if (VT.isSimple()) {
  704. MVT SVT = VT.getSimpleVT();
  705. assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
  706. MVT NVT = TransformToType[SVT.SimpleTy];
  707. LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
  708. assert((LA == TypeLegal || LA == TypeSoftenFloat ||
  709. ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger) &&
  710. "Promote may not follow Expand or Promote");
  711. if (LA == TypeSplitVector)
  712. return LegalizeKind(LA,
  713. EVT::getVectorVT(Context, SVT.getVectorElementType(),
  714. SVT.getVectorNumElements() / 2));
  715. if (LA == TypeScalarizeVector)
  716. return LegalizeKind(LA, SVT.getVectorElementType());
  717. return LegalizeKind(LA, NVT);
  718. }
  719. // Handle Extended Scalar Types.
  720. if (!VT.isVector()) {
  721. assert(VT.isInteger() && "Float types must be simple");
  722. unsigned BitSize = VT.getSizeInBits();
  723. // First promote to a power-of-two size, then expand if necessary.
  724. if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
  725. EVT NVT = VT.getRoundIntegerType(Context);
  726. assert(NVT != VT && "Unable to round integer VT");
  727. LegalizeKind NextStep = getTypeConversion(Context, NVT);
  728. // Avoid multi-step promotion.
  729. if (NextStep.first == TypePromoteInteger)
  730. return NextStep;
  731. // Return rounded integer type.
  732. return LegalizeKind(TypePromoteInteger, NVT);
  733. }
  734. return LegalizeKind(TypeExpandInteger,
  735. EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
  736. }
  737. // Handle vector types.
  738. unsigned NumElts = VT.getVectorNumElements();
  739. EVT EltVT = VT.getVectorElementType();
  740. // Vectors with only one element are always scalarized.
  741. if (NumElts == 1)
  742. return LegalizeKind(TypeScalarizeVector, EltVT);
  743. // Try to widen vector elements until the element type is a power of two and
  744. // promote it to a legal type later on, for example:
  745. // <3 x i8> -> <4 x i8> -> <4 x i32>
  746. if (EltVT.isInteger()) {
  747. // Vectors with a number of elements that is not a power of two are always
  748. // widened, for example <3 x i8> -> <4 x i8>.
  749. if (!VT.isPow2VectorType()) {
  750. NumElts = (unsigned)NextPowerOf2(NumElts);
  751. EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
  752. return LegalizeKind(TypeWidenVector, NVT);
  753. }
  754. // Examine the element type.
  755. LegalizeKind LK = getTypeConversion(Context, EltVT);
  756. // If type is to be expanded, split the vector.
  757. // <4 x i140> -> <2 x i140>
  758. if (LK.first == TypeExpandInteger)
  759. return LegalizeKind(TypeSplitVector,
  760. EVT::getVectorVT(Context, EltVT, NumElts / 2));
  761. // Promote the integer element types until a legal vector type is found
  762. // or until the element integer type is too big. If a legal type was not
  763. // found, fallback to the usual mechanism of widening/splitting the
  764. // vector.
  765. EVT OldEltVT = EltVT;
  766. while (true) {
  767. // Increase the bitwidth of the element to the next pow-of-two
  768. // (which is greater than 8 bits).
  769. EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
  770. .getRoundIntegerType(Context);
  771. // Stop trying when getting a non-simple element type.
  772. // Note that vector elements may be greater than legal vector element
  773. // types. Example: X86 XMM registers hold 64bit element on 32bit
  774. // systems.
  775. if (!EltVT.isSimple())
  776. break;
  777. // Build a new vector type and check if it is legal.
  778. MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
  779. // Found a legal promoted vector type.
  780. if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
  781. return LegalizeKind(TypePromoteInteger,
  782. EVT::getVectorVT(Context, EltVT, NumElts));
  783. }
  784. // Reset the type to the unexpanded type if we did not find a legal vector
  785. // type with a promoted vector element type.
  786. EltVT = OldEltVT;
  787. }
  788. // Try to widen the vector until a legal type is found.
  789. // If there is no wider legal type, split the vector.
  790. while (true) {
  791. // Round up to the next power of 2.
  792. NumElts = (unsigned)NextPowerOf2(NumElts);
  793. // If there is no simple vector type with this many elements then there
  794. // cannot be a larger legal vector type. Note that this assumes that
  795. // there are no skipped intermediate vector types in the simple types.
  796. if (!EltVT.isSimple())
  797. break;
  798. MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
  799. if (LargerVector == MVT())
  800. break;
  801. // If this type is legal then widen the vector.
  802. if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
  803. return LegalizeKind(TypeWidenVector, LargerVector);
  804. }
  805. // Widen odd vectors to next power of two.
  806. if (!VT.isPow2VectorType()) {
  807. EVT NVT = VT.getPow2VectorType(Context);
  808. return LegalizeKind(TypeWidenVector, NVT);
  809. }
  810. // Vectors with illegal element types are expanded.
  811. EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
  812. return LegalizeKind(TypeSplitVector, NVT);
  813. }
  814. static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
  815. unsigned &NumIntermediates,
  816. MVT &RegisterVT,
  817. TargetLoweringBase *TLI) {
  818. // Figure out the right, legal destination reg to copy into.
  819. unsigned NumElts = VT.getVectorNumElements();
  820. MVT EltTy = VT.getVectorElementType();
  821. unsigned NumVectorRegs = 1;
  822. // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
  823. // could break down into LHS/RHS like LegalizeDAG does.
  824. if (!isPowerOf2_32(NumElts)) {
  825. NumVectorRegs = NumElts;
  826. NumElts = 1;
  827. }
  828. // Divide the input until we get to a supported size. This will always
  829. // end with a scalar if the target doesn't support vectors.
  830. while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
  831. NumElts >>= 1;
  832. NumVectorRegs <<= 1;
  833. }
  834. NumIntermediates = NumVectorRegs;
  835. MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
  836. if (!TLI->isTypeLegal(NewVT))
  837. NewVT = EltTy;
  838. IntermediateVT = NewVT;
  839. unsigned NewVTSize = NewVT.getSizeInBits();
  840. // Convert sizes such as i33 to i64.
  841. if (!isPowerOf2_32(NewVTSize))
  842. NewVTSize = NextPowerOf2(NewVTSize);
  843. MVT DestVT = TLI->getRegisterType(NewVT);
  844. RegisterVT = DestVT;
  845. if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
  846. return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
  847. // Otherwise, promotion or legal types use the same number of registers as
  848. // the vector decimated to the appropriate level.
  849. return NumVectorRegs;
  850. }
  851. /// isLegalRC - Return true if the value types that can be represented by the
  852. /// specified register class are all legal.
  853. bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
  854. const TargetRegisterClass &RC) const {
  855. for (auto I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
  856. if (isTypeLegal(*I))
  857. return true;
  858. return false;
  859. }
  860. /// Replace/modify any TargetFrameIndex operands with a targte-dependent
  861. /// sequence of memory operands that is recognized by PrologEpilogInserter.
  862. MachineBasicBlock *
  863. TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
  864. MachineBasicBlock *MBB) const {
  865. MachineInstr *MI = &InitialMI;
  866. MachineFunction &MF = *MI->getMF();
  867. MachineFrameInfo &MFI = MF.getFrameInfo();
  868. // We're handling multiple types of operands here:
  869. // PATCHPOINT MetaArgs - live-in, read only, direct
  870. // STATEPOINT Deopt Spill - live-through, read only, indirect
  871. // STATEPOINT Deopt Alloca - live-through, read only, direct
  872. // (We're currently conservative and mark the deopt slots read/write in
  873. // practice.)
  874. // STATEPOINT GC Spill - live-through, read/write, indirect
  875. // STATEPOINT GC Alloca - live-through, read/write, direct
  876. // The live-in vs live-through is handled already (the live through ones are
  877. // all stack slots), but we need to handle the different type of stackmap
  878. // operands and memory effects here.
  879. // MI changes inside this loop as we grow operands.
  880. for(unsigned OperIdx = 0; OperIdx != MI->getNumOperands(); ++OperIdx) {
  881. MachineOperand &MO = MI->getOperand(OperIdx);
  882. if (!MO.isFI())
  883. continue;
  884. // foldMemoryOperand builds a new MI after replacing a single FI operand
  885. // with the canonical set of five x86 addressing-mode operands.
  886. int FI = MO.getIndex();
  887. MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
  888. // Copy operands before the frame-index.
  889. for (unsigned i = 0; i < OperIdx; ++i)
  890. MIB.add(MI->getOperand(i));
  891. // Add frame index operands recognized by stackmaps.cpp
  892. if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
  893. // indirect-mem-ref tag, size, #FI, offset.
  894. // Used for spills inserted by StatepointLowering. This codepath is not
  895. // used for patchpoints/stackmaps at all, for these spilling is done via
  896. // foldMemoryOperand callback only.
  897. assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
  898. MIB.addImm(StackMaps::IndirectMemRefOp);
  899. MIB.addImm(MFI.getObjectSize(FI));
  900. MIB.add(MI->getOperand(OperIdx));
  901. MIB.addImm(0);
  902. } else {
  903. // direct-mem-ref tag, #FI, offset.
  904. // Used by patchpoint, and direct alloca arguments to statepoints
  905. MIB.addImm(StackMaps::DirectMemRefOp);
  906. MIB.add(MI->getOperand(OperIdx));
  907. MIB.addImm(0);
  908. }
  909. // Copy the operands after the frame index.
  910. for (unsigned i = OperIdx + 1; i != MI->getNumOperands(); ++i)
  911. MIB.add(MI->getOperand(i));
  912. // Inherit previous memory operands.
  913. MIB.cloneMemRefs(*MI);
  914. assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
  915. // Add a new memory operand for this FI.
  916. assert(MFI.getObjectOffset(FI) != -1);
  917. // Note: STATEPOINT MMOs are added during SelectionDAG. STACKMAP, and
  918. // PATCHPOINT should be updated to do the same. (TODO)
  919. if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
  920. auto Flags = MachineMemOperand::MOLoad;
  921. MachineMemOperand *MMO = MF.getMachineMemOperand(
  922. MachinePointerInfo::getFixedStack(MF, FI), Flags,
  923. MF.getDataLayout().getPointerSize(), MFI.getObjectAlignment(FI));
  924. MIB->addMemOperand(MF, MMO);
  925. }
  926. // Replace the instruction and update the operand index.
  927. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  928. OperIdx += (MIB->getNumOperands() - MI->getNumOperands()) - 1;
  929. MI->eraseFromParent();
  930. MI = MIB;
  931. }
  932. return MBB;
  933. }
  934. MachineBasicBlock *
  935. TargetLoweringBase::emitXRayCustomEvent(MachineInstr &MI,
  936. MachineBasicBlock *MBB) const {
  937. assert(MI.getOpcode() == TargetOpcode::PATCHABLE_EVENT_CALL &&
  938. "Called emitXRayCustomEvent on the wrong MI!");
  939. auto &MF = *MI.getMF();
  940. auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
  941. for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
  942. MIB.add(MI.getOperand(OpIdx));
  943. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  944. MI.eraseFromParent();
  945. return MBB;
  946. }
  947. MachineBasicBlock *
  948. TargetLoweringBase::emitXRayTypedEvent(MachineInstr &MI,
  949. MachineBasicBlock *MBB) const {
  950. assert(MI.getOpcode() == TargetOpcode::PATCHABLE_TYPED_EVENT_CALL &&
  951. "Called emitXRayTypedEvent on the wrong MI!");
  952. auto &MF = *MI.getMF();
  953. auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
  954. for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
  955. MIB.add(MI.getOperand(OpIdx));
  956. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  957. MI.eraseFromParent();
  958. return MBB;
  959. }
  960. /// findRepresentativeClass - Return the largest legal super-reg register class
  961. /// of the register class for the specified type and its associated "cost".
  962. // This function is in TargetLowering because it uses RegClassForVT which would
  963. // need to be moved to TargetRegisterInfo and would necessitate moving
  964. // isTypeLegal over as well - a massive change that would just require
  965. // TargetLowering having a TargetRegisterInfo class member that it would use.
  966. std::pair<const TargetRegisterClass *, uint8_t>
  967. TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
  968. MVT VT) const {
  969. const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
  970. if (!RC)
  971. return std::make_pair(RC, 0);
  972. // Compute the set of all super-register classes.
  973. BitVector SuperRegRC(TRI->getNumRegClasses());
  974. for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
  975. SuperRegRC.setBitsInMask(RCI.getMask());
  976. // Find the first legal register class with the largest spill size.
  977. const TargetRegisterClass *BestRC = RC;
  978. for (unsigned i : SuperRegRC.set_bits()) {
  979. const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
  980. // We want the largest possible spill size.
  981. if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
  982. continue;
  983. if (!isLegalRC(*TRI, *SuperRC))
  984. continue;
  985. BestRC = SuperRC;
  986. }
  987. return std::make_pair(BestRC, 1);
  988. }
  989. /// computeRegisterProperties - Once all of the register classes are added,
  990. /// this allows us to compute derived properties we expose.
  991. void TargetLoweringBase::computeRegisterProperties(
  992. const TargetRegisterInfo *TRI) {
  993. static_assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE,
  994. "Too many value types for ValueTypeActions to hold!");
  995. // Everything defaults to needing one register.
  996. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
  997. NumRegistersForVT[i] = 1;
  998. RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
  999. }
  1000. // ...except isVoid, which doesn't need any registers.
  1001. NumRegistersForVT[MVT::isVoid] = 0;
  1002. // Find the largest integer register class.
  1003. unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
  1004. for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
  1005. assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
  1006. // Every integer value type larger than this largest register takes twice as
  1007. // many registers to represent as the previous ValueType.
  1008. for (unsigned ExpandedReg = LargestIntReg + 1;
  1009. ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
  1010. NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
  1011. RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
  1012. TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
  1013. ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
  1014. TypeExpandInteger);
  1015. }
  1016. // Inspect all of the ValueType's smaller than the largest integer
  1017. // register to see which ones need promotion.
  1018. unsigned LegalIntReg = LargestIntReg;
  1019. for (unsigned IntReg = LargestIntReg - 1;
  1020. IntReg >= (unsigned)MVT::i1; --IntReg) {
  1021. MVT IVT = (MVT::SimpleValueType)IntReg;
  1022. if (isTypeLegal(IVT)) {
  1023. LegalIntReg = IntReg;
  1024. } else {
  1025. RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
  1026. (MVT::SimpleValueType)LegalIntReg;
  1027. ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
  1028. }
  1029. }
  1030. // ppcf128 type is really two f64's.
  1031. if (!isTypeLegal(MVT::ppcf128)) {
  1032. if (isTypeLegal(MVT::f64)) {
  1033. NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
  1034. RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
  1035. TransformToType[MVT::ppcf128] = MVT::f64;
  1036. ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
  1037. } else {
  1038. NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
  1039. RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
  1040. TransformToType[MVT::ppcf128] = MVT::i128;
  1041. ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
  1042. }
  1043. }
  1044. // Decide how to handle f128. If the target does not have native f128 support,
  1045. // expand it to i128 and we will be generating soft float library calls.
  1046. if (!isTypeLegal(MVT::f128)) {
  1047. NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
  1048. RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
  1049. TransformToType[MVT::f128] = MVT::i128;
  1050. ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
  1051. }
  1052. // Decide how to handle f64. If the target does not have native f64 support,
  1053. // expand it to i64 and we will be generating soft float library calls.
  1054. if (!isTypeLegal(MVT::f64)) {
  1055. NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
  1056. RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
  1057. TransformToType[MVT::f64] = MVT::i64;
  1058. ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
  1059. }
  1060. // Decide how to handle f32. If the target does not have native f32 support,
  1061. // expand it to i32 and we will be generating soft float library calls.
  1062. if (!isTypeLegal(MVT::f32)) {
  1063. NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
  1064. RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
  1065. TransformToType[MVT::f32] = MVT::i32;
  1066. ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
  1067. }
  1068. // Decide how to handle f16. If the target does not have native f16 support,
  1069. // promote it to f32, because there are no f16 library calls (except for
  1070. // conversions).
  1071. if (!isTypeLegal(MVT::f16)) {
  1072. NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
  1073. RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
  1074. TransformToType[MVT::f16] = MVT::f32;
  1075. ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
  1076. }
  1077. // Loop over all of the vector value types to see which need transformations.
  1078. for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
  1079. i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
  1080. MVT VT = (MVT::SimpleValueType) i;
  1081. if (isTypeLegal(VT))
  1082. continue;
  1083. MVT EltVT = VT.getVectorElementType();
  1084. unsigned NElts = VT.getVectorNumElements();
  1085. bool IsLegalWiderType = false;
  1086. LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
  1087. switch (PreferredAction) {
  1088. case TypePromoteInteger:
  1089. // Try to promote the elements of integer vectors. If no legal
  1090. // promotion was found, fall through to the widen-vector method.
  1091. for (unsigned nVT = i + 1; nVT <= MVT::LAST_INTEGER_VECTOR_VALUETYPE; ++nVT) {
  1092. MVT SVT = (MVT::SimpleValueType) nVT;
  1093. // Promote vectors of integers to vectors with the same number
  1094. // of elements, with a wider element type.
  1095. if (SVT.getScalarSizeInBits() > EltVT.getSizeInBits() &&
  1096. SVT.getVectorNumElements() == NElts && isTypeLegal(SVT)) {
  1097. TransformToType[i] = SVT;
  1098. RegisterTypeForVT[i] = SVT;
  1099. NumRegistersForVT[i] = 1;
  1100. ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
  1101. IsLegalWiderType = true;
  1102. break;
  1103. }
  1104. }
  1105. if (IsLegalWiderType)
  1106. break;
  1107. LLVM_FALLTHROUGH;
  1108. case TypeWidenVector:
  1109. // Try to widen the vector.
  1110. for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
  1111. MVT SVT = (MVT::SimpleValueType) nVT;
  1112. if (SVT.getVectorElementType() == EltVT
  1113. && SVT.getVectorNumElements() > NElts && isTypeLegal(SVT)) {
  1114. TransformToType[i] = SVT;
  1115. RegisterTypeForVT[i] = SVT;
  1116. NumRegistersForVT[i] = 1;
  1117. ValueTypeActions.setTypeAction(VT, TypeWidenVector);
  1118. IsLegalWiderType = true;
  1119. break;
  1120. }
  1121. }
  1122. if (IsLegalWiderType)
  1123. break;
  1124. LLVM_FALLTHROUGH;
  1125. case TypeSplitVector:
  1126. case TypeScalarizeVector: {
  1127. MVT IntermediateVT;
  1128. MVT RegisterVT;
  1129. unsigned NumIntermediates;
  1130. NumRegistersForVT[i] = getVectorTypeBreakdownMVT(VT, IntermediateVT,
  1131. NumIntermediates, RegisterVT, this);
  1132. RegisterTypeForVT[i] = RegisterVT;
  1133. MVT NVT = VT.getPow2VectorType();
  1134. if (NVT == VT) {
  1135. // Type is already a power of 2. The default action is to split.
  1136. TransformToType[i] = MVT::Other;
  1137. if (PreferredAction == TypeScalarizeVector)
  1138. ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
  1139. else if (PreferredAction == TypeSplitVector)
  1140. ValueTypeActions.setTypeAction(VT, TypeSplitVector);
  1141. else
  1142. // Set type action according to the number of elements.
  1143. ValueTypeActions.setTypeAction(VT, NElts == 1 ? TypeScalarizeVector
  1144. : TypeSplitVector);
  1145. } else {
  1146. TransformToType[i] = NVT;
  1147. ValueTypeActions.setTypeAction(VT, TypeWidenVector);
  1148. }
  1149. break;
  1150. }
  1151. default:
  1152. llvm_unreachable("Unknown vector legalization action!");
  1153. }
  1154. }
  1155. // Determine the 'representative' register class for each value type.
  1156. // An representative register class is the largest (meaning one which is
  1157. // not a sub-register class / subreg register class) legal register class for
  1158. // a group of value types. For example, on i386, i8, i16, and i32
  1159. // representative would be GR32; while on x86_64 it's GR64.
  1160. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
  1161. const TargetRegisterClass* RRC;
  1162. uint8_t Cost;
  1163. std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
  1164. RepRegClassForVT[i] = RRC;
  1165. RepRegClassCostForVT[i] = Cost;
  1166. }
  1167. }
  1168. EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
  1169. EVT VT) const {
  1170. assert(!VT.isVector() && "No default SetCC type for vectors!");
  1171. return getPointerTy(DL).SimpleTy;
  1172. }
  1173. MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
  1174. return MVT::i32; // return the default value
  1175. }
  1176. /// getVectorTypeBreakdown - Vector types are broken down into some number of
  1177. /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
  1178. /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
  1179. /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
  1180. ///
  1181. /// This method returns the number of registers needed, and the VT for each
  1182. /// register. It also returns the VT and quantity of the intermediate values
  1183. /// before they are promoted/expanded.
  1184. unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
  1185. EVT &IntermediateVT,
  1186. unsigned &NumIntermediates,
  1187. MVT &RegisterVT) const {
  1188. unsigned NumElts = VT.getVectorNumElements();
  1189. // If there is a wider vector type with the same element type as this one,
  1190. // or a promoted vector type that has the same number of elements which
  1191. // are wider, then we should convert to that legal vector type.
  1192. // This handles things like <2 x float> -> <4 x float> and
  1193. // <4 x i1> -> <4 x i32>.
  1194. LegalizeTypeAction TA = getTypeAction(Context, VT);
  1195. if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) {
  1196. EVT RegisterEVT = getTypeToTransformTo(Context, VT);
  1197. if (isTypeLegal(RegisterEVT)) {
  1198. IntermediateVT = RegisterEVT;
  1199. RegisterVT = RegisterEVT.getSimpleVT();
  1200. NumIntermediates = 1;
  1201. return 1;
  1202. }
  1203. }
  1204. // Figure out the right, legal destination reg to copy into.
  1205. EVT EltTy = VT.getVectorElementType();
  1206. unsigned NumVectorRegs = 1;
  1207. // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
  1208. // could break down into LHS/RHS like LegalizeDAG does.
  1209. if (!isPowerOf2_32(NumElts)) {
  1210. NumVectorRegs = NumElts;
  1211. NumElts = 1;
  1212. }
  1213. // Divide the input until we get to a supported size. This will always
  1214. // end with a scalar if the target doesn't support vectors.
  1215. while (NumElts > 1 && !isTypeLegal(
  1216. EVT::getVectorVT(Context, EltTy, NumElts))) {
  1217. NumElts >>= 1;
  1218. NumVectorRegs <<= 1;
  1219. }
  1220. NumIntermediates = NumVectorRegs;
  1221. EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
  1222. if (!isTypeLegal(NewVT))
  1223. NewVT = EltTy;
  1224. IntermediateVT = NewVT;
  1225. MVT DestVT = getRegisterType(Context, NewVT);
  1226. RegisterVT = DestVT;
  1227. unsigned NewVTSize = NewVT.getSizeInBits();
  1228. // Convert sizes such as i33 to i64.
  1229. if (!isPowerOf2_32(NewVTSize))
  1230. NewVTSize = NextPowerOf2(NewVTSize);
  1231. if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
  1232. return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
  1233. // Otherwise, promotion or legal types use the same number of registers as
  1234. // the vector decimated to the appropriate level.
  1235. return NumVectorRegs;
  1236. }
  1237. /// Get the EVTs and ArgFlags collections that represent the legalized return
  1238. /// type of the given function. This does not require a DAG or a return value,
  1239. /// and is suitable for use before any DAGs for the function are constructed.
  1240. /// TODO: Move this out of TargetLowering.cpp.
  1241. void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
  1242. AttributeList attr,
  1243. SmallVectorImpl<ISD::OutputArg> &Outs,
  1244. const TargetLowering &TLI, const DataLayout &DL) {
  1245. SmallVector<EVT, 4> ValueVTs;
  1246. ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
  1247. unsigned NumValues = ValueVTs.size();
  1248. if (NumValues == 0) return;
  1249. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  1250. EVT VT = ValueVTs[j];
  1251. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1252. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
  1253. ExtendKind = ISD::SIGN_EXTEND;
  1254. else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
  1255. ExtendKind = ISD::ZERO_EXTEND;
  1256. // FIXME: C calling convention requires the return type to be promoted to
  1257. // at least 32-bit. But this is not necessary for non-C calling
  1258. // conventions. The frontend should mark functions whose return values
  1259. // require promoting with signext or zeroext attributes.
  1260. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
  1261. MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
  1262. if (VT.bitsLT(MinVT))
  1263. VT = MinVT;
  1264. }
  1265. unsigned NumParts =
  1266. TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT);
  1267. MVT PartVT =
  1268. TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT);
  1269. // 'inreg' on function refers to return value
  1270. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1271. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::InReg))
  1272. Flags.setInReg();
  1273. // Propagate extension type if any
  1274. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
  1275. Flags.setSExt();
  1276. else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
  1277. Flags.setZExt();
  1278. for (unsigned i = 0; i < NumParts; ++i)
  1279. Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isFixed=*/true, 0, 0));
  1280. }
  1281. }
  1282. /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
  1283. /// function arguments in the caller parameter area. This is the actual
  1284. /// alignment, not its logarithm.
  1285. unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty,
  1286. const DataLayout &DL) const {
  1287. return DL.getABITypeAlignment(Ty);
  1288. }
  1289. bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
  1290. const DataLayout &DL, EVT VT,
  1291. unsigned AddrSpace,
  1292. unsigned Alignment,
  1293. bool *Fast) const {
  1294. // Check if the specified alignment is sufficient based on the data layout.
  1295. // TODO: While using the data layout works in practice, a better solution
  1296. // would be to implement this check directly (make this a virtual function).
  1297. // For example, the ABI alignment may change based on software platform while
  1298. // this function should only be affected by hardware implementation.
  1299. Type *Ty = VT.getTypeForEVT(Context);
  1300. if (Alignment >= DL.getABITypeAlignment(Ty)) {
  1301. // Assume that an access that meets the ABI-specified alignment is fast.
  1302. if (Fast != nullptr)
  1303. *Fast = true;
  1304. return true;
  1305. }
  1306. // This is a misaligned access.
  1307. return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Fast);
  1308. }
  1309. BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const {
  1310. return BranchProbability(MinPercentageForPredictableBranch, 100);
  1311. }
  1312. //===----------------------------------------------------------------------===//
  1313. // TargetTransformInfo Helpers
  1314. //===----------------------------------------------------------------------===//
  1315. int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
  1316. enum InstructionOpcodes {
  1317. #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
  1318. #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
  1319. #include "llvm/IR/Instruction.def"
  1320. };
  1321. switch (static_cast<InstructionOpcodes>(Opcode)) {
  1322. case Ret: return 0;
  1323. case Br: return 0;
  1324. case Switch: return 0;
  1325. case IndirectBr: return 0;
  1326. case Invoke: return 0;
  1327. case CallBr: return 0;
  1328. case Resume: return 0;
  1329. case Unreachable: return 0;
  1330. case CleanupRet: return 0;
  1331. case CatchRet: return 0;
  1332. case CatchPad: return 0;
  1333. case CatchSwitch: return 0;
  1334. case CleanupPad: return 0;
  1335. case FNeg: return ISD::FNEG;
  1336. case Add: return ISD::ADD;
  1337. case FAdd: return ISD::FADD;
  1338. case Sub: return ISD::SUB;
  1339. case FSub: return ISD::FSUB;
  1340. case Mul: return ISD::MUL;
  1341. case FMul: return ISD::FMUL;
  1342. case UDiv: return ISD::UDIV;
  1343. case SDiv: return ISD::SDIV;
  1344. case FDiv: return ISD::FDIV;
  1345. case URem: return ISD::UREM;
  1346. case SRem: return ISD::SREM;
  1347. case FRem: return ISD::FREM;
  1348. case Shl: return ISD::SHL;
  1349. case LShr: return ISD::SRL;
  1350. case AShr: return ISD::SRA;
  1351. case And: return ISD::AND;
  1352. case Or: return ISD::OR;
  1353. case Xor: return ISD::XOR;
  1354. case Alloca: return 0;
  1355. case Load: return ISD::LOAD;
  1356. case Store: return ISD::STORE;
  1357. case GetElementPtr: return 0;
  1358. case Fence: return 0;
  1359. case AtomicCmpXchg: return 0;
  1360. case AtomicRMW: return 0;
  1361. case Trunc: return ISD::TRUNCATE;
  1362. case ZExt: return ISD::ZERO_EXTEND;
  1363. case SExt: return ISD::SIGN_EXTEND;
  1364. case FPToUI: return ISD::FP_TO_UINT;
  1365. case FPToSI: return ISD::FP_TO_SINT;
  1366. case UIToFP: return ISD::UINT_TO_FP;
  1367. case SIToFP: return ISD::SINT_TO_FP;
  1368. case FPTrunc: return ISD::FP_ROUND;
  1369. case FPExt: return ISD::FP_EXTEND;
  1370. case PtrToInt: return ISD::BITCAST;
  1371. case IntToPtr: return ISD::BITCAST;
  1372. case BitCast: return ISD::BITCAST;
  1373. case AddrSpaceCast: return ISD::ADDRSPACECAST;
  1374. case ICmp: return ISD::SETCC;
  1375. case FCmp: return ISD::SETCC;
  1376. case PHI: return 0;
  1377. case Call: return 0;
  1378. case Select: return ISD::SELECT;
  1379. case UserOp1: return 0;
  1380. case UserOp2: return 0;
  1381. case VAArg: return 0;
  1382. case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
  1383. case InsertElement: return ISD::INSERT_VECTOR_ELT;
  1384. case ShuffleVector: return ISD::VECTOR_SHUFFLE;
  1385. case ExtractValue: return ISD::MERGE_VALUES;
  1386. case InsertValue: return ISD::MERGE_VALUES;
  1387. case LandingPad: return 0;
  1388. }
  1389. llvm_unreachable("Unknown instruction type encountered!");
  1390. }
  1391. std::pair<int, MVT>
  1392. TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL,
  1393. Type *Ty) const {
  1394. LLVMContext &C = Ty->getContext();
  1395. EVT MTy = getValueType(DL, Ty);
  1396. int Cost = 1;
  1397. // We keep legalizing the type until we find a legal kind. We assume that
  1398. // the only operation that costs anything is the split. After splitting
  1399. // we need to handle two types.
  1400. while (true) {
  1401. LegalizeKind LK = getTypeConversion(C, MTy);
  1402. if (LK.first == TypeLegal)
  1403. return std::make_pair(Cost, MTy.getSimpleVT());
  1404. if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
  1405. Cost *= 2;
  1406. // Do not loop with f128 type.
  1407. if (MTy == LK.second)
  1408. return std::make_pair(Cost, MTy.getSimpleVT());
  1409. // Keep legalizing the type.
  1410. MTy = LK.second;
  1411. }
  1412. }
  1413. Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
  1414. bool UseTLS) const {
  1415. // compiler-rt provides a variable with a magic name. Targets that do not
  1416. // link with compiler-rt may also provide such a variable.
  1417. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  1418. const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
  1419. auto UnsafeStackPtr =
  1420. dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
  1421. Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
  1422. if (!UnsafeStackPtr) {
  1423. auto TLSModel = UseTLS ?
  1424. GlobalValue::InitialExecTLSModel :
  1425. GlobalValue::NotThreadLocal;
  1426. // The global variable is not defined yet, define it ourselves.
  1427. // We use the initial-exec TLS model because we do not support the
  1428. // variable living anywhere other than in the main executable.
  1429. UnsafeStackPtr = new GlobalVariable(
  1430. *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
  1431. UnsafeStackPtrVar, nullptr, TLSModel);
  1432. } else {
  1433. // The variable exists, check its type and attributes.
  1434. if (UnsafeStackPtr->getValueType() != StackPtrTy)
  1435. report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
  1436. if (UseTLS != UnsafeStackPtr->isThreadLocal())
  1437. report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
  1438. (UseTLS ? "" : "not ") + "be thread-local");
  1439. }
  1440. return UnsafeStackPtr;
  1441. }
  1442. Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
  1443. if (!TM.getTargetTriple().isAndroid())
  1444. return getDefaultSafeStackPointerLocation(IRB, true);
  1445. // Android provides a libc function to retrieve the address of the current
  1446. // thread's unsafe stack pointer.
  1447. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  1448. Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
  1449. FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address",
  1450. StackPtrTy->getPointerTo(0));
  1451. return IRB.CreateCall(Fn);
  1452. }
  1453. //===----------------------------------------------------------------------===//
  1454. // Loop Strength Reduction hooks
  1455. //===----------------------------------------------------------------------===//
  1456. /// isLegalAddressingMode - Return true if the addressing mode represented
  1457. /// by AM is legal for this target, for a load/store of the specified type.
  1458. bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
  1459. const AddrMode &AM, Type *Ty,
  1460. unsigned AS, Instruction *I) const {
  1461. // The default implementation of this implements a conservative RISCy, r+r and
  1462. // r+i addr mode.
  1463. // Allows a sign-extended 16-bit immediate field.
  1464. if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
  1465. return false;
  1466. // No global is ever allowed as a base.
  1467. if (AM.BaseGV)
  1468. return false;
  1469. // Only support r+r,
  1470. switch (AM.Scale) {
  1471. case 0: // "r+i" or just "i", depending on HasBaseReg.
  1472. break;
  1473. case 1:
  1474. if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
  1475. return false;
  1476. // Otherwise we have r+r or r+i.
  1477. break;
  1478. case 2:
  1479. if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
  1480. return false;
  1481. // Allow 2*r as r+r.
  1482. break;
  1483. default: // Don't allow n * r
  1484. return false;
  1485. }
  1486. return true;
  1487. }
  1488. //===----------------------------------------------------------------------===//
  1489. // Stack Protector
  1490. //===----------------------------------------------------------------------===//
  1491. // For OpenBSD return its special guard variable. Otherwise return nullptr,
  1492. // so that SelectionDAG handle SSP.
  1493. Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const {
  1494. if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
  1495. Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
  1496. PointerType *PtrTy = Type::getInt8PtrTy(M.getContext());
  1497. return M.getOrInsertGlobal("__guard_local", PtrTy);
  1498. }
  1499. return nullptr;
  1500. }
  1501. // Currently only support "standard" __stack_chk_guard.
  1502. // TODO: add LOAD_STACK_GUARD support.
  1503. void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
  1504. if (!M.getNamedValue("__stack_chk_guard"))
  1505. new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false,
  1506. GlobalVariable::ExternalLinkage,
  1507. nullptr, "__stack_chk_guard");
  1508. }
  1509. // Currently only support "standard" __stack_chk_guard.
  1510. // TODO: add LOAD_STACK_GUARD support.
  1511. Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
  1512. return M.getNamedValue("__stack_chk_guard");
  1513. }
  1514. Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
  1515. return nullptr;
  1516. }
  1517. unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
  1518. return MinimumJumpTableEntries;
  1519. }
  1520. void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
  1521. MinimumJumpTableEntries = Val;
  1522. }
  1523. unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
  1524. return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
  1525. }
  1526. unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
  1527. return MaximumJumpTableSize;
  1528. }
  1529. void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
  1530. MaximumJumpTableSize = Val;
  1531. }
  1532. //===----------------------------------------------------------------------===//
  1533. // Reciprocal Estimates
  1534. //===----------------------------------------------------------------------===//
  1535. /// Get the reciprocal estimate attribute string for a function that will
  1536. /// override the target defaults.
  1537. static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
  1538. const Function &F = MF.getFunction();
  1539. return F.getFnAttribute("reciprocal-estimates").getValueAsString();
  1540. }
  1541. /// Construct a string for the given reciprocal operation of the given type.
  1542. /// This string should match the corresponding option to the front-end's
  1543. /// "-mrecip" flag assuming those strings have been passed through in an
  1544. /// attribute string. For example, "vec-divf" for a division of a vXf32.
  1545. static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
  1546. std::string Name = VT.isVector() ? "vec-" : "";
  1547. Name += IsSqrt ? "sqrt" : "div";
  1548. // TODO: Handle "half" or other float types?
  1549. if (VT.getScalarType() == MVT::f64) {
  1550. Name += "d";
  1551. } else {
  1552. assert(VT.getScalarType() == MVT::f32 &&
  1553. "Unexpected FP type for reciprocal estimate");
  1554. Name += "f";
  1555. }
  1556. return Name;
  1557. }
  1558. /// Return the character position and value (a single numeric character) of a
  1559. /// customized refinement operation in the input string if it exists. Return
  1560. /// false if there is no customized refinement step count.
  1561. static bool parseRefinementStep(StringRef In, size_t &Position,
  1562. uint8_t &Value) {
  1563. const char RefStepToken = ':';
  1564. Position = In.find(RefStepToken);
  1565. if (Position == StringRef::npos)
  1566. return false;
  1567. StringRef RefStepString = In.substr(Position + 1);
  1568. // Allow exactly one numeric character for the additional refinement
  1569. // step parameter.
  1570. if (RefStepString.size() == 1) {
  1571. char RefStepChar = RefStepString[0];
  1572. if (RefStepChar >= '0' && RefStepChar <= '9') {
  1573. Value = RefStepChar - '0';
  1574. return true;
  1575. }
  1576. }
  1577. report_fatal_error("Invalid refinement step for -recip.");
  1578. }
  1579. /// For the input attribute string, return one of the ReciprocalEstimate enum
  1580. /// status values (enabled, disabled, or not specified) for this operation on
  1581. /// the specified data type.
  1582. static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
  1583. if (Override.empty())
  1584. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1585. SmallVector<StringRef, 4> OverrideVector;
  1586. Override.split(OverrideVector, ',');
  1587. unsigned NumArgs = OverrideVector.size();
  1588. // Check if "all", "none", or "default" was specified.
  1589. if (NumArgs == 1) {
  1590. // Look for an optional setting of the number of refinement steps needed
  1591. // for this type of reciprocal operation.
  1592. size_t RefPos;
  1593. uint8_t RefSteps;
  1594. if (parseRefinementStep(Override, RefPos, RefSteps)) {
  1595. // Split the string for further processing.
  1596. Override = Override.substr(0, RefPos);
  1597. }
  1598. // All reciprocal types are enabled.
  1599. if (Override == "all")
  1600. return TargetLoweringBase::ReciprocalEstimate::Enabled;
  1601. // All reciprocal types are disabled.
  1602. if (Override == "none")
  1603. return TargetLoweringBase::ReciprocalEstimate::Disabled;
  1604. // Target defaults for enablement are used.
  1605. if (Override == "default")
  1606. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1607. }
  1608. // The attribute string may omit the size suffix ('f'/'d').
  1609. std::string VTName = getReciprocalOpName(IsSqrt, VT);
  1610. std::string VTNameNoSize = VTName;
  1611. VTNameNoSize.pop_back();
  1612. static const char DisabledPrefix = '!';
  1613. for (StringRef RecipType : OverrideVector) {
  1614. size_t RefPos;
  1615. uint8_t RefSteps;
  1616. if (parseRefinementStep(RecipType, RefPos, RefSteps))
  1617. RecipType = RecipType.substr(0, RefPos);
  1618. // Ignore the disablement token for string matching.
  1619. bool IsDisabled = RecipType[0] == DisabledPrefix;
  1620. if (IsDisabled)
  1621. RecipType = RecipType.substr(1);
  1622. if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
  1623. return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
  1624. : TargetLoweringBase::ReciprocalEstimate::Enabled;
  1625. }
  1626. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1627. }
  1628. /// For the input attribute string, return the customized refinement step count
  1629. /// for this operation on the specified data type. If the step count does not
  1630. /// exist, return the ReciprocalEstimate enum value for unspecified.
  1631. static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
  1632. if (Override.empty())
  1633. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1634. SmallVector<StringRef, 4> OverrideVector;
  1635. Override.split(OverrideVector, ',');
  1636. unsigned NumArgs = OverrideVector.size();
  1637. // Check if "all", "default", or "none" was specified.
  1638. if (NumArgs == 1) {
  1639. // Look for an optional setting of the number of refinement steps needed
  1640. // for this type of reciprocal operation.
  1641. size_t RefPos;
  1642. uint8_t RefSteps;
  1643. if (!parseRefinementStep(Override, RefPos, RefSteps))
  1644. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1645. // Split the string for further processing.
  1646. Override = Override.substr(0, RefPos);
  1647. assert(Override != "none" &&
  1648. "Disabled reciprocals, but specifed refinement steps?");
  1649. // If this is a general override, return the specified number of steps.
  1650. if (Override == "all" || Override == "default")
  1651. return RefSteps;
  1652. }
  1653. // The attribute string may omit the size suffix ('f'/'d').
  1654. std::string VTName = getReciprocalOpName(IsSqrt, VT);
  1655. std::string VTNameNoSize = VTName;
  1656. VTNameNoSize.pop_back();
  1657. for (StringRef RecipType : OverrideVector) {
  1658. size_t RefPos;
  1659. uint8_t RefSteps;
  1660. if (!parseRefinementStep(RecipType, RefPos, RefSteps))
  1661. continue;
  1662. RecipType = RecipType.substr(0, RefPos);
  1663. if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
  1664. return RefSteps;
  1665. }
  1666. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1667. }
  1668. int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
  1669. MachineFunction &MF) const {
  1670. return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
  1671. }
  1672. int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
  1673. MachineFunction &MF) const {
  1674. return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
  1675. }
  1676. int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
  1677. MachineFunction &MF) const {
  1678. return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
  1679. }
  1680. int TargetLoweringBase::getDivRefinementSteps(EVT VT,
  1681. MachineFunction &MF) const {
  1682. return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
  1683. }
  1684. void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
  1685. MF.getRegInfo().freezeReservedRegs(MF);
  1686. }