ARMTargetTransformInfo.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115
  1. //===- ARMTargetTransformInfo.cpp - ARM specific TTI ----------------------===//
  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. #include "ARMTargetTransformInfo.h"
  9. #include "ARMSubtarget.h"
  10. #include "MCTargetDesc/ARMAddressingModes.h"
  11. #include "llvm/ADT/APInt.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/Analysis/LoopInfo.h"
  14. #include "llvm/CodeGen/CostTable.h"
  15. #include "llvm/CodeGen/ISDOpcodes.h"
  16. #include "llvm/CodeGen/ValueTypes.h"
  17. #include "llvm/IR/BasicBlock.h"
  18. #include "llvm/IR/DataLayout.h"
  19. #include "llvm/IR/DerivedTypes.h"
  20. #include "llvm/IR/Instruction.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/Intrinsics.h"
  23. #include "llvm/IR/IntrinsicInst.h"
  24. #include "llvm/IR/IntrinsicsARM.h"
  25. #include "llvm/IR/PatternMatch.h"
  26. #include "llvm/IR/Type.h"
  27. #include "llvm/MC/SubtargetFeature.h"
  28. #include "llvm/Support/Casting.h"
  29. #include "llvm/Support/KnownBits.h"
  30. #include "llvm/Support/MachineValueType.h"
  31. #include "llvm/Target/TargetMachine.h"
  32. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  33. #include "llvm/Transforms/Utils/Local.h"
  34. #include "llvm/Transforms/Utils/LoopUtils.h"
  35. #include <algorithm>
  36. #include <cassert>
  37. #include <cstdint>
  38. #include <utility>
  39. using namespace llvm;
  40. #define DEBUG_TYPE "armtti"
  41. static cl::opt<bool> EnableMaskedLoadStores(
  42. "enable-arm-maskedldst", cl::Hidden, cl::init(true),
  43. cl::desc("Enable the generation of masked loads and stores"));
  44. static cl::opt<bool> DisableLowOverheadLoops(
  45. "disable-arm-loloops", cl::Hidden, cl::init(false),
  46. cl::desc("Disable the generation of low-overhead loops"));
  47. static cl::opt<bool>
  48. AllowWLSLoops("allow-arm-wlsloops", cl::Hidden, cl::init(true),
  49. cl::desc("Enable the generation of WLS loops"));
  50. extern cl::opt<TailPredication::Mode> EnableTailPredication;
  51. extern cl::opt<bool> EnableMaskedGatherScatters;
  52. extern cl::opt<unsigned> MVEMaxSupportedInterleaveFactor;
  53. /// Convert a vector load intrinsic into a simple llvm load instruction.
  54. /// This is beneficial when the underlying object being addressed comes
  55. /// from a constant, since we get constant-folding for free.
  56. static Value *simplifyNeonVld1(const IntrinsicInst &II, unsigned MemAlign,
  57. InstCombiner::BuilderTy &Builder) {
  58. auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
  59. if (!IntrAlign)
  60. return nullptr;
  61. unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign
  62. ? MemAlign
  63. : IntrAlign->getLimitedValue();
  64. if (!isPowerOf2_32(Alignment))
  65. return nullptr;
  66. auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
  67. PointerType::get(II.getType(), 0));
  68. return Builder.CreateAlignedLoad(II.getType(), BCastInst, Align(Alignment));
  69. }
  70. bool ARMTTIImpl::areInlineCompatible(const Function *Caller,
  71. const Function *Callee) const {
  72. const TargetMachine &TM = getTLI()->getTargetMachine();
  73. const FeatureBitset &CallerBits =
  74. TM.getSubtargetImpl(*Caller)->getFeatureBits();
  75. const FeatureBitset &CalleeBits =
  76. TM.getSubtargetImpl(*Callee)->getFeatureBits();
  77. // To inline a callee, all features not in the allowed list must match exactly.
  78. bool MatchExact = (CallerBits & ~InlineFeaturesAllowed) ==
  79. (CalleeBits & ~InlineFeaturesAllowed);
  80. // For features in the allowed list, the callee's features must be a subset of
  81. // the callers'.
  82. bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeaturesAllowed) ==
  83. (CalleeBits & InlineFeaturesAllowed);
  84. return MatchExact && MatchSubset;
  85. }
  86. bool ARMTTIImpl::shouldFavorBackedgeIndex(const Loop *L) const {
  87. if (L->getHeader()->getParent()->hasOptSize())
  88. return false;
  89. if (ST->hasMVEIntegerOps())
  90. return false;
  91. return ST->isMClass() && ST->isThumb2() && L->getNumBlocks() == 1;
  92. }
  93. bool ARMTTIImpl::shouldFavorPostInc() const {
  94. if (ST->hasMVEIntegerOps())
  95. return true;
  96. return false;
  97. }
  98. Optional<Instruction *>
  99. ARMTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
  100. using namespace PatternMatch;
  101. Intrinsic::ID IID = II.getIntrinsicID();
  102. switch (IID) {
  103. default:
  104. break;
  105. case Intrinsic::arm_neon_vld1: {
  106. Align MemAlign =
  107. getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
  108. &IC.getAssumptionCache(), &IC.getDominatorTree());
  109. if (Value *V = simplifyNeonVld1(II, MemAlign.value(), IC.Builder)) {
  110. return IC.replaceInstUsesWith(II, V);
  111. }
  112. break;
  113. }
  114. case Intrinsic::arm_neon_vld2:
  115. case Intrinsic::arm_neon_vld3:
  116. case Intrinsic::arm_neon_vld4:
  117. case Intrinsic::arm_neon_vld2lane:
  118. case Intrinsic::arm_neon_vld3lane:
  119. case Intrinsic::arm_neon_vld4lane:
  120. case Intrinsic::arm_neon_vst1:
  121. case Intrinsic::arm_neon_vst2:
  122. case Intrinsic::arm_neon_vst3:
  123. case Intrinsic::arm_neon_vst4:
  124. case Intrinsic::arm_neon_vst2lane:
  125. case Intrinsic::arm_neon_vst3lane:
  126. case Intrinsic::arm_neon_vst4lane: {
  127. Align MemAlign =
  128. getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
  129. &IC.getAssumptionCache(), &IC.getDominatorTree());
  130. unsigned AlignArg = II.getNumArgOperands() - 1;
  131. Value *AlignArgOp = II.getArgOperand(AlignArg);
  132. MaybeAlign Align = cast<ConstantInt>(AlignArgOp)->getMaybeAlignValue();
  133. if (Align && *Align < MemAlign) {
  134. return IC.replaceOperand(
  135. II, AlignArg,
  136. ConstantInt::get(Type::getInt32Ty(II.getContext()), MemAlign.value(),
  137. false));
  138. }
  139. break;
  140. }
  141. case Intrinsic::arm_mve_pred_i2v: {
  142. Value *Arg = II.getArgOperand(0);
  143. Value *ArgArg;
  144. if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(
  145. PatternMatch::m_Value(ArgArg))) &&
  146. II.getType() == ArgArg->getType()) {
  147. return IC.replaceInstUsesWith(II, ArgArg);
  148. }
  149. Constant *XorMask;
  150. if (match(Arg, m_Xor(PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(
  151. PatternMatch::m_Value(ArgArg)),
  152. PatternMatch::m_Constant(XorMask))) &&
  153. II.getType() == ArgArg->getType()) {
  154. if (auto *CI = dyn_cast<ConstantInt>(XorMask)) {
  155. if (CI->getValue().trunc(16).isAllOnesValue()) {
  156. auto TrueVector = IC.Builder.CreateVectorSplat(
  157. cast<FixedVectorType>(II.getType())->getNumElements(),
  158. IC.Builder.getTrue());
  159. return BinaryOperator::Create(Instruction::Xor, ArgArg, TrueVector);
  160. }
  161. }
  162. }
  163. KnownBits ScalarKnown(32);
  164. if (IC.SimplifyDemandedBits(&II, 0, APInt::getLowBitsSet(32, 16),
  165. ScalarKnown, 0)) {
  166. return &II;
  167. }
  168. break;
  169. }
  170. case Intrinsic::arm_mve_pred_v2i: {
  171. Value *Arg = II.getArgOperand(0);
  172. Value *ArgArg;
  173. if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_i2v>(
  174. PatternMatch::m_Value(ArgArg)))) {
  175. return IC.replaceInstUsesWith(II, ArgArg);
  176. }
  177. if (!II.getMetadata(LLVMContext::MD_range)) {
  178. Type *IntTy32 = Type::getInt32Ty(II.getContext());
  179. Metadata *M[] = {
  180. ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0)),
  181. ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0xFFFF))};
  182. II.setMetadata(LLVMContext::MD_range, MDNode::get(II.getContext(), M));
  183. return &II;
  184. }
  185. break;
  186. }
  187. case Intrinsic::arm_mve_vadc:
  188. case Intrinsic::arm_mve_vadc_predicated: {
  189. unsigned CarryOp =
  190. (II.getIntrinsicID() == Intrinsic::arm_mve_vadc_predicated) ? 3 : 2;
  191. assert(II.getArgOperand(CarryOp)->getType()->getScalarSizeInBits() == 32 &&
  192. "Bad type for intrinsic!");
  193. KnownBits CarryKnown(32);
  194. if (IC.SimplifyDemandedBits(&II, CarryOp, APInt::getOneBitSet(32, 29),
  195. CarryKnown)) {
  196. return &II;
  197. }
  198. break;
  199. }
  200. case Intrinsic::arm_mve_vmldava: {
  201. Instruction *I = cast<Instruction>(&II);
  202. if (I->hasOneUse()) {
  203. auto *User = cast<Instruction>(*I->user_begin());
  204. Value *OpZ;
  205. if (match(User, m_c_Add(m_Specific(I), m_Value(OpZ))) &&
  206. match(I->getOperand(3), m_Zero())) {
  207. Value *OpX = I->getOperand(4);
  208. Value *OpY = I->getOperand(5);
  209. Type *OpTy = OpX->getType();
  210. IC.Builder.SetInsertPoint(User);
  211. Value *V =
  212. IC.Builder.CreateIntrinsic(Intrinsic::arm_mve_vmldava, {OpTy},
  213. {I->getOperand(0), I->getOperand(1),
  214. I->getOperand(2), OpZ, OpX, OpY});
  215. IC.replaceInstUsesWith(*User, V);
  216. return IC.eraseInstFromFunction(*User);
  217. }
  218. }
  219. return None;
  220. }
  221. }
  222. return None;
  223. }
  224. int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
  225. TTI::TargetCostKind CostKind) {
  226. assert(Ty->isIntegerTy());
  227. unsigned Bits = Ty->getPrimitiveSizeInBits();
  228. if (Bits == 0 || Imm.getActiveBits() >= 64)
  229. return 4;
  230. int64_t SImmVal = Imm.getSExtValue();
  231. uint64_t ZImmVal = Imm.getZExtValue();
  232. if (!ST->isThumb()) {
  233. if ((SImmVal >= 0 && SImmVal < 65536) ||
  234. (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
  235. (ARM_AM::getSOImmVal(~ZImmVal) != -1))
  236. return 1;
  237. return ST->hasV6T2Ops() ? 2 : 3;
  238. }
  239. if (ST->isThumb2()) {
  240. if ((SImmVal >= 0 && SImmVal < 65536) ||
  241. (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
  242. (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
  243. return 1;
  244. return ST->hasV6T2Ops() ? 2 : 3;
  245. }
  246. // Thumb1, any i8 imm cost 1.
  247. if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
  248. return 1;
  249. if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
  250. return 2;
  251. // Load from constantpool.
  252. return 3;
  253. }
  254. // Constants smaller than 256 fit in the immediate field of
  255. // Thumb1 instructions so we return a zero cost and 1 otherwise.
  256. int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
  257. const APInt &Imm, Type *Ty) {
  258. if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
  259. return 0;
  260. return 1;
  261. }
  262. // Checks whether Inst is part of a min(max()) or max(min()) pattern
  263. // that will match to an SSAT instruction
  264. static bool isSSATMinMaxPattern(Instruction *Inst, const APInt &Imm) {
  265. Value *LHS, *RHS;
  266. ConstantInt *C;
  267. SelectPatternFlavor InstSPF = matchSelectPattern(Inst, LHS, RHS).Flavor;
  268. if (InstSPF == SPF_SMAX &&
  269. PatternMatch::match(RHS, PatternMatch::m_ConstantInt(C)) &&
  270. C->getValue() == Imm && Imm.isNegative() && (-Imm).isPowerOf2()) {
  271. auto isSSatMin = [&](Value *MinInst) {
  272. if (isa<SelectInst>(MinInst)) {
  273. Value *MinLHS, *MinRHS;
  274. ConstantInt *MinC;
  275. SelectPatternFlavor MinSPF =
  276. matchSelectPattern(MinInst, MinLHS, MinRHS).Flavor;
  277. if (MinSPF == SPF_SMIN &&
  278. PatternMatch::match(MinRHS, PatternMatch::m_ConstantInt(MinC)) &&
  279. MinC->getValue() == ((-Imm) - 1))
  280. return true;
  281. }
  282. return false;
  283. };
  284. if (isSSatMin(Inst->getOperand(1)) ||
  285. (Inst->hasNUses(2) && (isSSatMin(*Inst->user_begin()) ||
  286. isSSatMin(*(++Inst->user_begin())))))
  287. return true;
  288. }
  289. return false;
  290. }
  291. int ARMTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
  292. const APInt &Imm, Type *Ty,
  293. TTI::TargetCostKind CostKind,
  294. Instruction *Inst) {
  295. // Division by a constant can be turned into multiplication, but only if we
  296. // know it's constant. So it's not so much that the immediate is cheap (it's
  297. // not), but that the alternative is worse.
  298. // FIXME: this is probably unneeded with GlobalISel.
  299. if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
  300. Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
  301. Idx == 1)
  302. return 0;
  303. if (Opcode == Instruction::And) {
  304. // UXTB/UXTH
  305. if (Imm == 255 || Imm == 65535)
  306. return 0;
  307. // Conversion to BIC is free, and means we can use ~Imm instead.
  308. return std::min(getIntImmCost(Imm, Ty, CostKind),
  309. getIntImmCost(~Imm, Ty, CostKind));
  310. }
  311. if (Opcode == Instruction::Add)
  312. // Conversion to SUB is free, and means we can use -Imm instead.
  313. return std::min(getIntImmCost(Imm, Ty, CostKind),
  314. getIntImmCost(-Imm, Ty, CostKind));
  315. if (Opcode == Instruction::ICmp && Imm.isNegative() &&
  316. Ty->getIntegerBitWidth() == 32) {
  317. int64_t NegImm = -Imm.getSExtValue();
  318. if (ST->isThumb2() && NegImm < 1<<12)
  319. // icmp X, #-C -> cmn X, #C
  320. return 0;
  321. if (ST->isThumb() && NegImm < 1<<8)
  322. // icmp X, #-C -> adds X, #C
  323. return 0;
  324. }
  325. // xor a, -1 can always be folded to MVN
  326. if (Opcode == Instruction::Xor && Imm.isAllOnesValue())
  327. return 0;
  328. // Ensures negative constant of min(max()) or max(min()) patterns that
  329. // match to SSAT instructions don't get hoisted
  330. if (Inst && ((ST->hasV6Ops() && !ST->isThumb()) || ST->isThumb2()) &&
  331. Ty->getIntegerBitWidth() <= 32) {
  332. if (isSSATMinMaxPattern(Inst, Imm) ||
  333. (isa<ICmpInst>(Inst) && Inst->hasOneUse() &&
  334. isSSATMinMaxPattern(cast<Instruction>(*Inst->user_begin()), Imm)))
  335. return 0;
  336. }
  337. return getIntImmCost(Imm, Ty, CostKind);
  338. }
  339. int ARMTTIImpl::getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind) {
  340. if (CostKind == TTI::TCK_RecipThroughput &&
  341. (ST->hasNEON() || ST->hasMVEIntegerOps())) {
  342. // FIXME: The vectorizer is highly sensistive to the cost of these
  343. // instructions, which suggests that it may be using the costs incorrectly.
  344. // But, for now, just make them free to avoid performance regressions for
  345. // vector targets.
  346. return 0;
  347. }
  348. return BaseT::getCFInstrCost(Opcode, CostKind);
  349. }
  350. int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
  351. TTI::CastContextHint CCH,
  352. TTI::TargetCostKind CostKind,
  353. const Instruction *I) {
  354. int ISD = TLI->InstructionOpcodeToISD(Opcode);
  355. assert(ISD && "Invalid opcode");
  356. // TODO: Allow non-throughput costs that aren't binary.
  357. auto AdjustCost = [&CostKind](int Cost) {
  358. if (CostKind != TTI::TCK_RecipThroughput)
  359. return Cost == 0 ? 0 : 1;
  360. return Cost;
  361. };
  362. auto IsLegalFPType = [this](EVT VT) {
  363. EVT EltVT = VT.getScalarType();
  364. return (EltVT == MVT::f32 && ST->hasVFP2Base()) ||
  365. (EltVT == MVT::f64 && ST->hasFP64()) ||
  366. (EltVT == MVT::f16 && ST->hasFullFP16());
  367. };
  368. EVT SrcTy = TLI->getValueType(DL, Src);
  369. EVT DstTy = TLI->getValueType(DL, Dst);
  370. if (!SrcTy.isSimple() || !DstTy.isSimple())
  371. return AdjustCost(
  372. BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
  373. // Extending masked load/Truncating masked stores is expensive because we
  374. // currently don't split them. This means that we'll likely end up
  375. // loading/storing each element individually (hence the high cost).
  376. if ((ST->hasMVEIntegerOps() &&
  377. (Opcode == Instruction::Trunc || Opcode == Instruction::ZExt ||
  378. Opcode == Instruction::SExt)) ||
  379. (ST->hasMVEFloatOps() &&
  380. (Opcode == Instruction::FPExt || Opcode == Instruction::FPTrunc) &&
  381. IsLegalFPType(SrcTy) && IsLegalFPType(DstTy)))
  382. if (CCH == TTI::CastContextHint::Masked && DstTy.getSizeInBits() > 128)
  383. return 2 * DstTy.getVectorNumElements() * ST->getMVEVectorCostFactor();
  384. // The extend of other kinds of load is free
  385. if (CCH == TTI::CastContextHint::Normal ||
  386. CCH == TTI::CastContextHint::Masked) {
  387. static const TypeConversionCostTblEntry LoadConversionTbl[] = {
  388. {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0},
  389. {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0},
  390. {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0},
  391. {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0},
  392. {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0},
  393. {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0},
  394. {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1},
  395. {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1},
  396. {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1},
  397. {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1},
  398. {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1},
  399. {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1},
  400. };
  401. if (const auto *Entry = ConvertCostTableLookup(
  402. LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
  403. return AdjustCost(Entry->Cost);
  404. static const TypeConversionCostTblEntry MVELoadConversionTbl[] = {
  405. {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0},
  406. {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0},
  407. {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0},
  408. {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0},
  409. {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0},
  410. {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0},
  411. // The following extend from a legal type to an illegal type, so need to
  412. // split the load. This introduced an extra load operation, but the
  413. // extend is still "free".
  414. {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1},
  415. {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1},
  416. {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 3},
  417. {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 3},
  418. {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 1},
  419. {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 1},
  420. };
  421. if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
  422. if (const auto *Entry =
  423. ConvertCostTableLookup(MVELoadConversionTbl, ISD,
  424. DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
  425. return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
  426. }
  427. static const TypeConversionCostTblEntry MVEFLoadConversionTbl[] = {
  428. // FPExtends are similar but also require the VCVT instructions.
  429. {ISD::FP_EXTEND, MVT::v4f32, MVT::v4f16, 1},
  430. {ISD::FP_EXTEND, MVT::v8f32, MVT::v8f16, 3},
  431. };
  432. if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
  433. if (const auto *Entry =
  434. ConvertCostTableLookup(MVEFLoadConversionTbl, ISD,
  435. DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
  436. return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
  437. }
  438. // The truncate of a store is free. This is the mirror of extends above.
  439. static const TypeConversionCostTblEntry MVEStoreConversionTbl[] = {
  440. {ISD::TRUNCATE, MVT::v4i32, MVT::v4i16, 0},
  441. {ISD::TRUNCATE, MVT::v4i32, MVT::v4i8, 0},
  442. {ISD::TRUNCATE, MVT::v8i16, MVT::v8i8, 0},
  443. {ISD::TRUNCATE, MVT::v8i32, MVT::v8i16, 1},
  444. {ISD::TRUNCATE, MVT::v8i32, MVT::v8i8, 1},
  445. {ISD::TRUNCATE, MVT::v16i32, MVT::v16i8, 3},
  446. {ISD::TRUNCATE, MVT::v16i16, MVT::v16i8, 1},
  447. };
  448. if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
  449. if (const auto *Entry =
  450. ConvertCostTableLookup(MVEStoreConversionTbl, ISD,
  451. SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
  452. return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
  453. }
  454. static const TypeConversionCostTblEntry MVEFStoreConversionTbl[] = {
  455. {ISD::FP_ROUND, MVT::v4f32, MVT::v4f16, 1},
  456. {ISD::FP_ROUND, MVT::v8f32, MVT::v8f16, 3},
  457. };
  458. if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
  459. if (const auto *Entry =
  460. ConvertCostTableLookup(MVEFStoreConversionTbl, ISD,
  461. SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
  462. return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
  463. }
  464. }
  465. // NEON vector operations that can extend their inputs.
  466. if ((ISD == ISD::SIGN_EXTEND || ISD == ISD::ZERO_EXTEND) &&
  467. I && I->hasOneUse() && ST->hasNEON() && SrcTy.isVector()) {
  468. static const TypeConversionCostTblEntry NEONDoubleWidthTbl[] = {
  469. // vaddl
  470. { ISD::ADD, MVT::v4i32, MVT::v4i16, 0 },
  471. { ISD::ADD, MVT::v8i16, MVT::v8i8, 0 },
  472. // vsubl
  473. { ISD::SUB, MVT::v4i32, MVT::v4i16, 0 },
  474. { ISD::SUB, MVT::v8i16, MVT::v8i8, 0 },
  475. // vmull
  476. { ISD::MUL, MVT::v4i32, MVT::v4i16, 0 },
  477. { ISD::MUL, MVT::v8i16, MVT::v8i8, 0 },
  478. // vshll
  479. { ISD::SHL, MVT::v4i32, MVT::v4i16, 0 },
  480. { ISD::SHL, MVT::v8i16, MVT::v8i8, 0 },
  481. };
  482. auto *User = cast<Instruction>(*I->user_begin());
  483. int UserISD = TLI->InstructionOpcodeToISD(User->getOpcode());
  484. if (auto *Entry = ConvertCostTableLookup(NEONDoubleWidthTbl, UserISD,
  485. DstTy.getSimpleVT(),
  486. SrcTy.getSimpleVT())) {
  487. return AdjustCost(Entry->Cost);
  488. }
  489. }
  490. // Single to/from double precision conversions.
  491. if (Src->isVectorTy() && ST->hasNEON() &&
  492. ((ISD == ISD::FP_ROUND && SrcTy.getScalarType() == MVT::f64 &&
  493. DstTy.getScalarType() == MVT::f32) ||
  494. (ISD == ISD::FP_EXTEND && SrcTy.getScalarType() == MVT::f32 &&
  495. DstTy.getScalarType() == MVT::f64))) {
  496. static const CostTblEntry NEONFltDblTbl[] = {
  497. // Vector fptrunc/fpext conversions.
  498. {ISD::FP_ROUND, MVT::v2f64, 2},
  499. {ISD::FP_EXTEND, MVT::v2f32, 2},
  500. {ISD::FP_EXTEND, MVT::v4f32, 4}};
  501. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
  502. if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
  503. return AdjustCost(LT.first * Entry->Cost);
  504. }
  505. // Some arithmetic, load and store operations have specific instructions
  506. // to cast up/down their types automatically at no extra cost.
  507. // TODO: Get these tables to know at least what the related operations are.
  508. static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
  509. { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
  510. { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
  511. { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
  512. { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
  513. { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 0 },
  514. { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 },
  515. // The number of vmovl instructions for the extension.
  516. { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
  517. { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
  518. { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
  519. { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
  520. { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 3 },
  521. { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 3 },
  522. { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
  523. { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
  524. { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
  525. { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
  526. { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
  527. { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
  528. { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
  529. { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
  530. { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
  531. { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
  532. { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
  533. { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
  534. // Operations that we legalize using splitting.
  535. { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
  536. { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 },
  537. // Vector float <-> i32 conversions.
  538. { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
  539. { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
  540. { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
  541. { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
  542. { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
  543. { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
  544. { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
  545. { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
  546. { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
  547. { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
  548. { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
  549. { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
  550. { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
  551. { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
  552. { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
  553. { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
  554. { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
  555. { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
  556. { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
  557. { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
  558. { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
  559. { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
  560. { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
  561. { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
  562. { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 3 },
  563. { ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 3 },
  564. { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
  565. { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
  566. // Vector double <-> i32 conversions.
  567. { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
  568. { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
  569. { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
  570. { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
  571. { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
  572. { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
  573. { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
  574. { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
  575. { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
  576. { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
  577. { ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f32, 4 },
  578. { ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f32, 4 },
  579. { ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f32, 8 },
  580. { ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f32, 8 }
  581. };
  582. if (SrcTy.isVector() && ST->hasNEON()) {
  583. if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
  584. DstTy.getSimpleVT(),
  585. SrcTy.getSimpleVT()))
  586. return AdjustCost(Entry->Cost);
  587. }
  588. // Scalar float to integer conversions.
  589. static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
  590. { ISD::FP_TO_SINT, MVT::i1, MVT::f32, 2 },
  591. { ISD::FP_TO_UINT, MVT::i1, MVT::f32, 2 },
  592. { ISD::FP_TO_SINT, MVT::i1, MVT::f64, 2 },
  593. { ISD::FP_TO_UINT, MVT::i1, MVT::f64, 2 },
  594. { ISD::FP_TO_SINT, MVT::i8, MVT::f32, 2 },
  595. { ISD::FP_TO_UINT, MVT::i8, MVT::f32, 2 },
  596. { ISD::FP_TO_SINT, MVT::i8, MVT::f64, 2 },
  597. { ISD::FP_TO_UINT, MVT::i8, MVT::f64, 2 },
  598. { ISD::FP_TO_SINT, MVT::i16, MVT::f32, 2 },
  599. { ISD::FP_TO_UINT, MVT::i16, MVT::f32, 2 },
  600. { ISD::FP_TO_SINT, MVT::i16, MVT::f64, 2 },
  601. { ISD::FP_TO_UINT, MVT::i16, MVT::f64, 2 },
  602. { ISD::FP_TO_SINT, MVT::i32, MVT::f32, 2 },
  603. { ISD::FP_TO_UINT, MVT::i32, MVT::f32, 2 },
  604. { ISD::FP_TO_SINT, MVT::i32, MVT::f64, 2 },
  605. { ISD::FP_TO_UINT, MVT::i32, MVT::f64, 2 },
  606. { ISD::FP_TO_SINT, MVT::i64, MVT::f32, 10 },
  607. { ISD::FP_TO_UINT, MVT::i64, MVT::f32, 10 },
  608. { ISD::FP_TO_SINT, MVT::i64, MVT::f64, 10 },
  609. { ISD::FP_TO_UINT, MVT::i64, MVT::f64, 10 }
  610. };
  611. if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
  612. if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
  613. DstTy.getSimpleVT(),
  614. SrcTy.getSimpleVT()))
  615. return AdjustCost(Entry->Cost);
  616. }
  617. // Scalar integer to float conversions.
  618. static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
  619. { ISD::SINT_TO_FP, MVT::f32, MVT::i1, 2 },
  620. { ISD::UINT_TO_FP, MVT::f32, MVT::i1, 2 },
  621. { ISD::SINT_TO_FP, MVT::f64, MVT::i1, 2 },
  622. { ISD::UINT_TO_FP, MVT::f64, MVT::i1, 2 },
  623. { ISD::SINT_TO_FP, MVT::f32, MVT::i8, 2 },
  624. { ISD::UINT_TO_FP, MVT::f32, MVT::i8, 2 },
  625. { ISD::SINT_TO_FP, MVT::f64, MVT::i8, 2 },
  626. { ISD::UINT_TO_FP, MVT::f64, MVT::i8, 2 },
  627. { ISD::SINT_TO_FP, MVT::f32, MVT::i16, 2 },
  628. { ISD::UINT_TO_FP, MVT::f32, MVT::i16, 2 },
  629. { ISD::SINT_TO_FP, MVT::f64, MVT::i16, 2 },
  630. { ISD::UINT_TO_FP, MVT::f64, MVT::i16, 2 },
  631. { ISD::SINT_TO_FP, MVT::f32, MVT::i32, 2 },
  632. { ISD::UINT_TO_FP, MVT::f32, MVT::i32, 2 },
  633. { ISD::SINT_TO_FP, MVT::f64, MVT::i32, 2 },
  634. { ISD::UINT_TO_FP, MVT::f64, MVT::i32, 2 },
  635. { ISD::SINT_TO_FP, MVT::f32, MVT::i64, 10 },
  636. { ISD::UINT_TO_FP, MVT::f32, MVT::i64, 10 },
  637. { ISD::SINT_TO_FP, MVT::f64, MVT::i64, 10 },
  638. { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 10 }
  639. };
  640. if (SrcTy.isInteger() && ST->hasNEON()) {
  641. if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
  642. ISD, DstTy.getSimpleVT(),
  643. SrcTy.getSimpleVT()))
  644. return AdjustCost(Entry->Cost);
  645. }
  646. // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one
  647. // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext
  648. // are linearised so take more.
  649. static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = {
  650. { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
  651. { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
  652. { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
  653. { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
  654. { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 },
  655. { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 },
  656. { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
  657. { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
  658. { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 },
  659. { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
  660. { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 },
  661. { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 },
  662. };
  663. if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
  664. if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl,
  665. ISD, DstTy.getSimpleVT(),
  666. SrcTy.getSimpleVT()))
  667. return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
  668. }
  669. if (ISD == ISD::FP_ROUND || ISD == ISD::FP_EXTEND) {
  670. // As general rule, fp converts that were not matched above are scalarized
  671. // and cost 1 vcvt for each lane, so long as the instruction is available.
  672. // If not it will become a series of function calls.
  673. const int CallCost = getCallInstrCost(nullptr, Dst, {Src}, CostKind);
  674. int Lanes = 1;
  675. if (SrcTy.isFixedLengthVector())
  676. Lanes = SrcTy.getVectorNumElements();
  677. if (IsLegalFPType(SrcTy) && IsLegalFPType(DstTy))
  678. return Lanes;
  679. else
  680. return Lanes * CallCost;
  681. }
  682. if (ISD == ISD::TRUNCATE && ST->hasMVEIntegerOps() &&
  683. SrcTy.isFixedLengthVector()) {
  684. // Treat a truncate with larger than legal source (128bits for MVE) as
  685. // expensive, 2 instructions per lane.
  686. if ((SrcTy.getScalarType() == MVT::i8 ||
  687. SrcTy.getScalarType() == MVT::i16 ||
  688. SrcTy.getScalarType() == MVT::i32) &&
  689. SrcTy.getSizeInBits() > 128 &&
  690. SrcTy.getSizeInBits() > DstTy.getSizeInBits())
  691. return SrcTy.getVectorNumElements() * 2;
  692. }
  693. // Scalar integer conversion costs.
  694. static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
  695. // i16 -> i64 requires two dependent operations.
  696. { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
  697. // Truncates on i64 are assumed to be free.
  698. { ISD::TRUNCATE, MVT::i32, MVT::i64, 0 },
  699. { ISD::TRUNCATE, MVT::i16, MVT::i64, 0 },
  700. { ISD::TRUNCATE, MVT::i8, MVT::i64, 0 },
  701. { ISD::TRUNCATE, MVT::i1, MVT::i64, 0 }
  702. };
  703. if (SrcTy.isInteger()) {
  704. if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
  705. DstTy.getSimpleVT(),
  706. SrcTy.getSimpleVT()))
  707. return AdjustCost(Entry->Cost);
  708. }
  709. int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
  710. ? ST->getMVEVectorCostFactor()
  711. : 1;
  712. return AdjustCost(
  713. BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
  714. }
  715. int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
  716. unsigned Index) {
  717. // Penalize inserting into an D-subregister. We end up with a three times
  718. // lower estimated throughput on swift.
  719. if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
  720. ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
  721. return 3;
  722. if (ST->hasNEON() && (Opcode == Instruction::InsertElement ||
  723. Opcode == Instruction::ExtractElement)) {
  724. // Cross-class copies are expensive on many microarchitectures,
  725. // so assume they are expensive by default.
  726. if (cast<VectorType>(ValTy)->getElementType()->isIntegerTy())
  727. return 3;
  728. // Even if it's not a cross class copy, this likely leads to mixing
  729. // of NEON and VFP code and should be therefore penalized.
  730. if (ValTy->isVectorTy() &&
  731. ValTy->getScalarSizeInBits() <= 32)
  732. return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U);
  733. }
  734. if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement ||
  735. Opcode == Instruction::ExtractElement)) {
  736. // We say MVE moves costs at least the MVEVectorCostFactor, even though
  737. // they are scalar instructions. This helps prevent mixing scalar and
  738. // vector, to prevent vectorising where we end up just scalarising the
  739. // result anyway.
  740. return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index),
  741. ST->getMVEVectorCostFactor()) *
  742. cast<FixedVectorType>(ValTy)->getNumElements() / 2;
  743. }
  744. return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
  745. }
  746. int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
  747. CmpInst::Predicate VecPred,
  748. TTI::TargetCostKind CostKind,
  749. const Instruction *I) {
  750. int ISD = TLI->InstructionOpcodeToISD(Opcode);
  751. // Thumb scalar code size cost for select.
  752. if (CostKind == TTI::TCK_CodeSize && ISD == ISD::SELECT &&
  753. ST->isThumb() && !ValTy->isVectorTy()) {
  754. // Assume expensive structs.
  755. if (TLI->getValueType(DL, ValTy, true) == MVT::Other)
  756. return TTI::TCC_Expensive;
  757. // Select costs can vary because they:
  758. // - may require one or more conditional mov (including an IT),
  759. // - can't operate directly on immediates,
  760. // - require live flags, which we can't copy around easily.
  761. int Cost = TLI->getTypeLegalizationCost(DL, ValTy).first;
  762. // Possible IT instruction for Thumb2, or more for Thumb1.
  763. ++Cost;
  764. // i1 values may need rematerialising by using mov immediates and/or
  765. // flag setting instructions.
  766. if (ValTy->isIntegerTy(1))
  767. ++Cost;
  768. return Cost;
  769. }
  770. // On NEON a vector select gets lowered to vbsl.
  771. if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT && CondTy) {
  772. // Lowering of some vector selects is currently far from perfect.
  773. static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
  774. { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
  775. { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
  776. { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
  777. };
  778. EVT SelCondTy = TLI->getValueType(DL, CondTy);
  779. EVT SelValTy = TLI->getValueType(DL, ValTy);
  780. if (SelCondTy.isSimple() && SelValTy.isSimple()) {
  781. if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
  782. SelCondTy.getSimpleVT(),
  783. SelValTy.getSimpleVT()))
  784. return Entry->Cost;
  785. }
  786. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
  787. return LT.first;
  788. }
  789. // Default to cheap (throughput/size of 1 instruction) but adjust throughput
  790. // for "multiple beats" potentially needed by MVE instructions.
  791. int BaseCost = 1;
  792. if (CostKind != TTI::TCK_CodeSize && ST->hasMVEIntegerOps() &&
  793. ValTy->isVectorTy())
  794. BaseCost = ST->getMVEVectorCostFactor();
  795. return BaseCost *
  796. BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
  797. }
  798. int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
  799. const SCEV *Ptr) {
  800. // Address computations in vectorized code with non-consecutive addresses will
  801. // likely result in more instructions compared to scalar code where the
  802. // computation can more often be merged into the index mode. The resulting
  803. // extra micro-ops can significantly decrease throughput.
  804. unsigned NumVectorInstToHideOverhead = 10;
  805. int MaxMergeDistance = 64;
  806. if (ST->hasNEON()) {
  807. if (Ty->isVectorTy() && SE &&
  808. !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
  809. return NumVectorInstToHideOverhead;
  810. // In many cases the address computation is not merged into the instruction
  811. // addressing mode.
  812. return 1;
  813. }
  814. return BaseT::getAddressComputationCost(Ty, SE, Ptr);
  815. }
  816. bool ARMTTIImpl::isProfitableLSRChainElement(Instruction *I) {
  817. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  818. // If a VCTP is part of a chain, it's already profitable and shouldn't be
  819. // optimized, else LSR may block tail-predication.
  820. switch (II->getIntrinsicID()) {
  821. case Intrinsic::arm_mve_vctp8:
  822. case Intrinsic::arm_mve_vctp16:
  823. case Intrinsic::arm_mve_vctp32:
  824. case Intrinsic::arm_mve_vctp64:
  825. return true;
  826. default:
  827. break;
  828. }
  829. }
  830. return false;
  831. }
  832. bool ARMTTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) {
  833. if (!EnableMaskedLoadStores || !ST->hasMVEIntegerOps())
  834. return false;
  835. if (auto *VecTy = dyn_cast<FixedVectorType>(DataTy)) {
  836. // Don't support v2i1 yet.
  837. if (VecTy->getNumElements() == 2)
  838. return false;
  839. // We don't support extending fp types.
  840. unsigned VecWidth = DataTy->getPrimitiveSizeInBits();
  841. if (VecWidth != 128 && VecTy->getElementType()->isFloatingPointTy())
  842. return false;
  843. }
  844. unsigned EltWidth = DataTy->getScalarSizeInBits();
  845. return (EltWidth == 32 && Alignment >= 4) ||
  846. (EltWidth == 16 && Alignment >= 2) || (EltWidth == 8);
  847. }
  848. bool ARMTTIImpl::isLegalMaskedGather(Type *Ty, Align Alignment) {
  849. if (!EnableMaskedGatherScatters || !ST->hasMVEIntegerOps())
  850. return false;
  851. // This method is called in 2 places:
  852. // - from the vectorizer with a scalar type, in which case we need to get
  853. // this as good as we can with the limited info we have (and rely on the cost
  854. // model for the rest).
  855. // - from the masked intrinsic lowering pass with the actual vector type.
  856. // For MVE, we have a custom lowering pass that will already have custom
  857. // legalised any gathers that we can to MVE intrinsics, and want to expand all
  858. // the rest. The pass runs before the masked intrinsic lowering pass, so if we
  859. // are here, we know we want to expand.
  860. if (isa<VectorType>(Ty))
  861. return false;
  862. unsigned EltWidth = Ty->getScalarSizeInBits();
  863. return ((EltWidth == 32 && Alignment >= 4) ||
  864. (EltWidth == 16 && Alignment >= 2) || EltWidth == 8);
  865. }
  866. /// Given a memcpy/memset/memmove instruction, return the number of memory
  867. /// operations performed, via querying findOptimalMemOpLowering. Returns -1 if a
  868. /// call is used.
  869. int ARMTTIImpl::getNumMemOps(const IntrinsicInst *I) const {
  870. MemOp MOp;
  871. unsigned DstAddrSpace = ~0u;
  872. unsigned SrcAddrSpace = ~0u;
  873. const Function *F = I->getParent()->getParent();
  874. if (const auto *MC = dyn_cast<MemTransferInst>(I)) {
  875. ConstantInt *C = dyn_cast<ConstantInt>(MC->getLength());
  876. // If 'size' is not a constant, a library call will be generated.
  877. if (!C)
  878. return -1;
  879. const unsigned Size = C->getValue().getZExtValue();
  880. const Align DstAlign = *MC->getDestAlign();
  881. const Align SrcAlign = *MC->getSourceAlign();
  882. MOp = MemOp::Copy(Size, /*DstAlignCanChange*/ false, DstAlign, SrcAlign,
  883. /*IsVolatile*/ false);
  884. DstAddrSpace = MC->getDestAddressSpace();
  885. SrcAddrSpace = MC->getSourceAddressSpace();
  886. }
  887. else if (const auto *MS = dyn_cast<MemSetInst>(I)) {
  888. ConstantInt *C = dyn_cast<ConstantInt>(MS->getLength());
  889. // If 'size' is not a constant, a library call will be generated.
  890. if (!C)
  891. return -1;
  892. const unsigned Size = C->getValue().getZExtValue();
  893. const Align DstAlign = *MS->getDestAlign();
  894. MOp = MemOp::Set(Size, /*DstAlignCanChange*/ false, DstAlign,
  895. /*IsZeroMemset*/ false, /*IsVolatile*/ false);
  896. DstAddrSpace = MS->getDestAddressSpace();
  897. }
  898. else
  899. llvm_unreachable("Expected a memcpy/move or memset!");
  900. unsigned Limit, Factor = 2;
  901. switch(I->getIntrinsicID()) {
  902. case Intrinsic::memcpy:
  903. Limit = TLI->getMaxStoresPerMemcpy(F->hasMinSize());
  904. break;
  905. case Intrinsic::memmove:
  906. Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize());
  907. break;
  908. case Intrinsic::memset:
  909. Limit = TLI->getMaxStoresPerMemset(F->hasMinSize());
  910. Factor = 1;
  911. break;
  912. default:
  913. llvm_unreachable("Expected a memcpy/move or memset!");
  914. }
  915. // MemOps will be poplulated with a list of data types that needs to be
  916. // loaded and stored. That's why we multiply the number of elements by 2 to
  917. // get the cost for this memcpy.
  918. std::vector<EVT> MemOps;
  919. if (getTLI()->findOptimalMemOpLowering(
  920. MemOps, Limit, MOp, DstAddrSpace,
  921. SrcAddrSpace, F->getAttributes()))
  922. return MemOps.size() * Factor;
  923. // If we can't find an optimal memop lowering, return the default cost
  924. return -1;
  925. }
  926. int ARMTTIImpl::getMemcpyCost(const Instruction *I) {
  927. int NumOps = getNumMemOps(cast<IntrinsicInst>(I));
  928. // To model the cost of a library call, we assume 1 for the call, and
  929. // 3 for the argument setup.
  930. if (NumOps == -1)
  931. return 4;
  932. return NumOps;
  933. }
  934. int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
  935. int Index, VectorType *SubTp) {
  936. if (ST->hasNEON()) {
  937. if (Kind == TTI::SK_Broadcast) {
  938. static const CostTblEntry NEONDupTbl[] = {
  939. // VDUP handles these cases.
  940. {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
  941. {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
  942. {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
  943. {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
  944. {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
  945. {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
  946. {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
  947. {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
  948. {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
  949. {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
  950. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
  951. if (const auto *Entry =
  952. CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second))
  953. return LT.first * Entry->Cost;
  954. }
  955. if (Kind == TTI::SK_Reverse) {
  956. static const CostTblEntry NEONShuffleTbl[] = {
  957. // Reverse shuffle cost one instruction if we are shuffling within a
  958. // double word (vrev) or two if we shuffle a quad word (vrev, vext).
  959. {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
  960. {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
  961. {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
  962. {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
  963. {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
  964. {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
  965. {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
  966. {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
  967. {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
  968. {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
  969. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
  970. if (const auto *Entry =
  971. CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second))
  972. return LT.first * Entry->Cost;
  973. }
  974. if (Kind == TTI::SK_Select) {
  975. static const CostTblEntry NEONSelShuffleTbl[] = {
  976. // Select shuffle cost table for ARM. Cost is the number of
  977. // instructions
  978. // required to create the shuffled vector.
  979. {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
  980. {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
  981. {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
  982. {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
  983. {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
  984. {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
  985. {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
  986. {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
  987. {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
  988. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
  989. if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
  990. ISD::VECTOR_SHUFFLE, LT.second))
  991. return LT.first * Entry->Cost;
  992. }
  993. }
  994. if (ST->hasMVEIntegerOps()) {
  995. if (Kind == TTI::SK_Broadcast) {
  996. static const CostTblEntry MVEDupTbl[] = {
  997. // VDUP handles these cases.
  998. {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
  999. {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
  1000. {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1},
  1001. {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
  1002. {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}};
  1003. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
  1004. if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE,
  1005. LT.second))
  1006. return LT.first * Entry->Cost * ST->getMVEVectorCostFactor();
  1007. }
  1008. }
  1009. int BaseCost = ST->hasMVEIntegerOps() && Tp->isVectorTy()
  1010. ? ST->getMVEVectorCostFactor()
  1011. : 1;
  1012. return BaseCost * BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
  1013. }
  1014. int ARMTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
  1015. TTI::TargetCostKind CostKind,
  1016. TTI::OperandValueKind Op1Info,
  1017. TTI::OperandValueKind Op2Info,
  1018. TTI::OperandValueProperties Opd1PropInfo,
  1019. TTI::OperandValueProperties Opd2PropInfo,
  1020. ArrayRef<const Value *> Args,
  1021. const Instruction *CxtI) {
  1022. int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
  1023. if (ST->isThumb() && CostKind == TTI::TCK_CodeSize && Ty->isIntegerTy(1)) {
  1024. // Make operations on i1 relatively expensive as this often involves
  1025. // combining predicates. AND and XOR should be easier to handle with IT
  1026. // blocks.
  1027. switch (ISDOpcode) {
  1028. default:
  1029. break;
  1030. case ISD::AND:
  1031. case ISD::XOR:
  1032. return 2;
  1033. case ISD::OR:
  1034. return 3;
  1035. }
  1036. }
  1037. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
  1038. if (ST->hasNEON()) {
  1039. const unsigned FunctionCallDivCost = 20;
  1040. const unsigned ReciprocalDivCost = 10;
  1041. static const CostTblEntry CostTbl[] = {
  1042. // Division.
  1043. // These costs are somewhat random. Choose a cost of 20 to indicate that
  1044. // vectorizing devision (added function call) is going to be very expensive.
  1045. // Double registers types.
  1046. { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
  1047. { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
  1048. { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
  1049. { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
  1050. { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
  1051. { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
  1052. { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
  1053. { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
  1054. { ISD::SDIV, MVT::v4i16, ReciprocalDivCost},
  1055. { ISD::UDIV, MVT::v4i16, ReciprocalDivCost},
  1056. { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
  1057. { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
  1058. { ISD::SDIV, MVT::v8i8, ReciprocalDivCost},
  1059. { ISD::UDIV, MVT::v8i8, ReciprocalDivCost},
  1060. { ISD::SREM, MVT::v8i8, 8 * FunctionCallDivCost},
  1061. { ISD::UREM, MVT::v8i8, 8 * FunctionCallDivCost},
  1062. // Quad register types.
  1063. { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
  1064. { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
  1065. { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
  1066. { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
  1067. { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
  1068. { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
  1069. { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
  1070. { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
  1071. { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
  1072. { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
  1073. { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
  1074. { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
  1075. { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
  1076. { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
  1077. { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
  1078. { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
  1079. // Multiplication.
  1080. };
  1081. if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
  1082. return LT.first * Entry->Cost;
  1083. int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
  1084. Op2Info,
  1085. Opd1PropInfo, Opd2PropInfo);
  1086. // This is somewhat of a hack. The problem that we are facing is that SROA
  1087. // creates a sequence of shift, and, or instructions to construct values.
  1088. // These sequences are recognized by the ISel and have zero-cost. Not so for
  1089. // the vectorized code. Because we have support for v2i64 but not i64 those
  1090. // sequences look particularly beneficial to vectorize.
  1091. // To work around this we increase the cost of v2i64 operations to make them
  1092. // seem less beneficial.
  1093. if (LT.second == MVT::v2i64 &&
  1094. Op2Info == TargetTransformInfo::OK_UniformConstantValue)
  1095. Cost += 4;
  1096. return Cost;
  1097. }
  1098. // If this operation is a shift on arm/thumb2, it might well be folded into
  1099. // the following instruction, hence having a cost of 0.
  1100. auto LooksLikeAFreeShift = [&]() {
  1101. if (ST->isThumb1Only() || Ty->isVectorTy())
  1102. return false;
  1103. if (!CxtI || !CxtI->hasOneUse() || !CxtI->isShift())
  1104. return false;
  1105. if (Op2Info != TargetTransformInfo::OK_UniformConstantValue)
  1106. return false;
  1107. // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB
  1108. switch (cast<Instruction>(CxtI->user_back())->getOpcode()) {
  1109. case Instruction::Add:
  1110. case Instruction::Sub:
  1111. case Instruction::And:
  1112. case Instruction::Xor:
  1113. case Instruction::Or:
  1114. case Instruction::ICmp:
  1115. return true;
  1116. default:
  1117. return false;
  1118. }
  1119. };
  1120. if (LooksLikeAFreeShift())
  1121. return 0;
  1122. // Default to cheap (throughput/size of 1 instruction) but adjust throughput
  1123. // for "multiple beats" potentially needed by MVE instructions.
  1124. int BaseCost = 1;
  1125. if (CostKind != TTI::TCK_CodeSize && ST->hasMVEIntegerOps() &&
  1126. Ty->isVectorTy())
  1127. BaseCost = ST->getMVEVectorCostFactor();
  1128. // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost,
  1129. // without treating floats as more expensive that scalars or increasing the
  1130. // costs for custom operations. The results is also multiplied by the
  1131. // MVEVectorCostFactor where appropriate.
  1132. if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second))
  1133. return LT.first * BaseCost;
  1134. // Else this is expand, assume that we need to scalarize this op.
  1135. if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
  1136. unsigned Num = VTy->getNumElements();
  1137. unsigned Cost = getArithmeticInstrCost(Opcode, Ty->getScalarType(),
  1138. CostKind);
  1139. // Return the cost of multiple scalar invocation plus the cost of
  1140. // inserting and extracting the values.
  1141. return BaseT::getScalarizationOverhead(VTy, Args) + Num * Cost;
  1142. }
  1143. return BaseCost;
  1144. }
  1145. int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
  1146. MaybeAlign Alignment, unsigned AddressSpace,
  1147. TTI::TargetCostKind CostKind,
  1148. const Instruction *I) {
  1149. // TODO: Handle other cost kinds.
  1150. if (CostKind != TTI::TCK_RecipThroughput)
  1151. return 1;
  1152. // Type legalization can't handle structs
  1153. if (TLI->getValueType(DL, Src, true) == MVT::Other)
  1154. return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
  1155. CostKind);
  1156. if (ST->hasNEON() && Src->isVectorTy() &&
  1157. (Alignment && *Alignment != Align(16)) &&
  1158. cast<VectorType>(Src)->getElementType()->isDoubleTy()) {
  1159. // Unaligned loads/stores are extremely inefficient.
  1160. // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
  1161. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
  1162. return LT.first * 4;
  1163. }
  1164. // MVE can optimize a fpext(load(4xhalf)) using an extending integer load.
  1165. // Same for stores.
  1166. if (ST->hasMVEFloatOps() && isa<FixedVectorType>(Src) && I &&
  1167. ((Opcode == Instruction::Load && I->hasOneUse() &&
  1168. isa<FPExtInst>(*I->user_begin())) ||
  1169. (Opcode == Instruction::Store && isa<FPTruncInst>(I->getOperand(0))))) {
  1170. FixedVectorType *SrcVTy = cast<FixedVectorType>(Src);
  1171. Type *DstTy =
  1172. Opcode == Instruction::Load
  1173. ? (*I->user_begin())->getType()
  1174. : cast<Instruction>(I->getOperand(0))->getOperand(0)->getType();
  1175. if (SrcVTy->getNumElements() == 4 && SrcVTy->getScalarType()->isHalfTy() &&
  1176. DstTy->getScalarType()->isFloatTy())
  1177. return ST->getMVEVectorCostFactor();
  1178. }
  1179. int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
  1180. ? ST->getMVEVectorCostFactor()
  1181. : 1;
  1182. return BaseCost * BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
  1183. CostKind, I);
  1184. }
  1185. unsigned ARMTTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
  1186. Align Alignment,
  1187. unsigned AddressSpace,
  1188. TTI::TargetCostKind CostKind) {
  1189. if (ST->hasMVEIntegerOps()) {
  1190. if (Opcode == Instruction::Load && isLegalMaskedLoad(Src, Alignment))
  1191. return ST->getMVEVectorCostFactor();
  1192. if (Opcode == Instruction::Store && isLegalMaskedStore(Src, Alignment))
  1193. return ST->getMVEVectorCostFactor();
  1194. }
  1195. if (!isa<FixedVectorType>(Src))
  1196. return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
  1197. CostKind);
  1198. // Scalar cost, which is currently very high due to the efficiency of the
  1199. // generated code.
  1200. return cast<FixedVectorType>(Src)->getNumElements() * 8;
  1201. }
  1202. int ARMTTIImpl::getInterleavedMemoryOpCost(
  1203. unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
  1204. Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
  1205. bool UseMaskForCond, bool UseMaskForGaps) {
  1206. assert(Factor >= 2 && "Invalid interleave factor");
  1207. assert(isa<VectorType>(VecTy) && "Expect a vector type");
  1208. // vldN/vstN doesn't support vector types of i64/f64 element.
  1209. bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
  1210. if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
  1211. !UseMaskForCond && !UseMaskForGaps) {
  1212. unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
  1213. auto *SubVecTy =
  1214. FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
  1215. // vldN/vstN only support legal vector types of size 64 or 128 in bits.
  1216. // Accesses having vector types that are a multiple of 128 bits can be
  1217. // matched to more than one vldN/vstN instruction.
  1218. int BaseCost = ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor() : 1;
  1219. if (NumElts % Factor == 0 &&
  1220. TLI->isLegalInterleavedAccessType(Factor, SubVecTy, DL))
  1221. return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL);
  1222. // Some smaller than legal interleaved patterns are cheap as we can make
  1223. // use of the vmovn or vrev patterns to interleave a standard load. This is
  1224. // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is
  1225. // promoted differently). The cost of 2 here is then a load and vrev or
  1226. // vmovn.
  1227. if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 &&
  1228. VecTy->isIntOrIntVectorTy() &&
  1229. DL.getTypeSizeInBits(SubVecTy).getFixedSize() <= 64)
  1230. return 2 * BaseCost;
  1231. }
  1232. return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
  1233. Alignment, AddressSpace, CostKind,
  1234. UseMaskForCond, UseMaskForGaps);
  1235. }
  1236. unsigned ARMTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
  1237. const Value *Ptr, bool VariableMask,
  1238. Align Alignment,
  1239. TTI::TargetCostKind CostKind,
  1240. const Instruction *I) {
  1241. using namespace PatternMatch;
  1242. if (!ST->hasMVEIntegerOps() || !EnableMaskedGatherScatters)
  1243. return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
  1244. Alignment, CostKind, I);
  1245. assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!");
  1246. auto *VTy = cast<FixedVectorType>(DataTy);
  1247. // TODO: Splitting, once we do that.
  1248. unsigned NumElems = VTy->getNumElements();
  1249. unsigned EltSize = VTy->getScalarSizeInBits();
  1250. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, DataTy);
  1251. // For now, it is assumed that for the MVE gather instructions the loads are
  1252. // all effectively serialised. This means the cost is the scalar cost
  1253. // multiplied by the number of elements being loaded. This is possibly very
  1254. // conservative, but even so we still end up vectorising loops because the
  1255. // cost per iteration for many loops is lower than for scalar loops.
  1256. unsigned VectorCost = NumElems * LT.first * ST->getMVEVectorCostFactor();
  1257. // The scalarization cost should be a lot higher. We use the number of vector
  1258. // elements plus the scalarization overhead.
  1259. unsigned ScalarCost =
  1260. NumElems * LT.first + BaseT::getScalarizationOverhead(VTy, {});
  1261. if (EltSize < 8 || Alignment < EltSize / 8)
  1262. return ScalarCost;
  1263. unsigned ExtSize = EltSize;
  1264. // Check whether there's a single user that asks for an extended type
  1265. if (I != nullptr) {
  1266. // Dependent of the caller of this function, a gather instruction will
  1267. // either have opcode Instruction::Load or be a call to the masked_gather
  1268. // intrinsic
  1269. if ((I->getOpcode() == Instruction::Load ||
  1270. match(I, m_Intrinsic<Intrinsic::masked_gather>())) &&
  1271. I->hasOneUse()) {
  1272. const User *Us = *I->users().begin();
  1273. if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) {
  1274. // only allow valid type combinations
  1275. unsigned TypeSize =
  1276. cast<Instruction>(Us)->getType()->getScalarSizeInBits();
  1277. if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) ||
  1278. (TypeSize == 16 && EltSize == 8)) &&
  1279. TypeSize * NumElems == 128) {
  1280. ExtSize = TypeSize;
  1281. }
  1282. }
  1283. }
  1284. // Check whether the input data needs to be truncated
  1285. TruncInst *T;
  1286. if ((I->getOpcode() == Instruction::Store ||
  1287. match(I, m_Intrinsic<Intrinsic::masked_scatter>())) &&
  1288. (T = dyn_cast<TruncInst>(I->getOperand(0)))) {
  1289. // Only allow valid type combinations
  1290. unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits();
  1291. if (((EltSize == 16 && TypeSize == 32) ||
  1292. (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) &&
  1293. TypeSize * NumElems == 128)
  1294. ExtSize = TypeSize;
  1295. }
  1296. }
  1297. if (ExtSize * NumElems != 128 || NumElems < 4)
  1298. return ScalarCost;
  1299. // Any (aligned) i32 gather will not need to be scalarised.
  1300. if (ExtSize == 32)
  1301. return VectorCost;
  1302. // For smaller types, we need to ensure that the gep's inputs are correctly
  1303. // extended from a small enough value. Other sizes (including i64) are
  1304. // scalarized for now.
  1305. if (ExtSize != 8 && ExtSize != 16)
  1306. return ScalarCost;
  1307. if (const auto *BC = dyn_cast<BitCastInst>(Ptr))
  1308. Ptr = BC->getOperand(0);
  1309. if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
  1310. if (GEP->getNumOperands() != 2)
  1311. return ScalarCost;
  1312. unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType());
  1313. // Scale needs to be correct (which is only relevant for i16s).
  1314. if (Scale != 1 && Scale * 8 != ExtSize)
  1315. return ScalarCost;
  1316. // And we need to zext (not sext) the indexes from a small enough type.
  1317. if (const auto *ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) {
  1318. if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize)
  1319. return VectorCost;
  1320. }
  1321. return ScalarCost;
  1322. }
  1323. return ScalarCost;
  1324. }
  1325. int ARMTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy,
  1326. bool IsPairwiseForm,
  1327. TTI::TargetCostKind CostKind) {
  1328. EVT ValVT = TLI->getValueType(DL, ValTy);
  1329. int ISD = TLI->InstructionOpcodeToISD(Opcode);
  1330. if (!ST->hasMVEIntegerOps() || !ValVT.isSimple() || ISD != ISD::ADD)
  1331. return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
  1332. CostKind);
  1333. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
  1334. static const CostTblEntry CostTblAdd[]{
  1335. {ISD::ADD, MVT::v16i8, 1},
  1336. {ISD::ADD, MVT::v8i16, 1},
  1337. {ISD::ADD, MVT::v4i32, 1},
  1338. };
  1339. if (const auto *Entry = CostTableLookup(CostTblAdd, ISD, LT.second))
  1340. return Entry->Cost * ST->getMVEVectorCostFactor() * LT.first;
  1341. return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
  1342. CostKind);
  1343. }
  1344. InstructionCost
  1345. ARMTTIImpl::getExtendedAddReductionCost(bool IsMLA, bool IsUnsigned,
  1346. Type *ResTy, VectorType *ValTy,
  1347. TTI::TargetCostKind CostKind) {
  1348. EVT ValVT = TLI->getValueType(DL, ValTy);
  1349. EVT ResVT = TLI->getValueType(DL, ResTy);
  1350. if (ST->hasMVEIntegerOps() && ValVT.isSimple() && ResVT.isSimple()) {
  1351. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
  1352. if ((LT.second == MVT::v16i8 && ResVT.getSizeInBits() <= 32) ||
  1353. (LT.second == MVT::v8i16 &&
  1354. ResVT.getSizeInBits() <= (IsMLA ? 64 : 32)) ||
  1355. (LT.second == MVT::v4i32 && ResVT.getSizeInBits() <= 64))
  1356. return ST->getMVEVectorCostFactor() * LT.first;
  1357. }
  1358. return BaseT::getExtendedAddReductionCost(IsMLA, IsUnsigned, ResTy, ValTy,
  1359. CostKind);
  1360. }
  1361. int ARMTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
  1362. TTI::TargetCostKind CostKind) {
  1363. switch (ICA.getID()) {
  1364. case Intrinsic::get_active_lane_mask:
  1365. // Currently we make a somewhat optimistic assumption that
  1366. // active_lane_mask's are always free. In reality it may be freely folded
  1367. // into a tail predicated loop, expanded into a VCPT or expanded into a lot
  1368. // of add/icmp code. We may need to improve this in the future, but being
  1369. // able to detect if it is free or not involves looking at a lot of other
  1370. // code. We currently assume that the vectorizer inserted these, and knew
  1371. // what it was doing in adding one.
  1372. if (ST->hasMVEIntegerOps())
  1373. return 0;
  1374. break;
  1375. case Intrinsic::sadd_sat:
  1376. case Intrinsic::ssub_sat:
  1377. case Intrinsic::uadd_sat:
  1378. case Intrinsic::usub_sat: {
  1379. if (!ST->hasMVEIntegerOps())
  1380. break;
  1381. // Get the Return type, either directly of from ICA.ReturnType and ICA.VF.
  1382. Type *VT = ICA.getReturnType();
  1383. if (!VT->isVectorTy() && !ICA.getVectorFactor().isScalar())
  1384. VT = VectorType::get(VT, ICA.getVectorFactor());
  1385. std::pair<int, MVT> LT =
  1386. TLI->getTypeLegalizationCost(DL, VT);
  1387. if (LT.second == MVT::v4i32 || LT.second == MVT::v8i16 ||
  1388. LT.second == MVT::v16i8) {
  1389. // This is a base cost of 1 for the vadd, plus 3 extract shifts if we
  1390. // need to extend the type, as it uses shr(qadd(shl, shl)).
  1391. unsigned Instrs = LT.second.getScalarSizeInBits() ==
  1392. ICA.getReturnType()->getScalarSizeInBits()
  1393. ? 1
  1394. : 4;
  1395. return LT.first * ST->getMVEVectorCostFactor() * Instrs;
  1396. }
  1397. break;
  1398. }
  1399. }
  1400. return BaseT::getIntrinsicInstrCost(ICA, CostKind);
  1401. }
  1402. bool ARMTTIImpl::isLoweredToCall(const Function *F) {
  1403. if (!F->isIntrinsic())
  1404. BaseT::isLoweredToCall(F);
  1405. // Assume all Arm-specific intrinsics map to an instruction.
  1406. if (F->getName().startswith("llvm.arm"))
  1407. return false;
  1408. switch (F->getIntrinsicID()) {
  1409. default: break;
  1410. case Intrinsic::powi:
  1411. case Intrinsic::sin:
  1412. case Intrinsic::cos:
  1413. case Intrinsic::pow:
  1414. case Intrinsic::log:
  1415. case Intrinsic::log10:
  1416. case Intrinsic::log2:
  1417. case Intrinsic::exp:
  1418. case Intrinsic::exp2:
  1419. return true;
  1420. case Intrinsic::sqrt:
  1421. case Intrinsic::fabs:
  1422. case Intrinsic::copysign:
  1423. case Intrinsic::floor:
  1424. case Intrinsic::ceil:
  1425. case Intrinsic::trunc:
  1426. case Intrinsic::rint:
  1427. case Intrinsic::nearbyint:
  1428. case Intrinsic::round:
  1429. case Intrinsic::canonicalize:
  1430. case Intrinsic::lround:
  1431. case Intrinsic::llround:
  1432. case Intrinsic::lrint:
  1433. case Intrinsic::llrint:
  1434. if (F->getReturnType()->isDoubleTy() && !ST->hasFP64())
  1435. return true;
  1436. if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16())
  1437. return true;
  1438. // Some operations can be handled by vector instructions and assume
  1439. // unsupported vectors will be expanded into supported scalar ones.
  1440. // TODO Handle scalar operations properly.
  1441. return !ST->hasFPARMv8Base() && !ST->hasVFP2Base();
  1442. case Intrinsic::masked_store:
  1443. case Intrinsic::masked_load:
  1444. case Intrinsic::masked_gather:
  1445. case Intrinsic::masked_scatter:
  1446. return !ST->hasMVEIntegerOps();
  1447. case Intrinsic::sadd_with_overflow:
  1448. case Intrinsic::uadd_with_overflow:
  1449. case Intrinsic::ssub_with_overflow:
  1450. case Intrinsic::usub_with_overflow:
  1451. case Intrinsic::sadd_sat:
  1452. case Intrinsic::uadd_sat:
  1453. case Intrinsic::ssub_sat:
  1454. case Intrinsic::usub_sat:
  1455. return false;
  1456. }
  1457. return BaseT::isLoweredToCall(F);
  1458. }
  1459. bool ARMTTIImpl::maybeLoweredToCall(Instruction &I) {
  1460. unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode());
  1461. EVT VT = TLI->getValueType(DL, I.getType(), true);
  1462. if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall)
  1463. return true;
  1464. // Check if an intrinsic will be lowered to a call and assume that any
  1465. // other CallInst will generate a bl.
  1466. if (auto *Call = dyn_cast<CallInst>(&I)) {
  1467. if (auto *II = dyn_cast<IntrinsicInst>(Call)) {
  1468. switch(II->getIntrinsicID()) {
  1469. case Intrinsic::memcpy:
  1470. case Intrinsic::memset:
  1471. case Intrinsic::memmove:
  1472. return getNumMemOps(II) == -1;
  1473. default:
  1474. if (const Function *F = Call->getCalledFunction())
  1475. return isLoweredToCall(F);
  1476. }
  1477. }
  1478. return true;
  1479. }
  1480. // FPv5 provides conversions between integer, double-precision,
  1481. // single-precision, and half-precision formats.
  1482. switch (I.getOpcode()) {
  1483. default:
  1484. break;
  1485. case Instruction::FPToSI:
  1486. case Instruction::FPToUI:
  1487. case Instruction::SIToFP:
  1488. case Instruction::UIToFP:
  1489. case Instruction::FPTrunc:
  1490. case Instruction::FPExt:
  1491. return !ST->hasFPARMv8Base();
  1492. }
  1493. // FIXME: Unfortunately the approach of checking the Operation Action does
  1494. // not catch all cases of Legalization that use library calls. Our
  1495. // Legalization step categorizes some transformations into library calls as
  1496. // Custom, Expand or even Legal when doing type legalization. So for now
  1497. // we have to special case for instance the SDIV of 64bit integers and the
  1498. // use of floating point emulation.
  1499. if (VT.isInteger() && VT.getSizeInBits() >= 64) {
  1500. switch (ISD) {
  1501. default:
  1502. break;
  1503. case ISD::SDIV:
  1504. case ISD::UDIV:
  1505. case ISD::SREM:
  1506. case ISD::UREM:
  1507. case ISD::SDIVREM:
  1508. case ISD::UDIVREM:
  1509. return true;
  1510. }
  1511. }
  1512. // Assume all other non-float operations are supported.
  1513. if (!VT.isFloatingPoint())
  1514. return false;
  1515. // We'll need a library call to handle most floats when using soft.
  1516. if (TLI->useSoftFloat()) {
  1517. switch (I.getOpcode()) {
  1518. default:
  1519. return true;
  1520. case Instruction::Alloca:
  1521. case Instruction::Load:
  1522. case Instruction::Store:
  1523. case Instruction::Select:
  1524. case Instruction::PHI:
  1525. return false;
  1526. }
  1527. }
  1528. // We'll need a libcall to perform double precision operations on a single
  1529. // precision only FPU.
  1530. if (I.getType()->isDoubleTy() && !ST->hasFP64())
  1531. return true;
  1532. // Likewise for half precision arithmetic.
  1533. if (I.getType()->isHalfTy() && !ST->hasFullFP16())
  1534. return true;
  1535. return false;
  1536. }
  1537. bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
  1538. AssumptionCache &AC,
  1539. TargetLibraryInfo *LibInfo,
  1540. HardwareLoopInfo &HWLoopInfo) {
  1541. // Low-overhead branches are only supported in the 'low-overhead branch'
  1542. // extension of v8.1-m.
  1543. if (!ST->hasLOB() || DisableLowOverheadLoops) {
  1544. LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n");
  1545. return false;
  1546. }
  1547. if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
  1548. LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n");
  1549. return false;
  1550. }
  1551. const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
  1552. if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
  1553. LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n");
  1554. return false;
  1555. }
  1556. const SCEV *TripCountSCEV =
  1557. SE.getAddExpr(BackedgeTakenCount,
  1558. SE.getOne(BackedgeTakenCount->getType()));
  1559. // We need to store the trip count in LR, a 32-bit register.
  1560. if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) {
  1561. LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n");
  1562. return false;
  1563. }
  1564. // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little
  1565. // point in generating a hardware loop if that's going to happen.
  1566. auto IsHardwareLoopIntrinsic = [](Instruction &I) {
  1567. if (auto *Call = dyn_cast<IntrinsicInst>(&I)) {
  1568. switch (Call->getIntrinsicID()) {
  1569. default:
  1570. break;
  1571. case Intrinsic::start_loop_iterations:
  1572. case Intrinsic::test_set_loop_iterations:
  1573. case Intrinsic::loop_decrement:
  1574. case Intrinsic::loop_decrement_reg:
  1575. return true;
  1576. }
  1577. }
  1578. return false;
  1579. };
  1580. // Scan the instructions to see if there's any that we know will turn into a
  1581. // call or if this loop is already a low-overhead loop or will become a tail
  1582. // predicated loop.
  1583. bool IsTailPredLoop = false;
  1584. auto ScanLoop = [&](Loop *L) {
  1585. for (auto *BB : L->getBlocks()) {
  1586. for (auto &I : *BB) {
  1587. if (maybeLoweredToCall(I) || IsHardwareLoopIntrinsic(I) ||
  1588. isa<InlineAsm>(I)) {
  1589. LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n");
  1590. return false;
  1591. }
  1592. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  1593. IsTailPredLoop |=
  1594. II->getIntrinsicID() == Intrinsic::get_active_lane_mask ||
  1595. II->getIntrinsicID() == Intrinsic::arm_mve_vctp8 ||
  1596. II->getIntrinsicID() == Intrinsic::arm_mve_vctp16 ||
  1597. II->getIntrinsicID() == Intrinsic::arm_mve_vctp32 ||
  1598. II->getIntrinsicID() == Intrinsic::arm_mve_vctp64;
  1599. }
  1600. }
  1601. return true;
  1602. };
  1603. // Visit inner loops.
  1604. for (auto Inner : *L)
  1605. if (!ScanLoop(Inner))
  1606. return false;
  1607. if (!ScanLoop(L))
  1608. return false;
  1609. // TODO: Check whether the trip count calculation is expensive. If L is the
  1610. // inner loop but we know it has a low trip count, calculating that trip
  1611. // count (in the parent loop) may be detrimental.
  1612. LLVMContext &C = L->getHeader()->getContext();
  1613. HWLoopInfo.CounterInReg = true;
  1614. HWLoopInfo.IsNestingLegal = false;
  1615. HWLoopInfo.PerformEntryTest = AllowWLSLoops && !IsTailPredLoop;
  1616. HWLoopInfo.CountType = Type::getInt32Ty(C);
  1617. HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
  1618. return true;
  1619. }
  1620. static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) {
  1621. // We don't allow icmp's, and because we only look at single block loops,
  1622. // we simply count the icmps, i.e. there should only be 1 for the backedge.
  1623. if (isa<ICmpInst>(&I) && ++ICmpCount > 1)
  1624. return false;
  1625. if (isa<FCmpInst>(&I))
  1626. return false;
  1627. // We could allow extending/narrowing FP loads/stores, but codegen is
  1628. // too inefficient so reject this for now.
  1629. if (isa<FPExtInst>(&I) || isa<FPTruncInst>(&I))
  1630. return false;
  1631. // Extends have to be extending-loads
  1632. if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) )
  1633. if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0)))
  1634. return false;
  1635. // Truncs have to be narrowing-stores
  1636. if (isa<TruncInst>(&I) )
  1637. if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin()))
  1638. return false;
  1639. return true;
  1640. }
  1641. // To set up a tail-predicated loop, we need to know the total number of
  1642. // elements processed by that loop. Thus, we need to determine the element
  1643. // size and:
  1644. // 1) it should be uniform for all operations in the vector loop, so we
  1645. // e.g. don't want any widening/narrowing operations.
  1646. // 2) it should be smaller than i64s because we don't have vector operations
  1647. // that work on i64s.
  1648. // 3) we don't want elements to be reversed or shuffled, to make sure the
  1649. // tail-predication masks/predicates the right lanes.
  1650. //
  1651. static bool canTailPredicateLoop(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
  1652. const DataLayout &DL,
  1653. const LoopAccessInfo *LAI) {
  1654. LLVM_DEBUG(dbgs() << "Tail-predication: checking allowed instructions\n");
  1655. // If there are live-out values, it is probably a reduction. We can predicate
  1656. // most reduction operations freely under MVE using a combination of
  1657. // prefer-predicated-reduction-select and inloop reductions. We limit this to
  1658. // floating point and integer reductions, but don't check for operators
  1659. // specifically here. If the value ends up not being a reduction (and so the
  1660. // vectorizer cannot tailfold the loop), we should fall back to standard
  1661. // vectorization automatically.
  1662. SmallVector< Instruction *, 8 > LiveOuts;
  1663. LiveOuts = llvm::findDefsUsedOutsideOfLoop(L);
  1664. bool ReductionsDisabled =
  1665. EnableTailPredication == TailPredication::EnabledNoReductions ||
  1666. EnableTailPredication == TailPredication::ForceEnabledNoReductions;
  1667. for (auto *I : LiveOuts) {
  1668. if (!I->getType()->isIntegerTy() && !I->getType()->isFloatTy() &&
  1669. !I->getType()->isHalfTy()) {
  1670. LLVM_DEBUG(dbgs() << "Don't tail-predicate loop with non-integer/float "
  1671. "live-out value\n");
  1672. return false;
  1673. }
  1674. if (ReductionsDisabled) {
  1675. LLVM_DEBUG(dbgs() << "Reductions not enabled\n");
  1676. return false;
  1677. }
  1678. }
  1679. // Next, check that all instructions can be tail-predicated.
  1680. PredicatedScalarEvolution PSE = LAI->getPSE();
  1681. SmallVector<Instruction *, 16> LoadStores;
  1682. int ICmpCount = 0;
  1683. for (BasicBlock *BB : L->blocks()) {
  1684. for (Instruction &I : BB->instructionsWithoutDebug()) {
  1685. if (isa<PHINode>(&I))
  1686. continue;
  1687. if (!canTailPredicateInstruction(I, ICmpCount)) {
  1688. LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump());
  1689. return false;
  1690. }
  1691. Type *T = I.getType();
  1692. if (T->isPointerTy())
  1693. T = T->getPointerElementType();
  1694. if (T->getScalarSizeInBits() > 32) {
  1695. LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump());
  1696. return false;
  1697. }
  1698. if (isa<StoreInst>(I) || isa<LoadInst>(I)) {
  1699. Value *Ptr = isa<LoadInst>(I) ? I.getOperand(0) : I.getOperand(1);
  1700. int64_t NextStride = getPtrStride(PSE, Ptr, L);
  1701. if (NextStride == 1) {
  1702. // TODO: for now only allow consecutive strides of 1. We could support
  1703. // other strides as long as it is uniform, but let's keep it simple
  1704. // for now.
  1705. continue;
  1706. } else if (NextStride == -1 ||
  1707. (NextStride == 2 && MVEMaxSupportedInterleaveFactor >= 2) ||
  1708. (NextStride == 4 && MVEMaxSupportedInterleaveFactor >= 4)) {
  1709. LLVM_DEBUG(dbgs()
  1710. << "Consecutive strides of 2 found, vld2/vstr2 can't "
  1711. "be tail-predicated\n.");
  1712. return false;
  1713. // TODO: don't tail predicate if there is a reversed load?
  1714. } else if (EnableMaskedGatherScatters) {
  1715. // Gather/scatters do allow loading from arbitrary strides, at
  1716. // least if they are loop invariant.
  1717. // TODO: Loop variant strides should in theory work, too, but
  1718. // this requires further testing.
  1719. const SCEV *PtrScev =
  1720. replaceSymbolicStrideSCEV(PSE, llvm::ValueToValueMap(), Ptr);
  1721. if (auto AR = dyn_cast<SCEVAddRecExpr>(PtrScev)) {
  1722. const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
  1723. if (PSE.getSE()->isLoopInvariant(Step, L))
  1724. continue;
  1725. }
  1726. }
  1727. LLVM_DEBUG(dbgs() << "Bad stride found, can't "
  1728. "tail-predicate\n.");
  1729. return false;
  1730. }
  1731. }
  1732. }
  1733. LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n");
  1734. return true;
  1735. }
  1736. bool ARMTTIImpl::preferPredicateOverEpilogue(Loop *L, LoopInfo *LI,
  1737. ScalarEvolution &SE,
  1738. AssumptionCache &AC,
  1739. TargetLibraryInfo *TLI,
  1740. DominatorTree *DT,
  1741. const LoopAccessInfo *LAI) {
  1742. if (!EnableTailPredication) {
  1743. LLVM_DEBUG(dbgs() << "Tail-predication not enabled.\n");
  1744. return false;
  1745. }
  1746. // Creating a predicated vector loop is the first step for generating a
  1747. // tail-predicated hardware loop, for which we need the MVE masked
  1748. // load/stores instructions:
  1749. if (!ST->hasMVEIntegerOps())
  1750. return false;
  1751. // For now, restrict this to single block loops.
  1752. if (L->getNumBlocks() > 1) {
  1753. LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: not a single block "
  1754. "loop.\n");
  1755. return false;
  1756. }
  1757. assert(L->isInnermost() && "preferPredicateOverEpilogue: inner-loop expected");
  1758. HardwareLoopInfo HWLoopInfo(L);
  1759. if (!HWLoopInfo.canAnalyze(*LI)) {
  1760. LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
  1761. "analyzable.\n");
  1762. return false;
  1763. }
  1764. // This checks if we have the low-overhead branch architecture
  1765. // extension, and if we will create a hardware-loop:
  1766. if (!isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) {
  1767. LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
  1768. "profitable.\n");
  1769. return false;
  1770. }
  1771. if (!HWLoopInfo.isHardwareLoopCandidate(SE, *LI, *DT)) {
  1772. LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
  1773. "a candidate.\n");
  1774. return false;
  1775. }
  1776. return canTailPredicateLoop(L, LI, SE, DL, LAI);
  1777. }
  1778. bool ARMTTIImpl::emitGetActiveLaneMask() const {
  1779. if (!ST->hasMVEIntegerOps() || !EnableTailPredication)
  1780. return false;
  1781. // Intrinsic @llvm.get.active.lane.mask is supported.
  1782. // It is used in the MVETailPredication pass, which requires the number of
  1783. // elements processed by this vector loop to setup the tail-predicated
  1784. // loop.
  1785. return true;
  1786. }
  1787. void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
  1788. TTI::UnrollingPreferences &UP) {
  1789. // Only currently enable these preferences for M-Class cores.
  1790. if (!ST->isMClass())
  1791. return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP);
  1792. // Disable loop unrolling for Oz and Os.
  1793. UP.OptSizeThreshold = 0;
  1794. UP.PartialOptSizeThreshold = 0;
  1795. if (L->getHeader()->getParent()->hasOptSize())
  1796. return;
  1797. // Only enable on Thumb-2 targets.
  1798. if (!ST->isThumb2())
  1799. return;
  1800. SmallVector<BasicBlock*, 4> ExitingBlocks;
  1801. L->getExitingBlocks(ExitingBlocks);
  1802. LLVM_DEBUG(dbgs() << "Loop has:\n"
  1803. << "Blocks: " << L->getNumBlocks() << "\n"
  1804. << "Exit blocks: " << ExitingBlocks.size() << "\n");
  1805. // Only allow another exit other than the latch. This acts as an early exit
  1806. // as it mirrors the profitability calculation of the runtime unroller.
  1807. if (ExitingBlocks.size() > 2)
  1808. return;
  1809. // Limit the CFG of the loop body for targets with a branch predictor.
  1810. // Allowing 4 blocks permits if-then-else diamonds in the body.
  1811. if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
  1812. return;
  1813. // Don't unroll vectorized loops, including the remainder loop
  1814. if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
  1815. return;
  1816. // Scan the loop: don't unroll loops with calls as this could prevent
  1817. // inlining.
  1818. unsigned Cost = 0;
  1819. for (auto *BB : L->getBlocks()) {
  1820. for (auto &I : *BB) {
  1821. // Don't unroll vectorised loop. MVE does not benefit from it as much as
  1822. // scalar code.
  1823. if (I.getType()->isVectorTy())
  1824. return;
  1825. if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
  1826. if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
  1827. if (!isLoweredToCall(F))
  1828. continue;
  1829. }
  1830. return;
  1831. }
  1832. SmallVector<const Value*, 4> Operands(I.operand_values());
  1833. Cost +=
  1834. getUserCost(&I, Operands, TargetTransformInfo::TCK_SizeAndLatency);
  1835. }
  1836. }
  1837. LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
  1838. UP.Partial = true;
  1839. UP.Runtime = true;
  1840. UP.UpperBound = true;
  1841. UP.UnrollRemainder = true;
  1842. UP.DefaultUnrollRuntimeCount = 4;
  1843. UP.UnrollAndJam = true;
  1844. UP.UnrollAndJamInnerLoopThreshold = 60;
  1845. // Force unrolling small loops can be very useful because of the branch
  1846. // taken cost of the backedge.
  1847. if (Cost < 12)
  1848. UP.Force = true;
  1849. }
  1850. void ARMTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
  1851. TTI::PeelingPreferences &PP) {
  1852. BaseT::getPeelingPreferences(L, SE, PP);
  1853. }
  1854. bool ARMTTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
  1855. TTI::ReductionFlags Flags) const {
  1856. return ST->hasMVEIntegerOps();
  1857. }
  1858. bool ARMTTIImpl::preferInLoopReduction(unsigned Opcode, Type *Ty,
  1859. TTI::ReductionFlags Flags) const {
  1860. if (!ST->hasMVEIntegerOps())
  1861. return false;
  1862. unsigned ScalarBits = Ty->getScalarSizeInBits();
  1863. switch (Opcode) {
  1864. case Instruction::Add:
  1865. return ScalarBits <= 64;
  1866. default:
  1867. return false;
  1868. }
  1869. }
  1870. bool ARMTTIImpl::preferPredicatedReductionSelect(
  1871. unsigned Opcode, Type *Ty, TTI::ReductionFlags Flags) const {
  1872. if (!ST->hasMVEIntegerOps())
  1873. return false;
  1874. return true;
  1875. }