ExpandMemCmp.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. //===--- ExpandMemCmp.cpp - Expand memcmp() to load/stores ----------------===//
  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 pass tries to expand memcmp() calls into optimally-sized loads and
  10. // compares for the target.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/Analysis/ConstantFolding.h"
  15. #include "llvm/Analysis/DomTreeUpdater.h"
  16. #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
  17. #include "llvm/Analysis/ProfileSummaryInfo.h"
  18. #include "llvm/Analysis/TargetLibraryInfo.h"
  19. #include "llvm/Analysis/TargetTransformInfo.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/CodeGen/TargetPassConfig.h"
  22. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/IRBuilder.h"
  25. #include "llvm/InitializePasses.h"
  26. #include "llvm/Target/TargetMachine.h"
  27. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  28. #include "llvm/Transforms/Utils/Local.h"
  29. #include "llvm/Transforms/Utils/SizeOpts.h"
  30. #include <optional>
  31. using namespace llvm;
  32. namespace llvm {
  33. class TargetLowering;
  34. }
  35. #define DEBUG_TYPE "expandmemcmp"
  36. STATISTIC(NumMemCmpCalls, "Number of memcmp calls");
  37. STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size");
  38. STATISTIC(NumMemCmpGreaterThanMax,
  39. "Number of memcmp calls with size greater than max size");
  40. STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls");
  41. static cl::opt<unsigned> MemCmpEqZeroNumLoadsPerBlock(
  42. "memcmp-num-loads-per-block", cl::Hidden, cl::init(1),
  43. cl::desc("The number of loads per basic block for inline expansion of "
  44. "memcmp that is only being compared against zero."));
  45. static cl::opt<unsigned> MaxLoadsPerMemcmp(
  46. "max-loads-per-memcmp", cl::Hidden,
  47. cl::desc("Set maximum number of loads used in expanded memcmp"));
  48. static cl::opt<unsigned> MaxLoadsPerMemcmpOptSize(
  49. "max-loads-per-memcmp-opt-size", cl::Hidden,
  50. cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz"));
  51. namespace {
  52. // This class provides helper functions to expand a memcmp library call into an
  53. // inline expansion.
  54. class MemCmpExpansion {
  55. struct ResultBlock {
  56. BasicBlock *BB = nullptr;
  57. PHINode *PhiSrc1 = nullptr;
  58. PHINode *PhiSrc2 = nullptr;
  59. ResultBlock() = default;
  60. };
  61. CallInst *const CI;
  62. ResultBlock ResBlock;
  63. const uint64_t Size;
  64. unsigned MaxLoadSize = 0;
  65. uint64_t NumLoadsNonOneByte = 0;
  66. const uint64_t NumLoadsPerBlockForZeroCmp;
  67. std::vector<BasicBlock *> LoadCmpBlocks;
  68. BasicBlock *EndBlock;
  69. PHINode *PhiRes;
  70. const bool IsUsedForZeroCmp;
  71. const DataLayout &DL;
  72. DomTreeUpdater *DTU;
  73. IRBuilder<> Builder;
  74. // Represents the decomposition in blocks of the expansion. For example,
  75. // comparing 33 bytes on X86+sse can be done with 2x16-byte loads and
  76. // 1x1-byte load, which would be represented as [{16, 0}, {16, 16}, {1, 32}.
  77. struct LoadEntry {
  78. LoadEntry(unsigned LoadSize, uint64_t Offset)
  79. : LoadSize(LoadSize), Offset(Offset) {
  80. }
  81. // The size of the load for this block, in bytes.
  82. unsigned LoadSize;
  83. // The offset of this load from the base pointer, in bytes.
  84. uint64_t Offset;
  85. };
  86. using LoadEntryVector = SmallVector<LoadEntry, 8>;
  87. LoadEntryVector LoadSequence;
  88. void createLoadCmpBlocks();
  89. void createResultBlock();
  90. void setupResultBlockPHINodes();
  91. void setupEndBlockPHINodes();
  92. Value *getCompareLoadPairs(unsigned BlockIndex, unsigned &LoadIndex);
  93. void emitLoadCompareBlock(unsigned BlockIndex);
  94. void emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
  95. unsigned &LoadIndex);
  96. void emitLoadCompareByteBlock(unsigned BlockIndex, unsigned OffsetBytes);
  97. void emitMemCmpResultBlock();
  98. Value *getMemCmpExpansionZeroCase();
  99. Value *getMemCmpEqZeroOneBlock();
  100. Value *getMemCmpOneBlock();
  101. struct LoadPair {
  102. Value *Lhs = nullptr;
  103. Value *Rhs = nullptr;
  104. };
  105. LoadPair getLoadPair(Type *LoadSizeType, bool NeedsBSwap, Type *CmpSizeType,
  106. unsigned OffsetBytes);
  107. static LoadEntryVector
  108. computeGreedyLoadSequence(uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
  109. unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte);
  110. static LoadEntryVector
  111. computeOverlappingLoadSequence(uint64_t Size, unsigned MaxLoadSize,
  112. unsigned MaxNumLoads,
  113. unsigned &NumLoadsNonOneByte);
  114. public:
  115. MemCmpExpansion(CallInst *CI, uint64_t Size,
  116. const TargetTransformInfo::MemCmpExpansionOptions &Options,
  117. const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
  118. DomTreeUpdater *DTU);
  119. unsigned getNumBlocks();
  120. uint64_t getNumLoads() const { return LoadSequence.size(); }
  121. Value *getMemCmpExpansion();
  122. };
  123. MemCmpExpansion::LoadEntryVector MemCmpExpansion::computeGreedyLoadSequence(
  124. uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
  125. const unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte) {
  126. NumLoadsNonOneByte = 0;
  127. LoadEntryVector LoadSequence;
  128. uint64_t Offset = 0;
  129. while (Size && !LoadSizes.empty()) {
  130. const unsigned LoadSize = LoadSizes.front();
  131. const uint64_t NumLoadsForThisSize = Size / LoadSize;
  132. if (LoadSequence.size() + NumLoadsForThisSize > MaxNumLoads) {
  133. // Do not expand if the total number of loads is larger than what the
  134. // target allows. Note that it's important that we exit before completing
  135. // the expansion to avoid using a ton of memory to store the expansion for
  136. // large sizes.
  137. return {};
  138. }
  139. if (NumLoadsForThisSize > 0) {
  140. for (uint64_t I = 0; I < NumLoadsForThisSize; ++I) {
  141. LoadSequence.push_back({LoadSize, Offset});
  142. Offset += LoadSize;
  143. }
  144. if (LoadSize > 1)
  145. ++NumLoadsNonOneByte;
  146. Size = Size % LoadSize;
  147. }
  148. LoadSizes = LoadSizes.drop_front();
  149. }
  150. return LoadSequence;
  151. }
  152. MemCmpExpansion::LoadEntryVector
  153. MemCmpExpansion::computeOverlappingLoadSequence(uint64_t Size,
  154. const unsigned MaxLoadSize,
  155. const unsigned MaxNumLoads,
  156. unsigned &NumLoadsNonOneByte) {
  157. // These are already handled by the greedy approach.
  158. if (Size < 2 || MaxLoadSize < 2)
  159. return {};
  160. // We try to do as many non-overlapping loads as possible starting from the
  161. // beginning.
  162. const uint64_t NumNonOverlappingLoads = Size / MaxLoadSize;
  163. assert(NumNonOverlappingLoads && "there must be at least one load");
  164. // There remain 0 to (MaxLoadSize - 1) bytes to load, this will be done with
  165. // an overlapping load.
  166. Size = Size - NumNonOverlappingLoads * MaxLoadSize;
  167. // Bail if we do not need an overloapping store, this is already handled by
  168. // the greedy approach.
  169. if (Size == 0)
  170. return {};
  171. // Bail if the number of loads (non-overlapping + potential overlapping one)
  172. // is larger than the max allowed.
  173. if ((NumNonOverlappingLoads + 1) > MaxNumLoads)
  174. return {};
  175. // Add non-overlapping loads.
  176. LoadEntryVector LoadSequence;
  177. uint64_t Offset = 0;
  178. for (uint64_t I = 0; I < NumNonOverlappingLoads; ++I) {
  179. LoadSequence.push_back({MaxLoadSize, Offset});
  180. Offset += MaxLoadSize;
  181. }
  182. // Add the last overlapping load.
  183. assert(Size > 0 && Size < MaxLoadSize && "broken invariant");
  184. LoadSequence.push_back({MaxLoadSize, Offset - (MaxLoadSize - Size)});
  185. NumLoadsNonOneByte = 1;
  186. return LoadSequence;
  187. }
  188. // Initialize the basic block structure required for expansion of memcmp call
  189. // with given maximum load size and memcmp size parameter.
  190. // This structure includes:
  191. // 1. A list of load compare blocks - LoadCmpBlocks.
  192. // 2. An EndBlock, split from original instruction point, which is the block to
  193. // return from.
  194. // 3. ResultBlock, block to branch to for early exit when a
  195. // LoadCmpBlock finds a difference.
  196. MemCmpExpansion::MemCmpExpansion(
  197. CallInst *const CI, uint64_t Size,
  198. const TargetTransformInfo::MemCmpExpansionOptions &Options,
  199. const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
  200. DomTreeUpdater *DTU)
  201. : CI(CI), Size(Size), NumLoadsPerBlockForZeroCmp(Options.NumLoadsPerBlock),
  202. IsUsedForZeroCmp(IsUsedForZeroCmp), DL(TheDataLayout), DTU(DTU),
  203. Builder(CI) {
  204. assert(Size > 0 && "zero blocks");
  205. // Scale the max size down if the target can load more bytes than we need.
  206. llvm::ArrayRef<unsigned> LoadSizes(Options.LoadSizes);
  207. while (!LoadSizes.empty() && LoadSizes.front() > Size) {
  208. LoadSizes = LoadSizes.drop_front();
  209. }
  210. assert(!LoadSizes.empty() && "cannot load Size bytes");
  211. MaxLoadSize = LoadSizes.front();
  212. // Compute the decomposition.
  213. unsigned GreedyNumLoadsNonOneByte = 0;
  214. LoadSequence = computeGreedyLoadSequence(Size, LoadSizes, Options.MaxNumLoads,
  215. GreedyNumLoadsNonOneByte);
  216. NumLoadsNonOneByte = GreedyNumLoadsNonOneByte;
  217. assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
  218. // If we allow overlapping loads and the load sequence is not already optimal,
  219. // use overlapping loads.
  220. if (Options.AllowOverlappingLoads &&
  221. (LoadSequence.empty() || LoadSequence.size() > 2)) {
  222. unsigned OverlappingNumLoadsNonOneByte = 0;
  223. auto OverlappingLoads = computeOverlappingLoadSequence(
  224. Size, MaxLoadSize, Options.MaxNumLoads, OverlappingNumLoadsNonOneByte);
  225. if (!OverlappingLoads.empty() &&
  226. (LoadSequence.empty() ||
  227. OverlappingLoads.size() < LoadSequence.size())) {
  228. LoadSequence = OverlappingLoads;
  229. NumLoadsNonOneByte = OverlappingNumLoadsNonOneByte;
  230. }
  231. }
  232. assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
  233. }
  234. unsigned MemCmpExpansion::getNumBlocks() {
  235. if (IsUsedForZeroCmp)
  236. return getNumLoads() / NumLoadsPerBlockForZeroCmp +
  237. (getNumLoads() % NumLoadsPerBlockForZeroCmp != 0 ? 1 : 0);
  238. return getNumLoads();
  239. }
  240. void MemCmpExpansion::createLoadCmpBlocks() {
  241. for (unsigned i = 0; i < getNumBlocks(); i++) {
  242. BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
  243. EndBlock->getParent(), EndBlock);
  244. LoadCmpBlocks.push_back(BB);
  245. }
  246. }
  247. void MemCmpExpansion::createResultBlock() {
  248. ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
  249. EndBlock->getParent(), EndBlock);
  250. }
  251. MemCmpExpansion::LoadPair MemCmpExpansion::getLoadPair(Type *LoadSizeType,
  252. bool NeedsBSwap,
  253. Type *CmpSizeType,
  254. unsigned OffsetBytes) {
  255. // Get the memory source at offset `OffsetBytes`.
  256. Value *LhsSource = CI->getArgOperand(0);
  257. Value *RhsSource = CI->getArgOperand(1);
  258. Align LhsAlign = LhsSource->getPointerAlignment(DL);
  259. Align RhsAlign = RhsSource->getPointerAlignment(DL);
  260. if (OffsetBytes > 0) {
  261. auto *ByteType = Type::getInt8Ty(CI->getContext());
  262. LhsSource = Builder.CreateConstGEP1_64(
  263. ByteType, Builder.CreateBitCast(LhsSource, ByteType->getPointerTo()),
  264. OffsetBytes);
  265. RhsSource = Builder.CreateConstGEP1_64(
  266. ByteType, Builder.CreateBitCast(RhsSource, ByteType->getPointerTo()),
  267. OffsetBytes);
  268. LhsAlign = commonAlignment(LhsAlign, OffsetBytes);
  269. RhsAlign = commonAlignment(RhsAlign, OffsetBytes);
  270. }
  271. LhsSource = Builder.CreateBitCast(LhsSource, LoadSizeType->getPointerTo());
  272. RhsSource = Builder.CreateBitCast(RhsSource, LoadSizeType->getPointerTo());
  273. // Create a constant or a load from the source.
  274. Value *Lhs = nullptr;
  275. if (auto *C = dyn_cast<Constant>(LhsSource))
  276. Lhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
  277. if (!Lhs)
  278. Lhs = Builder.CreateAlignedLoad(LoadSizeType, LhsSource, LhsAlign);
  279. Value *Rhs = nullptr;
  280. if (auto *C = dyn_cast<Constant>(RhsSource))
  281. Rhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
  282. if (!Rhs)
  283. Rhs = Builder.CreateAlignedLoad(LoadSizeType, RhsSource, RhsAlign);
  284. // Swap bytes if required.
  285. if (NeedsBSwap) {
  286. Function *Bswap = Intrinsic::getDeclaration(CI->getModule(),
  287. Intrinsic::bswap, LoadSizeType);
  288. Lhs = Builder.CreateCall(Bswap, Lhs);
  289. Rhs = Builder.CreateCall(Bswap, Rhs);
  290. }
  291. // Zero extend if required.
  292. if (CmpSizeType != nullptr && CmpSizeType != LoadSizeType) {
  293. Lhs = Builder.CreateZExt(Lhs, CmpSizeType);
  294. Rhs = Builder.CreateZExt(Rhs, CmpSizeType);
  295. }
  296. return {Lhs, Rhs};
  297. }
  298. // This function creates the IR instructions for loading and comparing 1 byte.
  299. // It loads 1 byte from each source of the memcmp parameters with the given
  300. // GEPIndex. It then subtracts the two loaded values and adds this result to the
  301. // final phi node for selecting the memcmp result.
  302. void MemCmpExpansion::emitLoadCompareByteBlock(unsigned BlockIndex,
  303. unsigned OffsetBytes) {
  304. BasicBlock *BB = LoadCmpBlocks[BlockIndex];
  305. Builder.SetInsertPoint(BB);
  306. const LoadPair Loads =
  307. getLoadPair(Type::getInt8Ty(CI->getContext()), /*NeedsBSwap=*/false,
  308. Type::getInt32Ty(CI->getContext()), OffsetBytes);
  309. Value *Diff = Builder.CreateSub(Loads.Lhs, Loads.Rhs);
  310. PhiRes->addIncoming(Diff, BB);
  311. if (BlockIndex < (LoadCmpBlocks.size() - 1)) {
  312. // Early exit branch if difference found to EndBlock. Otherwise, continue to
  313. // next LoadCmpBlock,
  314. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
  315. ConstantInt::get(Diff->getType(), 0));
  316. BranchInst *CmpBr =
  317. BranchInst::Create(EndBlock, LoadCmpBlocks[BlockIndex + 1], Cmp);
  318. Builder.Insert(CmpBr);
  319. if (DTU)
  320. DTU->applyUpdates(
  321. {{DominatorTree::Insert, BB, EndBlock},
  322. {DominatorTree::Insert, BB, LoadCmpBlocks[BlockIndex + 1]}});
  323. } else {
  324. // The last block has an unconditional branch to EndBlock.
  325. BranchInst *CmpBr = BranchInst::Create(EndBlock);
  326. Builder.Insert(CmpBr);
  327. if (DTU)
  328. DTU->applyUpdates({{DominatorTree::Insert, BB, EndBlock}});
  329. }
  330. }
  331. /// Generate an equality comparison for one or more pairs of loaded values.
  332. /// This is used in the case where the memcmp() call is compared equal or not
  333. /// equal to zero.
  334. Value *MemCmpExpansion::getCompareLoadPairs(unsigned BlockIndex,
  335. unsigned &LoadIndex) {
  336. assert(LoadIndex < getNumLoads() &&
  337. "getCompareLoadPairs() called with no remaining loads");
  338. std::vector<Value *> XorList, OrList;
  339. Value *Diff = nullptr;
  340. const unsigned NumLoads =
  341. std::min(getNumLoads() - LoadIndex, NumLoadsPerBlockForZeroCmp);
  342. // For a single-block expansion, start inserting before the memcmp call.
  343. if (LoadCmpBlocks.empty())
  344. Builder.SetInsertPoint(CI);
  345. else
  346. Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
  347. Value *Cmp = nullptr;
  348. // If we have multiple loads per block, we need to generate a composite
  349. // comparison using xor+or. The type for the combinations is the largest load
  350. // type.
  351. IntegerType *const MaxLoadType =
  352. NumLoads == 1 ? nullptr
  353. : IntegerType::get(CI->getContext(), MaxLoadSize * 8);
  354. for (unsigned i = 0; i < NumLoads; ++i, ++LoadIndex) {
  355. const LoadEntry &CurLoadEntry = LoadSequence[LoadIndex];
  356. const LoadPair Loads = getLoadPair(
  357. IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8),
  358. /*NeedsBSwap=*/false, MaxLoadType, CurLoadEntry.Offset);
  359. if (NumLoads != 1) {
  360. // If we have multiple loads per block, we need to generate a composite
  361. // comparison using xor+or.
  362. Diff = Builder.CreateXor(Loads.Lhs, Loads.Rhs);
  363. Diff = Builder.CreateZExt(Diff, MaxLoadType);
  364. XorList.push_back(Diff);
  365. } else {
  366. // If there's only one load per block, we just compare the loaded values.
  367. Cmp = Builder.CreateICmpNE(Loads.Lhs, Loads.Rhs);
  368. }
  369. }
  370. auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
  371. std::vector<Value *> OutList;
  372. for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
  373. Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
  374. OutList.push_back(Or);
  375. }
  376. if (InList.size() % 2 != 0)
  377. OutList.push_back(InList.back());
  378. return OutList;
  379. };
  380. if (!Cmp) {
  381. // Pairwise OR the XOR results.
  382. OrList = pairWiseOr(XorList);
  383. // Pairwise OR the OR results until one result left.
  384. while (OrList.size() != 1) {
  385. OrList = pairWiseOr(OrList);
  386. }
  387. assert(Diff && "Failed to find comparison diff");
  388. Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
  389. }
  390. return Cmp;
  391. }
  392. void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
  393. unsigned &LoadIndex) {
  394. Value *Cmp = getCompareLoadPairs(BlockIndex, LoadIndex);
  395. BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
  396. ? EndBlock
  397. : LoadCmpBlocks[BlockIndex + 1];
  398. // Early exit branch if difference found to ResultBlock. Otherwise,
  399. // continue to next LoadCmpBlock or EndBlock.
  400. BasicBlock *BB = Builder.GetInsertBlock();
  401. BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
  402. Builder.Insert(CmpBr);
  403. if (DTU)
  404. DTU->applyUpdates({{DominatorTree::Insert, BB, ResBlock.BB},
  405. {DominatorTree::Insert, BB, NextBB}});
  406. // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
  407. // since early exit to ResultBlock was not taken (no difference was found in
  408. // any of the bytes).
  409. if (BlockIndex == LoadCmpBlocks.size() - 1) {
  410. Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
  411. PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
  412. }
  413. }
  414. // This function creates the IR intructions for loading and comparing using the
  415. // given LoadSize. It loads the number of bytes specified by LoadSize from each
  416. // source of the memcmp parameters. It then does a subtract to see if there was
  417. // a difference in the loaded values. If a difference is found, it branches
  418. // with an early exit to the ResultBlock for calculating which source was
  419. // larger. Otherwise, it falls through to the either the next LoadCmpBlock or
  420. // the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
  421. // a special case through emitLoadCompareByteBlock. The special handling can
  422. // simply subtract the loaded values and add it to the result phi node.
  423. void MemCmpExpansion::emitLoadCompareBlock(unsigned BlockIndex) {
  424. // There is one load per block in this case, BlockIndex == LoadIndex.
  425. const LoadEntry &CurLoadEntry = LoadSequence[BlockIndex];
  426. if (CurLoadEntry.LoadSize == 1) {
  427. MemCmpExpansion::emitLoadCompareByteBlock(BlockIndex, CurLoadEntry.Offset);
  428. return;
  429. }
  430. Type *LoadSizeType =
  431. IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8);
  432. Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
  433. assert(CurLoadEntry.LoadSize <= MaxLoadSize && "Unexpected load type");
  434. Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
  435. const LoadPair Loads =
  436. getLoadPair(LoadSizeType, /*NeedsBSwap=*/DL.isLittleEndian(), MaxLoadType,
  437. CurLoadEntry.Offset);
  438. // Add the loaded values to the phi nodes for calculating memcmp result only
  439. // if result is not used in a zero equality.
  440. if (!IsUsedForZeroCmp) {
  441. ResBlock.PhiSrc1->addIncoming(Loads.Lhs, LoadCmpBlocks[BlockIndex]);
  442. ResBlock.PhiSrc2->addIncoming(Loads.Rhs, LoadCmpBlocks[BlockIndex]);
  443. }
  444. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Loads.Lhs, Loads.Rhs);
  445. BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
  446. ? EndBlock
  447. : LoadCmpBlocks[BlockIndex + 1];
  448. // Early exit branch if difference found to ResultBlock. Otherwise, continue
  449. // to next LoadCmpBlock or EndBlock.
  450. BasicBlock *BB = Builder.GetInsertBlock();
  451. BranchInst *CmpBr = BranchInst::Create(NextBB, ResBlock.BB, Cmp);
  452. Builder.Insert(CmpBr);
  453. if (DTU)
  454. DTU->applyUpdates({{DominatorTree::Insert, BB, NextBB},
  455. {DominatorTree::Insert, BB, ResBlock.BB}});
  456. // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
  457. // since early exit to ResultBlock was not taken (no difference was found in
  458. // any of the bytes).
  459. if (BlockIndex == LoadCmpBlocks.size() - 1) {
  460. Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
  461. PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
  462. }
  463. }
  464. // This function populates the ResultBlock with a sequence to calculate the
  465. // memcmp result. It compares the two loaded source values and returns -1 if
  466. // src1 < src2 and 1 if src1 > src2.
  467. void MemCmpExpansion::emitMemCmpResultBlock() {
  468. // Special case: if memcmp result is used in a zero equality, result does not
  469. // need to be calculated and can simply return 1.
  470. if (IsUsedForZeroCmp) {
  471. BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
  472. Builder.SetInsertPoint(ResBlock.BB, InsertPt);
  473. Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
  474. PhiRes->addIncoming(Res, ResBlock.BB);
  475. BranchInst *NewBr = BranchInst::Create(EndBlock);
  476. Builder.Insert(NewBr);
  477. if (DTU)
  478. DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
  479. return;
  480. }
  481. BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
  482. Builder.SetInsertPoint(ResBlock.BB, InsertPt);
  483. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
  484. ResBlock.PhiSrc2);
  485. Value *Res =
  486. Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1),
  487. ConstantInt::get(Builder.getInt32Ty(), 1));
  488. PhiRes->addIncoming(Res, ResBlock.BB);
  489. BranchInst *NewBr = BranchInst::Create(EndBlock);
  490. Builder.Insert(NewBr);
  491. if (DTU)
  492. DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
  493. }
  494. void MemCmpExpansion::setupResultBlockPHINodes() {
  495. Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
  496. Builder.SetInsertPoint(ResBlock.BB);
  497. // Note: this assumes one load per block.
  498. ResBlock.PhiSrc1 =
  499. Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src1");
  500. ResBlock.PhiSrc2 =
  501. Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src2");
  502. }
  503. void MemCmpExpansion::setupEndBlockPHINodes() {
  504. Builder.SetInsertPoint(&EndBlock->front());
  505. PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
  506. }
  507. Value *MemCmpExpansion::getMemCmpExpansionZeroCase() {
  508. unsigned LoadIndex = 0;
  509. // This loop populates each of the LoadCmpBlocks with the IR sequence to
  510. // handle multiple loads per block.
  511. for (unsigned I = 0; I < getNumBlocks(); ++I) {
  512. emitLoadCompareBlockMultipleLoads(I, LoadIndex);
  513. }
  514. emitMemCmpResultBlock();
  515. return PhiRes;
  516. }
  517. /// A memcmp expansion that compares equality with 0 and only has one block of
  518. /// load and compare can bypass the compare, branch, and phi IR that is required
  519. /// in the general case.
  520. Value *MemCmpExpansion::getMemCmpEqZeroOneBlock() {
  521. unsigned LoadIndex = 0;
  522. Value *Cmp = getCompareLoadPairs(0, LoadIndex);
  523. assert(LoadIndex == getNumLoads() && "some entries were not consumed");
  524. return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext()));
  525. }
  526. /// A memcmp expansion that only has one block of load and compare can bypass
  527. /// the compare, branch, and phi IR that is required in the general case.
  528. Value *MemCmpExpansion::getMemCmpOneBlock() {
  529. Type *LoadSizeType = IntegerType::get(CI->getContext(), Size * 8);
  530. bool NeedsBSwap = DL.isLittleEndian() && Size != 1;
  531. // The i8 and i16 cases don't need compares. We zext the loaded values and
  532. // subtract them to get the suitable negative, zero, or positive i32 result.
  533. if (Size < 4) {
  534. const LoadPair Loads =
  535. getLoadPair(LoadSizeType, NeedsBSwap, Builder.getInt32Ty(),
  536. /*Offset*/ 0);
  537. return Builder.CreateSub(Loads.Lhs, Loads.Rhs);
  538. }
  539. const LoadPair Loads = getLoadPair(LoadSizeType, NeedsBSwap, LoadSizeType,
  540. /*Offset*/ 0);
  541. // The result of memcmp is negative, zero, or positive, so produce that by
  542. // subtracting 2 extended compare bits: sub (ugt, ult).
  543. // If a target prefers to use selects to get -1/0/1, they should be able
  544. // to transform this later. The inverse transform (going from selects to math)
  545. // may not be possible in the DAG because the selects got converted into
  546. // branches before we got there.
  547. Value *CmpUGT = Builder.CreateICmpUGT(Loads.Lhs, Loads.Rhs);
  548. Value *CmpULT = Builder.CreateICmpULT(Loads.Lhs, Loads.Rhs);
  549. Value *ZextUGT = Builder.CreateZExt(CmpUGT, Builder.getInt32Ty());
  550. Value *ZextULT = Builder.CreateZExt(CmpULT, Builder.getInt32Ty());
  551. return Builder.CreateSub(ZextUGT, ZextULT);
  552. }
  553. // This function expands the memcmp call into an inline expansion and returns
  554. // the memcmp result.
  555. Value *MemCmpExpansion::getMemCmpExpansion() {
  556. // Create the basic block framework for a multi-block expansion.
  557. if (getNumBlocks() != 1) {
  558. BasicBlock *StartBlock = CI->getParent();
  559. EndBlock = SplitBlock(StartBlock, CI, DTU, /*LI=*/nullptr,
  560. /*MSSAU=*/nullptr, "endblock");
  561. setupEndBlockPHINodes();
  562. createResultBlock();
  563. // If return value of memcmp is not used in a zero equality, we need to
  564. // calculate which source was larger. The calculation requires the
  565. // two loaded source values of each load compare block.
  566. // These will be saved in the phi nodes created by setupResultBlockPHINodes.
  567. if (!IsUsedForZeroCmp) setupResultBlockPHINodes();
  568. // Create the number of required load compare basic blocks.
  569. createLoadCmpBlocks();
  570. // Update the terminator added by SplitBlock to branch to the first
  571. // LoadCmpBlock.
  572. StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]);
  573. if (DTU)
  574. DTU->applyUpdates({{DominatorTree::Insert, StartBlock, LoadCmpBlocks[0]},
  575. {DominatorTree::Delete, StartBlock, EndBlock}});
  576. }
  577. Builder.SetCurrentDebugLocation(CI->getDebugLoc());
  578. if (IsUsedForZeroCmp)
  579. return getNumBlocks() == 1 ? getMemCmpEqZeroOneBlock()
  580. : getMemCmpExpansionZeroCase();
  581. if (getNumBlocks() == 1)
  582. return getMemCmpOneBlock();
  583. for (unsigned I = 0; I < getNumBlocks(); ++I) {
  584. emitLoadCompareBlock(I);
  585. }
  586. emitMemCmpResultBlock();
  587. return PhiRes;
  588. }
  589. // This function checks to see if an expansion of memcmp can be generated.
  590. // It checks for constant compare size that is less than the max inline size.
  591. // If an expansion cannot occur, returns false to leave as a library call.
  592. // Otherwise, the library call is replaced with a new IR instruction sequence.
  593. /// We want to transform:
  594. /// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
  595. /// To:
  596. /// loadbb:
  597. /// %0 = bitcast i32* %buffer2 to i8*
  598. /// %1 = bitcast i32* %buffer1 to i8*
  599. /// %2 = bitcast i8* %1 to i64*
  600. /// %3 = bitcast i8* %0 to i64*
  601. /// %4 = load i64, i64* %2
  602. /// %5 = load i64, i64* %3
  603. /// %6 = call i64 @llvm.bswap.i64(i64 %4)
  604. /// %7 = call i64 @llvm.bswap.i64(i64 %5)
  605. /// %8 = sub i64 %6, %7
  606. /// %9 = icmp ne i64 %8, 0
  607. /// br i1 %9, label %res_block, label %loadbb1
  608. /// res_block: ; preds = %loadbb2,
  609. /// %loadbb1, %loadbb
  610. /// %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
  611. /// %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
  612. /// %10 = icmp ult i64 %phi.src1, %phi.src2
  613. /// %11 = select i1 %10, i32 -1, i32 1
  614. /// br label %endblock
  615. /// loadbb1: ; preds = %loadbb
  616. /// %12 = bitcast i32* %buffer2 to i8*
  617. /// %13 = bitcast i32* %buffer1 to i8*
  618. /// %14 = bitcast i8* %13 to i32*
  619. /// %15 = bitcast i8* %12 to i32*
  620. /// %16 = getelementptr i32, i32* %14, i32 2
  621. /// %17 = getelementptr i32, i32* %15, i32 2
  622. /// %18 = load i32, i32* %16
  623. /// %19 = load i32, i32* %17
  624. /// %20 = call i32 @llvm.bswap.i32(i32 %18)
  625. /// %21 = call i32 @llvm.bswap.i32(i32 %19)
  626. /// %22 = zext i32 %20 to i64
  627. /// %23 = zext i32 %21 to i64
  628. /// %24 = sub i64 %22, %23
  629. /// %25 = icmp ne i64 %24, 0
  630. /// br i1 %25, label %res_block, label %loadbb2
  631. /// loadbb2: ; preds = %loadbb1
  632. /// %26 = bitcast i32* %buffer2 to i8*
  633. /// %27 = bitcast i32* %buffer1 to i8*
  634. /// %28 = bitcast i8* %27 to i16*
  635. /// %29 = bitcast i8* %26 to i16*
  636. /// %30 = getelementptr i16, i16* %28, i16 6
  637. /// %31 = getelementptr i16, i16* %29, i16 6
  638. /// %32 = load i16, i16* %30
  639. /// %33 = load i16, i16* %31
  640. /// %34 = call i16 @llvm.bswap.i16(i16 %32)
  641. /// %35 = call i16 @llvm.bswap.i16(i16 %33)
  642. /// %36 = zext i16 %34 to i64
  643. /// %37 = zext i16 %35 to i64
  644. /// %38 = sub i64 %36, %37
  645. /// %39 = icmp ne i64 %38, 0
  646. /// br i1 %39, label %res_block, label %loadbb3
  647. /// loadbb3: ; preds = %loadbb2
  648. /// %40 = bitcast i32* %buffer2 to i8*
  649. /// %41 = bitcast i32* %buffer1 to i8*
  650. /// %42 = getelementptr i8, i8* %41, i8 14
  651. /// %43 = getelementptr i8, i8* %40, i8 14
  652. /// %44 = load i8, i8* %42
  653. /// %45 = load i8, i8* %43
  654. /// %46 = zext i8 %44 to i32
  655. /// %47 = zext i8 %45 to i32
  656. /// %48 = sub i32 %46, %47
  657. /// br label %endblock
  658. /// endblock: ; preds = %res_block,
  659. /// %loadbb3
  660. /// %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
  661. /// ret i32 %phi.res
  662. static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
  663. const TargetLowering *TLI, const DataLayout *DL,
  664. ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
  665. DomTreeUpdater *DTU, const bool IsBCmp) {
  666. NumMemCmpCalls++;
  667. // Early exit from expansion if -Oz.
  668. if (CI->getFunction()->hasMinSize())
  669. return false;
  670. // Early exit from expansion if size is not a constant.
  671. ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  672. if (!SizeCast) {
  673. NumMemCmpNotConstant++;
  674. return false;
  675. }
  676. const uint64_t SizeVal = SizeCast->getZExtValue();
  677. if (SizeVal == 0) {
  678. return false;
  679. }
  680. // TTI call to check if target would like to expand memcmp. Also, get the
  681. // available load sizes.
  682. const bool IsUsedForZeroCmp =
  683. IsBCmp || isOnlyUsedInZeroEqualityComparison(CI);
  684. bool OptForSize = CI->getFunction()->hasOptSize() ||
  685. llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
  686. auto Options = TTI->enableMemCmpExpansion(OptForSize,
  687. IsUsedForZeroCmp);
  688. if (!Options) return false;
  689. if (MemCmpEqZeroNumLoadsPerBlock.getNumOccurrences())
  690. Options.NumLoadsPerBlock = MemCmpEqZeroNumLoadsPerBlock;
  691. if (OptForSize &&
  692. MaxLoadsPerMemcmpOptSize.getNumOccurrences())
  693. Options.MaxNumLoads = MaxLoadsPerMemcmpOptSize;
  694. if (!OptForSize && MaxLoadsPerMemcmp.getNumOccurrences())
  695. Options.MaxNumLoads = MaxLoadsPerMemcmp;
  696. MemCmpExpansion Expansion(CI, SizeVal, Options, IsUsedForZeroCmp, *DL, DTU);
  697. // Don't expand if this will require more loads than desired by the target.
  698. if (Expansion.getNumLoads() == 0) {
  699. NumMemCmpGreaterThanMax++;
  700. return false;
  701. }
  702. NumMemCmpInlined++;
  703. Value *Res = Expansion.getMemCmpExpansion();
  704. // Replace call with result of expansion and erase call.
  705. CI->replaceAllUsesWith(Res);
  706. CI->eraseFromParent();
  707. return true;
  708. }
  709. class ExpandMemCmpPass : public FunctionPass {
  710. public:
  711. static char ID;
  712. ExpandMemCmpPass() : FunctionPass(ID) {
  713. initializeExpandMemCmpPassPass(*PassRegistry::getPassRegistry());
  714. }
  715. bool runOnFunction(Function &F) override {
  716. if (skipFunction(F)) return false;
  717. auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
  718. if (!TPC) {
  719. return false;
  720. }
  721. const TargetLowering* TL =
  722. TPC->getTM<TargetMachine>().getSubtargetImpl(F)->getTargetLowering();
  723. const TargetLibraryInfo *TLI =
  724. &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  725. const TargetTransformInfo *TTI =
  726. &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  727. auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  728. auto *BFI = (PSI && PSI->hasProfileSummary()) ?
  729. &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
  730. nullptr;
  731. DominatorTree *DT = nullptr;
  732. if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
  733. DT = &DTWP->getDomTree();
  734. auto PA = runImpl(F, TLI, TTI, TL, PSI, BFI, DT);
  735. return !PA.areAllPreserved();
  736. }
  737. private:
  738. void getAnalysisUsage(AnalysisUsage &AU) const override {
  739. AU.addRequired<TargetLibraryInfoWrapperPass>();
  740. AU.addRequired<TargetTransformInfoWrapperPass>();
  741. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  742. AU.addPreserved<DominatorTreeWrapperPass>();
  743. LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
  744. FunctionPass::getAnalysisUsage(AU);
  745. }
  746. PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
  747. const TargetTransformInfo *TTI,
  748. const TargetLowering *TL, ProfileSummaryInfo *PSI,
  749. BlockFrequencyInfo *BFI, DominatorTree *DT);
  750. // Returns true if a change was made.
  751. bool runOnBlock(BasicBlock &BB, const TargetLibraryInfo *TLI,
  752. const TargetTransformInfo *TTI, const TargetLowering *TL,
  753. const DataLayout &DL, ProfileSummaryInfo *PSI,
  754. BlockFrequencyInfo *BFI, DomTreeUpdater *DTU);
  755. };
  756. bool ExpandMemCmpPass::runOnBlock(BasicBlock &BB, const TargetLibraryInfo *TLI,
  757. const TargetTransformInfo *TTI,
  758. const TargetLowering *TL,
  759. const DataLayout &DL, ProfileSummaryInfo *PSI,
  760. BlockFrequencyInfo *BFI,
  761. DomTreeUpdater *DTU) {
  762. for (Instruction& I : BB) {
  763. CallInst *CI = dyn_cast<CallInst>(&I);
  764. if (!CI) {
  765. continue;
  766. }
  767. LibFunc Func;
  768. if (TLI->getLibFunc(*CI, Func) &&
  769. (Func == LibFunc_memcmp || Func == LibFunc_bcmp) &&
  770. expandMemCmp(CI, TTI, TL, &DL, PSI, BFI, DTU, Func == LibFunc_bcmp)) {
  771. return true;
  772. }
  773. }
  774. return false;
  775. }
  776. PreservedAnalyses
  777. ExpandMemCmpPass::runImpl(Function &F, const TargetLibraryInfo *TLI,
  778. const TargetTransformInfo *TTI,
  779. const TargetLowering *TL, ProfileSummaryInfo *PSI,
  780. BlockFrequencyInfo *BFI, DominatorTree *DT) {
  781. std::optional<DomTreeUpdater> DTU;
  782. if (DT)
  783. DTU.emplace(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  784. const DataLayout& DL = F.getParent()->getDataLayout();
  785. bool MadeChanges = false;
  786. for (auto BBIt = F.begin(); BBIt != F.end();) {
  787. if (runOnBlock(*BBIt, TLI, TTI, TL, DL, PSI, BFI, DTU ? &*DTU : nullptr)) {
  788. MadeChanges = true;
  789. // If changes were made, restart the function from the beginning, since
  790. // the structure of the function was changed.
  791. BBIt = F.begin();
  792. } else {
  793. ++BBIt;
  794. }
  795. }
  796. if (MadeChanges)
  797. for (BasicBlock &BB : F)
  798. SimplifyInstructionsInBlock(&BB);
  799. if (!MadeChanges)
  800. return PreservedAnalyses::all();
  801. PreservedAnalyses PA;
  802. PA.preserve<DominatorTreeAnalysis>();
  803. return PA;
  804. }
  805. } // namespace
  806. char ExpandMemCmpPass::ID = 0;
  807. INITIALIZE_PASS_BEGIN(ExpandMemCmpPass, "expandmemcmp",
  808. "Expand memcmp() to load/stores", false, false)
  809. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  810. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  811. INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
  812. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  813. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  814. INITIALIZE_PASS_END(ExpandMemCmpPass, "expandmemcmp",
  815. "Expand memcmp() to load/stores", false, false)
  816. FunctionPass *llvm::createExpandMemCmpPass() {
  817. return new ExpandMemCmpPass();
  818. }