LoopVectorizationLegality.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. //===- LoopVectorizationLegality.cpp --------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file provides loop vectorization legality analysis. Original code
  10. // resided in LoopVectorize.cpp for a long time.
  11. //
  12. // At this point, it is implemented as a utility class, not as an analysis
  13. // pass. It should be easy to create an analysis pass around it if there
  14. // is a need (but D45420 needs to happen first).
  15. //
  16. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  17. #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
  18. #include "llvm/Analysis/VectorUtils.h"
  19. #include "llvm/IR/IntrinsicInst.h"
  20. using namespace llvm;
  21. #define LV_NAME "loop-vectorize"
  22. #define DEBUG_TYPE LV_NAME
  23. extern cl::opt<bool> EnableVPlanPredication;
  24. static cl::opt<bool>
  25. EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
  26. cl::desc("Enable if-conversion during vectorization."));
  27. static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
  28. "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
  29. cl::desc("The maximum allowed number of runtime memory checks with a "
  30. "vectorize(enable) pragma."));
  31. static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
  32. "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
  33. cl::desc("The maximum number of SCEV checks allowed."));
  34. static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
  35. "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
  36. cl::desc("The maximum number of SCEV checks allowed with a "
  37. "vectorize(enable) pragma"));
  38. /// Maximum vectorization interleave count.
  39. static const unsigned MaxInterleaveFactor = 16;
  40. namespace llvm {
  41. bool LoopVectorizeHints::Hint::validate(unsigned Val) {
  42. switch (Kind) {
  43. case HK_WIDTH:
  44. return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
  45. case HK_UNROLL:
  46. return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
  47. case HK_FORCE:
  48. return (Val <= 1);
  49. case HK_ISVECTORIZED:
  50. case HK_PREDICATE:
  51. return (Val == 0 || Val == 1);
  52. }
  53. return false;
  54. }
  55. LoopVectorizeHints::LoopVectorizeHints(const Loop *L,
  56. bool InterleaveOnlyWhenForced,
  57. OptimizationRemarkEmitter &ORE)
  58. : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
  59. Interleave("interleave.count", InterleaveOnlyWhenForced, HK_UNROLL),
  60. Force("vectorize.enable", FK_Undefined, HK_FORCE),
  61. IsVectorized("isvectorized", 0, HK_ISVECTORIZED),
  62. Predicate("vectorize.predicate.enable", 0, HK_PREDICATE), TheLoop(L),
  63. ORE(ORE) {
  64. // Populate values with existing loop metadata.
  65. getHintsFromMetadata();
  66. // force-vector-interleave overrides DisableInterleaving.
  67. if (VectorizerParams::isInterleaveForced())
  68. Interleave.Value = VectorizerParams::VectorizationInterleave;
  69. if (IsVectorized.Value != 1)
  70. // If the vectorization width and interleaving count are both 1 then
  71. // consider the loop to have been already vectorized because there's
  72. // nothing more that we can do.
  73. IsVectorized.Value = Width.Value == 1 && Interleave.Value == 1;
  74. LLVM_DEBUG(if (InterleaveOnlyWhenForced && Interleave.Value == 1) dbgs()
  75. << "LV: Interleaving disabled by the pass manager\n");
  76. }
  77. void LoopVectorizeHints::setAlreadyVectorized() {
  78. LLVMContext &Context = TheLoop->getHeader()->getContext();
  79. MDNode *IsVectorizedMD = MDNode::get(
  80. Context,
  81. {MDString::get(Context, "llvm.loop.isvectorized"),
  82. ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))});
  83. MDNode *LoopID = TheLoop->getLoopID();
  84. MDNode *NewLoopID =
  85. makePostTransformationMetadata(Context, LoopID,
  86. {Twine(Prefix(), "vectorize.").str(),
  87. Twine(Prefix(), "interleave.").str()},
  88. {IsVectorizedMD});
  89. TheLoop->setLoopID(NewLoopID);
  90. // Update internal cache.
  91. IsVectorized.Value = 1;
  92. }
  93. bool LoopVectorizeHints::allowVectorization(
  94. Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
  95. if (getForce() == LoopVectorizeHints::FK_Disabled) {
  96. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
  97. emitRemarkWithHints();
  98. return false;
  99. }
  100. if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
  101. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
  102. emitRemarkWithHints();
  103. return false;
  104. }
  105. if (getIsVectorized() == 1) {
  106. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
  107. // FIXME: Add interleave.disable metadata. This will allow
  108. // vectorize.disable to be used without disabling the pass and errors
  109. // to differentiate between disabled vectorization and a width of 1.
  110. ORE.emit([&]() {
  111. return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
  112. "AllDisabled", L->getStartLoc(),
  113. L->getHeader())
  114. << "loop not vectorized: vectorization and interleaving are "
  115. "explicitly disabled, or the loop has already been "
  116. "vectorized";
  117. });
  118. return false;
  119. }
  120. return true;
  121. }
  122. void LoopVectorizeHints::emitRemarkWithHints() const {
  123. using namespace ore;
  124. ORE.emit([&]() {
  125. if (Force.Value == LoopVectorizeHints::FK_Disabled)
  126. return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
  127. TheLoop->getStartLoc(),
  128. TheLoop->getHeader())
  129. << "loop not vectorized: vectorization is explicitly disabled";
  130. else {
  131. OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
  132. TheLoop->getStartLoc(), TheLoop->getHeader());
  133. R << "loop not vectorized";
  134. if (Force.Value == LoopVectorizeHints::FK_Enabled) {
  135. R << " (Force=" << NV("Force", true);
  136. if (Width.Value != 0)
  137. R << ", Vector Width=" << NV("VectorWidth", Width.Value);
  138. if (Interleave.Value != 0)
  139. R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value);
  140. R << ")";
  141. }
  142. return R;
  143. }
  144. });
  145. }
  146. const char *LoopVectorizeHints::vectorizeAnalysisPassName() const {
  147. if (getWidth() == 1)
  148. return LV_NAME;
  149. if (getForce() == LoopVectorizeHints::FK_Disabled)
  150. return LV_NAME;
  151. if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
  152. return LV_NAME;
  153. return OptimizationRemarkAnalysis::AlwaysPrint;
  154. }
  155. void LoopVectorizeHints::getHintsFromMetadata() {
  156. MDNode *LoopID = TheLoop->getLoopID();
  157. if (!LoopID)
  158. return;
  159. // First operand should refer to the loop id itself.
  160. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  161. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  162. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  163. const MDString *S = nullptr;
  164. SmallVector<Metadata *, 4> Args;
  165. // The expected hint is either a MDString or a MDNode with the first
  166. // operand a MDString.
  167. if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
  168. if (!MD || MD->getNumOperands() == 0)
  169. continue;
  170. S = dyn_cast<MDString>(MD->getOperand(0));
  171. for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
  172. Args.push_back(MD->getOperand(i));
  173. } else {
  174. S = dyn_cast<MDString>(LoopID->getOperand(i));
  175. assert(Args.size() == 0 && "too many arguments for MDString");
  176. }
  177. if (!S)
  178. continue;
  179. // Check if the hint starts with the loop metadata prefix.
  180. StringRef Name = S->getString();
  181. if (Args.size() == 1)
  182. setHint(Name, Args[0]);
  183. }
  184. }
  185. void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
  186. if (!Name.startswith(Prefix()))
  187. return;
  188. Name = Name.substr(Prefix().size(), StringRef::npos);
  189. const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
  190. if (!C)
  191. return;
  192. unsigned Val = C->getZExtValue();
  193. Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized, &Predicate};
  194. for (auto H : Hints) {
  195. if (Name == H->Name) {
  196. if (H->validate(Val))
  197. H->Value = Val;
  198. else
  199. LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
  200. break;
  201. }
  202. }
  203. }
  204. bool LoopVectorizationRequirements::doesNotMeet(
  205. Function *F, Loop *L, const LoopVectorizeHints &Hints) {
  206. const char *PassName = Hints.vectorizeAnalysisPassName();
  207. bool Failed = false;
  208. if (UnsafeAlgebraInst && !Hints.allowReordering()) {
  209. ORE.emit([&]() {
  210. return OptimizationRemarkAnalysisFPCommute(
  211. PassName, "CantReorderFPOps", UnsafeAlgebraInst->getDebugLoc(),
  212. UnsafeAlgebraInst->getParent())
  213. << "loop not vectorized: cannot prove it is safe to reorder "
  214. "floating-point operations";
  215. });
  216. Failed = true;
  217. }
  218. // Test if runtime memcheck thresholds are exceeded.
  219. bool PragmaThresholdReached =
  220. NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
  221. bool ThresholdReached =
  222. NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
  223. if ((ThresholdReached && !Hints.allowReordering()) ||
  224. PragmaThresholdReached) {
  225. ORE.emit([&]() {
  226. return OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
  227. L->getStartLoc(),
  228. L->getHeader())
  229. << "loop not vectorized: cannot prove it is safe to reorder "
  230. "memory operations";
  231. });
  232. LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
  233. Failed = true;
  234. }
  235. return Failed;
  236. }
  237. // Return true if the inner loop \p Lp is uniform with regard to the outer loop
  238. // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
  239. // executing the inner loop will execute the same iterations). This check is
  240. // very constrained for now but it will be relaxed in the future. \p Lp is
  241. // considered uniform if it meets all the following conditions:
  242. // 1) it has a canonical IV (starting from 0 and with stride 1),
  243. // 2) its latch terminator is a conditional branch and,
  244. // 3) its latch condition is a compare instruction whose operands are the
  245. // canonical IV and an OuterLp invariant.
  246. // This check doesn't take into account the uniformity of other conditions not
  247. // related to the loop latch because they don't affect the loop uniformity.
  248. //
  249. // NOTE: We decided to keep all these checks and its associated documentation
  250. // together so that we can easily have a picture of the current supported loop
  251. // nests. However, some of the current checks don't depend on \p OuterLp and
  252. // would be redundantly executed for each \p Lp if we invoked this function for
  253. // different candidate outer loops. This is not the case for now because we
  254. // don't currently have the infrastructure to evaluate multiple candidate outer
  255. // loops and \p OuterLp will be a fixed parameter while we only support explicit
  256. // outer loop vectorization. It's also very likely that these checks go away
  257. // before introducing the aforementioned infrastructure. However, if this is not
  258. // the case, we should move the \p OuterLp independent checks to a separate
  259. // function that is only executed once for each \p Lp.
  260. static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
  261. assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
  262. // If Lp is the outer loop, it's uniform by definition.
  263. if (Lp == OuterLp)
  264. return true;
  265. assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
  266. // 1.
  267. PHINode *IV = Lp->getCanonicalInductionVariable();
  268. if (!IV) {
  269. LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
  270. return false;
  271. }
  272. // 2.
  273. BasicBlock *Latch = Lp->getLoopLatch();
  274. auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
  275. if (!LatchBr || LatchBr->isUnconditional()) {
  276. LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
  277. return false;
  278. }
  279. // 3.
  280. auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
  281. if (!LatchCmp) {
  282. LLVM_DEBUG(
  283. dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
  284. return false;
  285. }
  286. Value *CondOp0 = LatchCmp->getOperand(0);
  287. Value *CondOp1 = LatchCmp->getOperand(1);
  288. Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
  289. if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
  290. !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
  291. LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
  292. return false;
  293. }
  294. return true;
  295. }
  296. // Return true if \p Lp and all its nested loops are uniform with regard to \p
  297. // OuterLp.
  298. static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
  299. if (!isUniformLoop(Lp, OuterLp))
  300. return false;
  301. // Check if nested loops are uniform.
  302. for (Loop *SubLp : *Lp)
  303. if (!isUniformLoopNest(SubLp, OuterLp))
  304. return false;
  305. return true;
  306. }
  307. /// Check whether it is safe to if-convert this phi node.
  308. ///
  309. /// Phi nodes with constant expressions that can trap are not safe to if
  310. /// convert.
  311. static bool canIfConvertPHINodes(BasicBlock *BB) {
  312. for (PHINode &Phi : BB->phis()) {
  313. for (Value *V : Phi.incoming_values())
  314. if (auto *C = dyn_cast<Constant>(V))
  315. if (C->canTrap())
  316. return false;
  317. }
  318. return true;
  319. }
  320. static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
  321. if (Ty->isPointerTy())
  322. return DL.getIntPtrType(Ty);
  323. // It is possible that char's or short's overflow when we ask for the loop's
  324. // trip count, work around this by changing the type size.
  325. if (Ty->getScalarSizeInBits() < 32)
  326. return Type::getInt32Ty(Ty->getContext());
  327. return Ty;
  328. }
  329. static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
  330. Ty0 = convertPointerToIntegerType(DL, Ty0);
  331. Ty1 = convertPointerToIntegerType(DL, Ty1);
  332. if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
  333. return Ty0;
  334. return Ty1;
  335. }
  336. /// Check that the instruction has outside loop users and is not an
  337. /// identified reduction variable.
  338. static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
  339. SmallPtrSetImpl<Value *> &AllowedExit) {
  340. // Reductions, Inductions and non-header phis are allowed to have exit users. All
  341. // other instructions must not have external users.
  342. if (!AllowedExit.count(Inst))
  343. // Check that all of the users of the loop are inside the BB.
  344. for (User *U : Inst->users()) {
  345. Instruction *UI = cast<Instruction>(U);
  346. // This user may be a reduction exit value.
  347. if (!TheLoop->contains(UI)) {
  348. LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
  349. return true;
  350. }
  351. }
  352. return false;
  353. }
  354. int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
  355. const ValueToValueMap &Strides =
  356. getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
  357. int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
  358. if (Stride == 1 || Stride == -1)
  359. return Stride;
  360. return 0;
  361. }
  362. bool LoopVectorizationLegality::isUniform(Value *V) {
  363. return LAI->isUniform(V);
  364. }
  365. bool LoopVectorizationLegality::canVectorizeOuterLoop() {
  366. assert(!TheLoop->empty() && "We are not vectorizing an outer loop.");
  367. // Store the result and return it at the end instead of exiting early, in case
  368. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  369. bool Result = true;
  370. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  371. for (BasicBlock *BB : TheLoop->blocks()) {
  372. // Check whether the BB terminator is a BranchInst. Any other terminator is
  373. // not supported yet.
  374. auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
  375. if (!Br) {
  376. reportVectorizationFailure("Unsupported basic block terminator",
  377. "loop control flow is not understood by vectorizer",
  378. "CFGNotUnderstood", ORE, TheLoop);
  379. if (DoExtraAnalysis)
  380. Result = false;
  381. else
  382. return false;
  383. }
  384. // Check whether the BranchInst is a supported one. Only unconditional
  385. // branches, conditional branches with an outer loop invariant condition or
  386. // backedges are supported.
  387. // FIXME: We skip these checks when VPlan predication is enabled as we
  388. // want to allow divergent branches. This whole check will be removed
  389. // once VPlan predication is on by default.
  390. if (!EnableVPlanPredication && Br && Br->isConditional() &&
  391. !TheLoop->isLoopInvariant(Br->getCondition()) &&
  392. !LI->isLoopHeader(Br->getSuccessor(0)) &&
  393. !LI->isLoopHeader(Br->getSuccessor(1))) {
  394. reportVectorizationFailure("Unsupported conditional branch",
  395. "loop control flow is not understood by vectorizer",
  396. "CFGNotUnderstood", ORE, TheLoop);
  397. if (DoExtraAnalysis)
  398. Result = false;
  399. else
  400. return false;
  401. }
  402. }
  403. // Check whether inner loops are uniform. At this point, we only support
  404. // simple outer loops scenarios with uniform nested loops.
  405. if (!isUniformLoopNest(TheLoop /*loop nest*/,
  406. TheLoop /*context outer loop*/)) {
  407. reportVectorizationFailure("Outer loop contains divergent loops",
  408. "loop control flow is not understood by vectorizer",
  409. "CFGNotUnderstood", ORE, TheLoop);
  410. if (DoExtraAnalysis)
  411. Result = false;
  412. else
  413. return false;
  414. }
  415. // Check whether we are able to set up outer loop induction.
  416. if (!setupOuterLoopInductions()) {
  417. reportVectorizationFailure("Unsupported outer loop Phi(s)",
  418. "Unsupported outer loop Phi(s)",
  419. "UnsupportedPhi", ORE, TheLoop);
  420. if (DoExtraAnalysis)
  421. Result = false;
  422. else
  423. return false;
  424. }
  425. return Result;
  426. }
  427. void LoopVectorizationLegality::addInductionPhi(
  428. PHINode *Phi, const InductionDescriptor &ID,
  429. SmallPtrSetImpl<Value *> &AllowedExit) {
  430. Inductions[Phi] = ID;
  431. // In case this induction also comes with casts that we know we can ignore
  432. // in the vectorized loop body, record them here. All casts could be recorded
  433. // here for ignoring, but suffices to record only the first (as it is the
  434. // only one that may bw used outside the cast sequence).
  435. const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
  436. if (!Casts.empty())
  437. InductionCastsToIgnore.insert(*Casts.begin());
  438. Type *PhiTy = Phi->getType();
  439. const DataLayout &DL = Phi->getModule()->getDataLayout();
  440. // Get the widest type.
  441. if (!PhiTy->isFloatingPointTy()) {
  442. if (!WidestIndTy)
  443. WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
  444. else
  445. WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
  446. }
  447. // Int inductions are special because we only allow one IV.
  448. if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
  449. ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
  450. isa<Constant>(ID.getStartValue()) &&
  451. cast<Constant>(ID.getStartValue())->isNullValue()) {
  452. // Use the phi node with the widest type as induction. Use the last
  453. // one if there are multiple (no good reason for doing this other
  454. // than it is expedient). We've checked that it begins at zero and
  455. // steps by one, so this is a canonical induction variable.
  456. if (!PrimaryInduction || PhiTy == WidestIndTy)
  457. PrimaryInduction = Phi;
  458. }
  459. // Both the PHI node itself, and the "post-increment" value feeding
  460. // back into the PHI node may have external users.
  461. // We can allow those uses, except if the SCEVs we have for them rely
  462. // on predicates that only hold within the loop, since allowing the exit
  463. // currently means re-using this SCEV outside the loop (see PR33706 for more
  464. // details).
  465. if (PSE.getUnionPredicate().isAlwaysTrue()) {
  466. AllowedExit.insert(Phi);
  467. AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
  468. }
  469. LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
  470. }
  471. bool LoopVectorizationLegality::setupOuterLoopInductions() {
  472. BasicBlock *Header = TheLoop->getHeader();
  473. // Returns true if a given Phi is a supported induction.
  474. auto isSupportedPhi = [&](PHINode &Phi) -> bool {
  475. InductionDescriptor ID;
  476. if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
  477. ID.getKind() == InductionDescriptor::IK_IntInduction) {
  478. addInductionPhi(&Phi, ID, AllowedExit);
  479. return true;
  480. } else {
  481. // Bail out for any Phi in the outer loop header that is not a supported
  482. // induction.
  483. LLVM_DEBUG(
  484. dbgs()
  485. << "LV: Found unsupported PHI for outer loop vectorization.\n");
  486. return false;
  487. }
  488. };
  489. if (llvm::all_of(Header->phis(), isSupportedPhi))
  490. return true;
  491. else
  492. return false;
  493. }
  494. bool LoopVectorizationLegality::canVectorizeInstrs() {
  495. BasicBlock *Header = TheLoop->getHeader();
  496. // Look for the attribute signaling the absence of NaNs.
  497. Function &F = *Header->getParent();
  498. HasFunNoNaNAttr =
  499. F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
  500. // For each block in the loop.
  501. for (BasicBlock *BB : TheLoop->blocks()) {
  502. // Scan the instructions in the block and look for hazards.
  503. for (Instruction &I : *BB) {
  504. if (auto *Phi = dyn_cast<PHINode>(&I)) {
  505. Type *PhiTy = Phi->getType();
  506. // Check that this PHI type is allowed.
  507. if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
  508. !PhiTy->isPointerTy()) {
  509. reportVectorizationFailure("Found a non-int non-pointer PHI",
  510. "loop control flow is not understood by vectorizer",
  511. "CFGNotUnderstood", ORE, TheLoop);
  512. return false;
  513. }
  514. // If this PHINode is not in the header block, then we know that we
  515. // can convert it to select during if-conversion. No need to check if
  516. // the PHIs in this block are induction or reduction variables.
  517. if (BB != Header) {
  518. // Non-header phi nodes that have outside uses can be vectorized. Add
  519. // them to the list of allowed exits.
  520. // Unsafe cyclic dependencies with header phis are identified during
  521. // legalization for reduction, induction and first order
  522. // recurrences.
  523. continue;
  524. }
  525. // We only allow if-converted PHIs with exactly two incoming values.
  526. if (Phi->getNumIncomingValues() != 2) {
  527. reportVectorizationFailure("Found an invalid PHI",
  528. "loop control flow is not understood by vectorizer",
  529. "CFGNotUnderstood", ORE, TheLoop, Phi);
  530. return false;
  531. }
  532. RecurrenceDescriptor RedDes;
  533. if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
  534. DT)) {
  535. if (RedDes.hasUnsafeAlgebra())
  536. Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
  537. AllowedExit.insert(RedDes.getLoopExitInstr());
  538. Reductions[Phi] = RedDes;
  539. continue;
  540. }
  541. // TODO: Instead of recording the AllowedExit, it would be good to record the
  542. // complementary set: NotAllowedExit. These include (but may not be
  543. // limited to):
  544. // 1. Reduction phis as they represent the one-before-last value, which
  545. // is not available when vectorized
  546. // 2. Induction phis and increment when SCEV predicates cannot be used
  547. // outside the loop - see addInductionPhi
  548. // 3. Non-Phis with outside uses when SCEV predicates cannot be used
  549. // outside the loop - see call to hasOutsideLoopUser in the non-phi
  550. // handling below
  551. // 4. FirstOrderRecurrence phis that can possibly be handled by
  552. // extraction.
  553. // By recording these, we can then reason about ways to vectorize each
  554. // of these NotAllowedExit.
  555. InductionDescriptor ID;
  556. if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
  557. addInductionPhi(Phi, ID, AllowedExit);
  558. if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
  559. Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
  560. continue;
  561. }
  562. if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
  563. SinkAfter, DT)) {
  564. FirstOrderRecurrences.insert(Phi);
  565. continue;
  566. }
  567. // As a last resort, coerce the PHI to a AddRec expression
  568. // and re-try classifying it a an induction PHI.
  569. if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
  570. addInductionPhi(Phi, ID, AllowedExit);
  571. continue;
  572. }
  573. reportVectorizationFailure("Found an unidentified PHI",
  574. "value that could not be identified as "
  575. "reduction is used outside the loop",
  576. "NonReductionValueUsedOutsideLoop", ORE, TheLoop, Phi);
  577. return false;
  578. } // end of PHI handling
  579. // We handle calls that:
  580. // * Are debug info intrinsics.
  581. // * Have a mapping to an IR intrinsic.
  582. // * Have a vector version available.
  583. auto *CI = dyn_cast<CallInst>(&I);
  584. if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
  585. !isa<DbgInfoIntrinsic>(CI) &&
  586. !(CI->getCalledFunction() && TLI &&
  587. TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
  588. // If the call is a recognized math libary call, it is likely that
  589. // we can vectorize it given loosened floating-point constraints.
  590. LibFunc Func;
  591. bool IsMathLibCall =
  592. TLI && CI->getCalledFunction() &&
  593. CI->getType()->isFloatingPointTy() &&
  594. TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
  595. TLI->hasOptimizedCodeGen(Func);
  596. if (IsMathLibCall) {
  597. // TODO: Ideally, we should not use clang-specific language here,
  598. // but it's hard to provide meaningful yet generic advice.
  599. // Also, should this be guarded by allowExtraAnalysis() and/or be part
  600. // of the returned info from isFunctionVectorizable()?
  601. reportVectorizationFailure("Found a non-intrinsic callsite",
  602. "library call cannot be vectorized. "
  603. "Try compiling with -fno-math-errno, -ffast-math, "
  604. "or similar flags",
  605. "CantVectorizeLibcall", ORE, TheLoop, CI);
  606. } else {
  607. reportVectorizationFailure("Found a non-intrinsic callsite",
  608. "call instruction cannot be vectorized",
  609. "CantVectorizeLibcall", ORE, TheLoop, CI);
  610. }
  611. return false;
  612. }
  613. // Some intrinsics have scalar arguments and should be same in order for
  614. // them to be vectorized (i.e. loop invariant).
  615. if (CI) {
  616. auto *SE = PSE.getSE();
  617. Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
  618. for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
  619. if (hasVectorInstrinsicScalarOpd(IntrinID, i)) {
  620. if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) {
  621. reportVectorizationFailure("Found unvectorizable intrinsic",
  622. "intrinsic instruction cannot be vectorized",
  623. "CantVectorizeIntrinsic", ORE, TheLoop, CI);
  624. return false;
  625. }
  626. }
  627. }
  628. // Check that the instruction return type is vectorizable.
  629. // Also, we can't vectorize extractelement instructions.
  630. if ((!VectorType::isValidElementType(I.getType()) &&
  631. !I.getType()->isVoidTy()) ||
  632. isa<ExtractElementInst>(I)) {
  633. reportVectorizationFailure("Found unvectorizable type",
  634. "instruction return type cannot be vectorized",
  635. "CantVectorizeInstructionReturnType", ORE, TheLoop, &I);
  636. return false;
  637. }
  638. // Check that the stored type is vectorizable.
  639. if (auto *ST = dyn_cast<StoreInst>(&I)) {
  640. Type *T = ST->getValueOperand()->getType();
  641. if (!VectorType::isValidElementType(T)) {
  642. reportVectorizationFailure("Store instruction cannot be vectorized",
  643. "store instruction cannot be vectorized",
  644. "CantVectorizeStore", ORE, TheLoop, ST);
  645. return false;
  646. }
  647. // For nontemporal stores, check that a nontemporal vector version is
  648. // supported on the target.
  649. if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
  650. // Arbitrarily try a vector of 2 elements.
  651. Type *VecTy = VectorType::get(T, /*NumElements=*/2);
  652. assert(VecTy && "did not find vectorized version of stored type");
  653. unsigned Alignment = getLoadStoreAlignment(ST);
  654. if (!TTI->isLegalNTStore(VecTy, Alignment)) {
  655. reportVectorizationFailure(
  656. "nontemporal store instruction cannot be vectorized",
  657. "nontemporal store instruction cannot be vectorized",
  658. "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
  659. return false;
  660. }
  661. }
  662. } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
  663. if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
  664. // For nontemporal loads, check that a nontemporal vector version is
  665. // supported on the target (arbitrarily try a vector of 2 elements).
  666. Type *VecTy = VectorType::get(I.getType(), /*NumElements=*/2);
  667. assert(VecTy && "did not find vectorized version of load type");
  668. unsigned Alignment = getLoadStoreAlignment(LD);
  669. if (!TTI->isLegalNTLoad(VecTy, Alignment)) {
  670. reportVectorizationFailure(
  671. "nontemporal load instruction cannot be vectorized",
  672. "nontemporal load instruction cannot be vectorized",
  673. "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
  674. return false;
  675. }
  676. }
  677. // FP instructions can allow unsafe algebra, thus vectorizable by
  678. // non-IEEE-754 compliant SIMD units.
  679. // This applies to floating-point math operations and calls, not memory
  680. // operations, shuffles, or casts, as they don't change precision or
  681. // semantics.
  682. } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
  683. !I.isFast()) {
  684. LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
  685. Hints->setPotentiallyUnsafe();
  686. }
  687. // Reduction instructions are allowed to have exit users.
  688. // All other instructions must not have external users.
  689. if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
  690. // We can safely vectorize loops where instructions within the loop are
  691. // used outside the loop only if the SCEV predicates within the loop is
  692. // same as outside the loop. Allowing the exit means reusing the SCEV
  693. // outside the loop.
  694. if (PSE.getUnionPredicate().isAlwaysTrue()) {
  695. AllowedExit.insert(&I);
  696. continue;
  697. }
  698. reportVectorizationFailure("Value cannot be used outside the loop",
  699. "value cannot be used outside the loop",
  700. "ValueUsedOutsideLoop", ORE, TheLoop, &I);
  701. return false;
  702. }
  703. } // next instr.
  704. }
  705. if (!PrimaryInduction) {
  706. if (Inductions.empty()) {
  707. reportVectorizationFailure("Did not find one integer induction var",
  708. "loop induction variable could not be identified",
  709. "NoInductionVariable", ORE, TheLoop);
  710. return false;
  711. } else if (!WidestIndTy) {
  712. reportVectorizationFailure("Did not find one integer induction var",
  713. "integer loop induction variable could not be identified",
  714. "NoIntegerInductionVariable", ORE, TheLoop);
  715. return false;
  716. } else {
  717. LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
  718. }
  719. }
  720. // Now we know the widest induction type, check if our found induction
  721. // is the same size. If it's not, unset it here and InnerLoopVectorizer
  722. // will create another.
  723. if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
  724. PrimaryInduction = nullptr;
  725. return true;
  726. }
  727. bool LoopVectorizationLegality::canVectorizeMemory() {
  728. LAI = &(*GetLAA)(*TheLoop);
  729. const OptimizationRemarkAnalysis *LAR = LAI->getReport();
  730. if (LAR) {
  731. ORE->emit([&]() {
  732. return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
  733. "loop not vectorized: ", *LAR);
  734. });
  735. }
  736. if (!LAI->canVectorizeMemory())
  737. return false;
  738. if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
  739. reportVectorizationFailure("Stores to a uniform address",
  740. "write to a loop invariant address could not be vectorized",
  741. "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
  742. return false;
  743. }
  744. Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
  745. PSE.addPredicate(LAI->getPSE().getUnionPredicate());
  746. return true;
  747. }
  748. bool LoopVectorizationLegality::isInductionPhi(const Value *V) {
  749. Value *In0 = const_cast<Value *>(V);
  750. PHINode *PN = dyn_cast_or_null<PHINode>(In0);
  751. if (!PN)
  752. return false;
  753. return Inductions.count(PN);
  754. }
  755. bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) {
  756. auto *Inst = dyn_cast<Instruction>(V);
  757. return (Inst && InductionCastsToIgnore.count(Inst));
  758. }
  759. bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
  760. return isInductionPhi(V) || isCastedInductionVariable(V);
  761. }
  762. bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
  763. return FirstOrderRecurrences.count(Phi);
  764. }
  765. bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
  766. return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
  767. }
  768. bool LoopVectorizationLegality::blockCanBePredicated(
  769. BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs, bool PreserveGuards) {
  770. const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
  771. for (Instruction &I : *BB) {
  772. // Check that we don't have a constant expression that can trap as operand.
  773. for (Value *Operand : I.operands()) {
  774. if (auto *C = dyn_cast<Constant>(Operand))
  775. if (C->canTrap())
  776. return false;
  777. }
  778. // We might be able to hoist the load.
  779. if (I.mayReadFromMemory()) {
  780. auto *LI = dyn_cast<LoadInst>(&I);
  781. if (!LI)
  782. return false;
  783. if (!SafePtrs.count(LI->getPointerOperand())) {
  784. // !llvm.mem.parallel_loop_access implies if-conversion safety.
  785. // Otherwise, record that the load needs (real or emulated) masking
  786. // and let the cost model decide.
  787. if (!IsAnnotatedParallel || PreserveGuards)
  788. MaskedOp.insert(LI);
  789. continue;
  790. }
  791. }
  792. if (I.mayWriteToMemory()) {
  793. auto *SI = dyn_cast<StoreInst>(&I);
  794. if (!SI)
  795. return false;
  796. // Predicated store requires some form of masking:
  797. // 1) masked store HW instruction,
  798. // 2) emulation via load-blend-store (only if safe and legal to do so,
  799. // be aware on the race conditions), or
  800. // 3) element-by-element predicate check and scalar store.
  801. MaskedOp.insert(SI);
  802. continue;
  803. }
  804. if (I.mayThrow())
  805. return false;
  806. }
  807. return true;
  808. }
  809. bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
  810. if (!EnableIfConversion) {
  811. reportVectorizationFailure("If-conversion is disabled",
  812. "if-conversion is disabled",
  813. "IfConversionDisabled",
  814. ORE, TheLoop);
  815. return false;
  816. }
  817. assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
  818. // A list of pointers which are known to be dereferenceable within scope of
  819. // the loop body for each iteration of the loop which executes. That is,
  820. // the memory pointed to can be dereferenced (with the access size implied by
  821. // the value's type) unconditionally within the loop header without
  822. // introducing a new fault.
  823. SmallPtrSet<Value *, 8> SafePointes;
  824. // Collect safe addresses.
  825. for (BasicBlock *BB : TheLoop->blocks()) {
  826. if (blockNeedsPredication(BB))
  827. continue;
  828. for (Instruction &I : *BB)
  829. if (auto *Ptr = getLoadStorePointerOperand(&I))
  830. SafePointes.insert(Ptr);
  831. }
  832. // Collect the blocks that need predication.
  833. BasicBlock *Header = TheLoop->getHeader();
  834. for (BasicBlock *BB : TheLoop->blocks()) {
  835. // We don't support switch statements inside loops.
  836. if (!isa<BranchInst>(BB->getTerminator())) {
  837. reportVectorizationFailure("Loop contains a switch statement",
  838. "loop contains a switch statement",
  839. "LoopContainsSwitch", ORE, TheLoop,
  840. BB->getTerminator());
  841. return false;
  842. }
  843. // We must be able to predicate all blocks that need to be predicated.
  844. if (blockNeedsPredication(BB)) {
  845. if (!blockCanBePredicated(BB, SafePointes)) {
  846. reportVectorizationFailure(
  847. "Control flow cannot be substituted for a select",
  848. "control flow cannot be substituted for a select",
  849. "NoCFGForSelect", ORE, TheLoop,
  850. BB->getTerminator());
  851. return false;
  852. }
  853. } else if (BB != Header && !canIfConvertPHINodes(BB)) {
  854. reportVectorizationFailure(
  855. "Control flow cannot be substituted for a select",
  856. "control flow cannot be substituted for a select",
  857. "NoCFGForSelect", ORE, TheLoop,
  858. BB->getTerminator());
  859. return false;
  860. }
  861. }
  862. // We can if-convert this loop.
  863. return true;
  864. }
  865. // Helper function to canVectorizeLoopNestCFG.
  866. bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
  867. bool UseVPlanNativePath) {
  868. assert((UseVPlanNativePath || Lp->empty()) &&
  869. "VPlan-native path is not enabled.");
  870. // TODO: ORE should be improved to show more accurate information when an
  871. // outer loop can't be vectorized because a nested loop is not understood or
  872. // legal. Something like: "outer_loop_location: loop not vectorized:
  873. // (inner_loop_location) loop control flow is not understood by vectorizer".
  874. // Store the result and return it at the end instead of exiting early, in case
  875. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  876. bool Result = true;
  877. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  878. // We must have a loop in canonical form. Loops with indirectbr in them cannot
  879. // be canonicalized.
  880. if (!Lp->getLoopPreheader()) {
  881. reportVectorizationFailure("Loop doesn't have a legal pre-header",
  882. "loop control flow is not understood by vectorizer",
  883. "CFGNotUnderstood", ORE, TheLoop);
  884. if (DoExtraAnalysis)
  885. Result = false;
  886. else
  887. return false;
  888. }
  889. // We must have a single backedge.
  890. if (Lp->getNumBackEdges() != 1) {
  891. reportVectorizationFailure("The loop must have a single backedge",
  892. "loop control flow is not understood by vectorizer",
  893. "CFGNotUnderstood", ORE, TheLoop);
  894. if (DoExtraAnalysis)
  895. Result = false;
  896. else
  897. return false;
  898. }
  899. // We must have a single exiting block.
  900. if (!Lp->getExitingBlock()) {
  901. reportVectorizationFailure("The loop must have an exiting block",
  902. "loop control flow is not understood by vectorizer",
  903. "CFGNotUnderstood", ORE, TheLoop);
  904. if (DoExtraAnalysis)
  905. Result = false;
  906. else
  907. return false;
  908. }
  909. // We only handle bottom-tested loops, i.e. loop in which the condition is
  910. // checked at the end of each iteration. With that we can assume that all
  911. // instructions in the loop are executed the same number of times.
  912. if (Lp->getExitingBlock() != Lp->getLoopLatch()) {
  913. reportVectorizationFailure("The exiting block is not the loop latch",
  914. "loop control flow is not understood by vectorizer",
  915. "CFGNotUnderstood", ORE, TheLoop);
  916. if (DoExtraAnalysis)
  917. Result = false;
  918. else
  919. return false;
  920. }
  921. return Result;
  922. }
  923. bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
  924. Loop *Lp, bool UseVPlanNativePath) {
  925. // Store the result and return it at the end instead of exiting early, in case
  926. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  927. bool Result = true;
  928. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  929. if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
  930. if (DoExtraAnalysis)
  931. Result = false;
  932. else
  933. return false;
  934. }
  935. // Recursively check whether the loop control flow of nested loops is
  936. // understood.
  937. for (Loop *SubLp : *Lp)
  938. if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
  939. if (DoExtraAnalysis)
  940. Result = false;
  941. else
  942. return false;
  943. }
  944. return Result;
  945. }
  946. bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
  947. // Store the result and return it at the end instead of exiting early, in case
  948. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  949. bool Result = true;
  950. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  951. // Check whether the loop-related control flow in the loop nest is expected by
  952. // vectorizer.
  953. if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
  954. if (DoExtraAnalysis)
  955. Result = false;
  956. else
  957. return false;
  958. }
  959. // We need to have a loop header.
  960. LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
  961. << '\n');
  962. // Specific checks for outer loops. We skip the remaining legal checks at this
  963. // point because they don't support outer loops.
  964. if (!TheLoop->empty()) {
  965. assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
  966. if (!canVectorizeOuterLoop()) {
  967. reportVectorizationFailure("Unsupported outer loop",
  968. "unsupported outer loop",
  969. "UnsupportedOuterLoop",
  970. ORE, TheLoop);
  971. // TODO: Implement DoExtraAnalysis when subsequent legal checks support
  972. // outer loops.
  973. return false;
  974. }
  975. LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
  976. return Result;
  977. }
  978. assert(TheLoop->empty() && "Inner loop expected.");
  979. // Check if we can if-convert non-single-bb loops.
  980. unsigned NumBlocks = TheLoop->getNumBlocks();
  981. if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
  982. LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
  983. if (DoExtraAnalysis)
  984. Result = false;
  985. else
  986. return false;
  987. }
  988. // Check if we can vectorize the instructions and CFG in this loop.
  989. if (!canVectorizeInstrs()) {
  990. LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
  991. if (DoExtraAnalysis)
  992. Result = false;
  993. else
  994. return false;
  995. }
  996. // Go over each instruction and look at memory deps.
  997. if (!canVectorizeMemory()) {
  998. LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
  999. if (DoExtraAnalysis)
  1000. Result = false;
  1001. else
  1002. return false;
  1003. }
  1004. LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
  1005. << (LAI->getRuntimePointerChecking()->Need
  1006. ? " (with a runtime bound check)"
  1007. : "")
  1008. << "!\n");
  1009. unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
  1010. if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
  1011. SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
  1012. if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
  1013. reportVectorizationFailure("Too many SCEV checks needed",
  1014. "Too many SCEV assumptions need to be made and checked at runtime",
  1015. "TooManySCEVRunTimeChecks", ORE, TheLoop);
  1016. if (DoExtraAnalysis)
  1017. Result = false;
  1018. else
  1019. return false;
  1020. }
  1021. // Okay! We've done all the tests. If any have failed, return false. Otherwise
  1022. // we can vectorize, and at this point we don't have any other mem analysis
  1023. // which may limit our maximum vectorization factor, so just return true with
  1024. // no restrictions.
  1025. return Result;
  1026. }
  1027. bool LoopVectorizationLegality::prepareToFoldTailByMasking() {
  1028. LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
  1029. if (!PrimaryInduction) {
  1030. reportVectorizationFailure(
  1031. "No primary induction, cannot fold tail by masking",
  1032. "Missing a primary induction variable in the loop, which is "
  1033. "needed in order to fold tail by masking as required.",
  1034. "NoPrimaryInduction", ORE, TheLoop);
  1035. return false;
  1036. }
  1037. SmallPtrSet<const Value *, 8> ReductionLiveOuts;
  1038. for (auto &Reduction : *getReductionVars())
  1039. ReductionLiveOuts.insert(Reduction.second.getLoopExitInstr());
  1040. // TODO: handle non-reduction outside users when tail is folded by masking.
  1041. for (auto *AE : AllowedExit) {
  1042. // Check that all users of allowed exit values are inside the loop or
  1043. // are the live-out of a reduction.
  1044. if (ReductionLiveOuts.count(AE))
  1045. continue;
  1046. for (User *U : AE->users()) {
  1047. Instruction *UI = cast<Instruction>(U);
  1048. if (TheLoop->contains(UI))
  1049. continue;
  1050. reportVectorizationFailure(
  1051. "Cannot fold tail by masking, loop has an outside user for",
  1052. "Cannot fold tail by masking in the presence of live outs.",
  1053. "LiveOutFoldingTailByMasking", ORE, TheLoop, UI);
  1054. return false;
  1055. }
  1056. }
  1057. // The list of pointers that we can safely read and write to remains empty.
  1058. SmallPtrSet<Value *, 8> SafePointers;
  1059. // Check and mark all blocks for predication, including those that ordinarily
  1060. // do not need predication such as the header block.
  1061. for (BasicBlock *BB : TheLoop->blocks()) {
  1062. if (!blockCanBePredicated(BB, SafePointers, /* MaskAllLoads= */ true)) {
  1063. reportVectorizationFailure(
  1064. "Cannot fold tail by masking as required",
  1065. "control flow cannot be substituted for a select",
  1066. "NoCFGForSelect", ORE, TheLoop,
  1067. BB->getTerminator());
  1068. return false;
  1069. }
  1070. }
  1071. LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
  1072. return true;
  1073. }
  1074. } // namespace llvm