xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/ExpandMemCmp.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===--- ExpandMemCmp.cpp - Expand memcmp() to load/stores ----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass tries to expand memcmp() calls into optimally-sized loads and
100b57cec5SDimitry Andric // compares for the target.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
145f757f3fSDimitry Andric #include "llvm/CodeGen/ExpandMemCmp.h"
150b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
160b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
17fe6060f1SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
18480093f4SDimitry Andric #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
19480093f4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
25fe6060f1SDimitry Andric #include "llvm/IR/Dominators.h"
260b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
275f757f3fSDimitry Andric #include "llvm/IR/PatternMatch.h"
28480093f4SDimitry Andric #include "llvm/InitializePasses.h"
29fe6060f1SDimitry Andric #include "llvm/Target/TargetMachine.h"
30fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
315ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/Local.h"
32480093f4SDimitry Andric #include "llvm/Transforms/Utils/SizeOpts.h"
33bdd1243dSDimitry Andric #include <optional>
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric using namespace llvm;
365f757f3fSDimitry Andric using namespace llvm::PatternMatch;
370b57cec5SDimitry Andric 
3881ad6265SDimitry Andric namespace llvm {
3981ad6265SDimitry Andric class TargetLowering;
4081ad6265SDimitry Andric }
4181ad6265SDimitry Andric 
425f757f3fSDimitry Andric #define DEBUG_TYPE "expand-memcmp"
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric STATISTIC(NumMemCmpCalls, "Number of memcmp calls");
450b57cec5SDimitry Andric STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size");
460b57cec5SDimitry Andric STATISTIC(NumMemCmpGreaterThanMax,
470b57cec5SDimitry Andric           "Number of memcmp calls with size greater than max size");
480b57cec5SDimitry Andric STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls");
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric static cl::opt<unsigned> MemCmpEqZeroNumLoadsPerBlock(
510b57cec5SDimitry Andric     "memcmp-num-loads-per-block", cl::Hidden, cl::init(1),
520b57cec5SDimitry Andric     cl::desc("The number of loads per basic block for inline expansion of "
530b57cec5SDimitry Andric              "memcmp that is only being compared against zero."));
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric static cl::opt<unsigned> MaxLoadsPerMemcmp(
560b57cec5SDimitry Andric     "max-loads-per-memcmp", cl::Hidden,
570b57cec5SDimitry Andric     cl::desc("Set maximum number of loads used in expanded memcmp"));
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric static cl::opt<unsigned> MaxLoadsPerMemcmpOptSize(
600b57cec5SDimitry Andric     "max-loads-per-memcmp-opt-size", cl::Hidden,
610b57cec5SDimitry Andric     cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz"));
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric namespace {
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric // This class provides helper functions to expand a memcmp library call into an
670b57cec5SDimitry Andric // inline expansion.
680b57cec5SDimitry Andric class MemCmpExpansion {
690b57cec5SDimitry Andric   struct ResultBlock {
700b57cec5SDimitry Andric     BasicBlock *BB = nullptr;
710b57cec5SDimitry Andric     PHINode *PhiSrc1 = nullptr;
720b57cec5SDimitry Andric     PHINode *PhiSrc2 = nullptr;
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric     ResultBlock() = default;
750b57cec5SDimitry Andric   };
760b57cec5SDimitry Andric 
7706c3fb27SDimitry Andric   CallInst *const CI = nullptr;
780b57cec5SDimitry Andric   ResultBlock ResBlock;
790b57cec5SDimitry Andric   const uint64_t Size;
801fd87a68SDimitry Andric   unsigned MaxLoadSize = 0;
811fd87a68SDimitry Andric   uint64_t NumLoadsNonOneByte = 0;
820b57cec5SDimitry Andric   const uint64_t NumLoadsPerBlockForZeroCmp;
830b57cec5SDimitry Andric   std::vector<BasicBlock *> LoadCmpBlocks;
8406c3fb27SDimitry Andric   BasicBlock *EndBlock = nullptr;
8506c3fb27SDimitry Andric   PHINode *PhiRes = nullptr;
860b57cec5SDimitry Andric   const bool IsUsedForZeroCmp;
870b57cec5SDimitry Andric   const DataLayout &DL;
8806c3fb27SDimitry Andric   DomTreeUpdater *DTU = nullptr;
890b57cec5SDimitry Andric   IRBuilder<> Builder;
900b57cec5SDimitry Andric   // Represents the decomposition in blocks of the expansion. For example,
910b57cec5SDimitry Andric   // comparing 33 bytes on X86+sse can be done with 2x16-byte loads and
925ffd83dbSDimitry Andric   // 1x1-byte load, which would be represented as [{16, 0}, {16, 16}, {1, 32}.
930b57cec5SDimitry Andric   struct LoadEntry {
LoadEntry__anon455dbdd30111::MemCmpExpansion::LoadEntry940b57cec5SDimitry Andric     LoadEntry(unsigned LoadSize, uint64_t Offset)
950b57cec5SDimitry Andric         : LoadSize(LoadSize), Offset(Offset) {
960b57cec5SDimitry Andric     }
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric     // The size of the load for this block, in bytes.
990b57cec5SDimitry Andric     unsigned LoadSize;
1000b57cec5SDimitry Andric     // The offset of this load from the base pointer, in bytes.
1010b57cec5SDimitry Andric     uint64_t Offset;
1020b57cec5SDimitry Andric   };
1030b57cec5SDimitry Andric   using LoadEntryVector = SmallVector<LoadEntry, 8>;
1040b57cec5SDimitry Andric   LoadEntryVector LoadSequence;
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric   void createLoadCmpBlocks();
1070b57cec5SDimitry Andric   void createResultBlock();
1080b57cec5SDimitry Andric   void setupResultBlockPHINodes();
1090b57cec5SDimitry Andric   void setupEndBlockPHINodes();
1100b57cec5SDimitry Andric   Value *getCompareLoadPairs(unsigned BlockIndex, unsigned &LoadIndex);
1110b57cec5SDimitry Andric   void emitLoadCompareBlock(unsigned BlockIndex);
1120b57cec5SDimitry Andric   void emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
1130b57cec5SDimitry Andric                                          unsigned &LoadIndex);
1140b57cec5SDimitry Andric   void emitLoadCompareByteBlock(unsigned BlockIndex, unsigned OffsetBytes);
1150b57cec5SDimitry Andric   void emitMemCmpResultBlock();
1160b57cec5SDimitry Andric   Value *getMemCmpExpansionZeroCase();
1170b57cec5SDimitry Andric   Value *getMemCmpEqZeroOneBlock();
1180b57cec5SDimitry Andric   Value *getMemCmpOneBlock();
1195ffd83dbSDimitry Andric   struct LoadPair {
1205ffd83dbSDimitry Andric     Value *Lhs = nullptr;
1215ffd83dbSDimitry Andric     Value *Rhs = nullptr;
1225ffd83dbSDimitry Andric   };
1235f757f3fSDimitry Andric   LoadPair getLoadPair(Type *LoadSizeType, Type *BSwapSizeType,
1245f757f3fSDimitry Andric                        Type *CmpSizeType, unsigned OffsetBytes);
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric   static LoadEntryVector
1270b57cec5SDimitry Andric   computeGreedyLoadSequence(uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
1280b57cec5SDimitry Andric                             unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte);
1290b57cec5SDimitry Andric   static LoadEntryVector
1300b57cec5SDimitry Andric   computeOverlappingLoadSequence(uint64_t Size, unsigned MaxLoadSize,
1310b57cec5SDimitry Andric                                  unsigned MaxNumLoads,
1320b57cec5SDimitry Andric                                  unsigned &NumLoadsNonOneByte);
1330b57cec5SDimitry Andric 
1345f757f3fSDimitry Andric   static void optimiseLoadSequence(
1355f757f3fSDimitry Andric       LoadEntryVector &LoadSequence,
1365f757f3fSDimitry Andric       const TargetTransformInfo::MemCmpExpansionOptions &Options,
1375f757f3fSDimitry Andric       bool IsUsedForZeroCmp);
1385f757f3fSDimitry Andric 
1390b57cec5SDimitry Andric public:
1400b57cec5SDimitry Andric   MemCmpExpansion(CallInst *CI, uint64_t Size,
1410b57cec5SDimitry Andric                   const TargetTransformInfo::MemCmpExpansionOptions &Options,
142fe6060f1SDimitry Andric                   const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
143fe6060f1SDimitry Andric                   DomTreeUpdater *DTU);
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   unsigned getNumBlocks();
getNumLoads() const1460b57cec5SDimitry Andric   uint64_t getNumLoads() const { return LoadSequence.size(); }
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   Value *getMemCmpExpansion();
1490b57cec5SDimitry Andric };
1500b57cec5SDimitry Andric 
computeGreedyLoadSequence(uint64_t Size,llvm::ArrayRef<unsigned> LoadSizes,const unsigned MaxNumLoads,unsigned & NumLoadsNonOneByte)1510b57cec5SDimitry Andric MemCmpExpansion::LoadEntryVector MemCmpExpansion::computeGreedyLoadSequence(
1520b57cec5SDimitry Andric     uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
1530b57cec5SDimitry Andric     const unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte) {
1540b57cec5SDimitry Andric   NumLoadsNonOneByte = 0;
1550b57cec5SDimitry Andric   LoadEntryVector LoadSequence;
1560b57cec5SDimitry Andric   uint64_t Offset = 0;
1570b57cec5SDimitry Andric   while (Size && !LoadSizes.empty()) {
1580b57cec5SDimitry Andric     const unsigned LoadSize = LoadSizes.front();
1590b57cec5SDimitry Andric     const uint64_t NumLoadsForThisSize = Size / LoadSize;
1600b57cec5SDimitry Andric     if (LoadSequence.size() + NumLoadsForThisSize > MaxNumLoads) {
1610b57cec5SDimitry Andric       // Do not expand if the total number of loads is larger than what the
1620b57cec5SDimitry Andric       // target allows. Note that it's important that we exit before completing
1630b57cec5SDimitry Andric       // the expansion to avoid using a ton of memory to store the expansion for
1640b57cec5SDimitry Andric       // large sizes.
1650b57cec5SDimitry Andric       return {};
1660b57cec5SDimitry Andric     }
1670b57cec5SDimitry Andric     if (NumLoadsForThisSize > 0) {
1680b57cec5SDimitry Andric       for (uint64_t I = 0; I < NumLoadsForThisSize; ++I) {
1690b57cec5SDimitry Andric         LoadSequence.push_back({LoadSize, Offset});
1700b57cec5SDimitry Andric         Offset += LoadSize;
1710b57cec5SDimitry Andric       }
1720b57cec5SDimitry Andric       if (LoadSize > 1)
1730b57cec5SDimitry Andric         ++NumLoadsNonOneByte;
1740b57cec5SDimitry Andric       Size = Size % LoadSize;
1750b57cec5SDimitry Andric     }
1760b57cec5SDimitry Andric     LoadSizes = LoadSizes.drop_front();
1770b57cec5SDimitry Andric   }
1780b57cec5SDimitry Andric   return LoadSequence;
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric MemCmpExpansion::LoadEntryVector
computeOverlappingLoadSequence(uint64_t Size,const unsigned MaxLoadSize,const unsigned MaxNumLoads,unsigned & NumLoadsNonOneByte)1820b57cec5SDimitry Andric MemCmpExpansion::computeOverlappingLoadSequence(uint64_t Size,
1830b57cec5SDimitry Andric                                                 const unsigned MaxLoadSize,
1840b57cec5SDimitry Andric                                                 const unsigned MaxNumLoads,
1850b57cec5SDimitry Andric                                                 unsigned &NumLoadsNonOneByte) {
1860b57cec5SDimitry Andric   // These are already handled by the greedy approach.
1870b57cec5SDimitry Andric   if (Size < 2 || MaxLoadSize < 2)
1880b57cec5SDimitry Andric     return {};
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   // We try to do as many non-overlapping loads as possible starting from the
1910b57cec5SDimitry Andric   // beginning.
1920b57cec5SDimitry Andric   const uint64_t NumNonOverlappingLoads = Size / MaxLoadSize;
1930b57cec5SDimitry Andric   assert(NumNonOverlappingLoads && "there must be at least one load");
1940b57cec5SDimitry Andric   // There remain 0 to (MaxLoadSize - 1) bytes to load, this will be done with
1950b57cec5SDimitry Andric   // an overlapping load.
1960b57cec5SDimitry Andric   Size = Size - NumNonOverlappingLoads * MaxLoadSize;
1970b57cec5SDimitry Andric   // Bail if we do not need an overloapping store, this is already handled by
1980b57cec5SDimitry Andric   // the greedy approach.
1990b57cec5SDimitry Andric   if (Size == 0)
2000b57cec5SDimitry Andric     return {};
2010b57cec5SDimitry Andric   // Bail if the number of loads (non-overlapping + potential overlapping one)
2020b57cec5SDimitry Andric   // is larger than the max allowed.
2030b57cec5SDimitry Andric   if ((NumNonOverlappingLoads + 1) > MaxNumLoads)
2040b57cec5SDimitry Andric     return {};
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   // Add non-overlapping loads.
2070b57cec5SDimitry Andric   LoadEntryVector LoadSequence;
2080b57cec5SDimitry Andric   uint64_t Offset = 0;
2090b57cec5SDimitry Andric   for (uint64_t I = 0; I < NumNonOverlappingLoads; ++I) {
2100b57cec5SDimitry Andric     LoadSequence.push_back({MaxLoadSize, Offset});
2110b57cec5SDimitry Andric     Offset += MaxLoadSize;
2120b57cec5SDimitry Andric   }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   // Add the last overlapping load.
2150b57cec5SDimitry Andric   assert(Size > 0 && Size < MaxLoadSize && "broken invariant");
2160b57cec5SDimitry Andric   LoadSequence.push_back({MaxLoadSize, Offset - (MaxLoadSize - Size)});
2170b57cec5SDimitry Andric   NumLoadsNonOneByte = 1;
2180b57cec5SDimitry Andric   return LoadSequence;
2190b57cec5SDimitry Andric }
2200b57cec5SDimitry Andric 
optimiseLoadSequence(LoadEntryVector & LoadSequence,const TargetTransformInfo::MemCmpExpansionOptions & Options,bool IsUsedForZeroCmp)2215f757f3fSDimitry Andric void MemCmpExpansion::optimiseLoadSequence(
2225f757f3fSDimitry Andric     LoadEntryVector &LoadSequence,
2235f757f3fSDimitry Andric     const TargetTransformInfo::MemCmpExpansionOptions &Options,
2245f757f3fSDimitry Andric     bool IsUsedForZeroCmp) {
2255f757f3fSDimitry Andric   // This part of code attempts to optimize the LoadSequence by merging allowed
2265f757f3fSDimitry Andric   // subsequences into single loads of allowed sizes from
2275f757f3fSDimitry Andric   // `MemCmpExpansionOptions::AllowedTailExpansions`. If it is for zero
2285f757f3fSDimitry Andric   // comparison or if no allowed tail expansions are specified, we exit early.
2295f757f3fSDimitry Andric   if (IsUsedForZeroCmp || Options.AllowedTailExpansions.empty())
2305f757f3fSDimitry Andric     return;
2315f757f3fSDimitry Andric 
2325f757f3fSDimitry Andric   while (LoadSequence.size() >= 2) {
2335f757f3fSDimitry Andric     auto Last = LoadSequence[LoadSequence.size() - 1];
2345f757f3fSDimitry Andric     auto PreLast = LoadSequence[LoadSequence.size() - 2];
2355f757f3fSDimitry Andric 
2365f757f3fSDimitry Andric     // Exit the loop if the two sequences are not contiguous
2375f757f3fSDimitry Andric     if (PreLast.Offset + PreLast.LoadSize != Last.Offset)
2385f757f3fSDimitry Andric       break;
2395f757f3fSDimitry Andric 
2405f757f3fSDimitry Andric     auto LoadSize = Last.LoadSize + PreLast.LoadSize;
2415f757f3fSDimitry Andric     if (find(Options.AllowedTailExpansions, LoadSize) ==
2425f757f3fSDimitry Andric         Options.AllowedTailExpansions.end())
2435f757f3fSDimitry Andric       break;
2445f757f3fSDimitry Andric 
2455f757f3fSDimitry Andric     // Remove the last two sequences and replace with the combined sequence
2465f757f3fSDimitry Andric     LoadSequence.pop_back();
2475f757f3fSDimitry Andric     LoadSequence.pop_back();
2485f757f3fSDimitry Andric     LoadSequence.emplace_back(PreLast.Offset, LoadSize);
2495f757f3fSDimitry Andric   }
2505f757f3fSDimitry Andric }
2515f757f3fSDimitry Andric 
2520b57cec5SDimitry Andric // Initialize the basic block structure required for expansion of memcmp call
2530b57cec5SDimitry Andric // with given maximum load size and memcmp size parameter.
2540b57cec5SDimitry Andric // This structure includes:
2550b57cec5SDimitry Andric // 1. A list of load compare blocks - LoadCmpBlocks.
2560b57cec5SDimitry Andric // 2. An EndBlock, split from original instruction point, which is the block to
2570b57cec5SDimitry Andric // return from.
2580b57cec5SDimitry Andric // 3. ResultBlock, block to branch to for early exit when a
2590b57cec5SDimitry Andric // LoadCmpBlock finds a difference.
MemCmpExpansion(CallInst * const CI,uint64_t Size,const TargetTransformInfo::MemCmpExpansionOptions & Options,const bool IsUsedForZeroCmp,const DataLayout & TheDataLayout,DomTreeUpdater * DTU)2600b57cec5SDimitry Andric MemCmpExpansion::MemCmpExpansion(
2610b57cec5SDimitry Andric     CallInst *const CI, uint64_t Size,
2620b57cec5SDimitry Andric     const TargetTransformInfo::MemCmpExpansionOptions &Options,
263fe6060f1SDimitry Andric     const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
264fe6060f1SDimitry Andric     DomTreeUpdater *DTU)
2651fd87a68SDimitry Andric     : CI(CI), Size(Size), NumLoadsPerBlockForZeroCmp(Options.NumLoadsPerBlock),
266fe6060f1SDimitry Andric       IsUsedForZeroCmp(IsUsedForZeroCmp), DL(TheDataLayout), DTU(DTU),
267fe6060f1SDimitry Andric       Builder(CI) {
2680b57cec5SDimitry Andric   assert(Size > 0 && "zero blocks");
2690b57cec5SDimitry Andric   // Scale the max size down if the target can load more bytes than we need.
2700b57cec5SDimitry Andric   llvm::ArrayRef<unsigned> LoadSizes(Options.LoadSizes);
2710b57cec5SDimitry Andric   while (!LoadSizes.empty() && LoadSizes.front() > Size) {
2720b57cec5SDimitry Andric     LoadSizes = LoadSizes.drop_front();
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric   assert(!LoadSizes.empty() && "cannot load Size bytes");
2750b57cec5SDimitry Andric   MaxLoadSize = LoadSizes.front();
2760b57cec5SDimitry Andric   // Compute the decomposition.
2770b57cec5SDimitry Andric   unsigned GreedyNumLoadsNonOneByte = 0;
2780b57cec5SDimitry Andric   LoadSequence = computeGreedyLoadSequence(Size, LoadSizes, Options.MaxNumLoads,
2790b57cec5SDimitry Andric                                            GreedyNumLoadsNonOneByte);
2800b57cec5SDimitry Andric   NumLoadsNonOneByte = GreedyNumLoadsNonOneByte;
2810b57cec5SDimitry Andric   assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
2820b57cec5SDimitry Andric   // If we allow overlapping loads and the load sequence is not already optimal,
2830b57cec5SDimitry Andric   // use overlapping loads.
2840b57cec5SDimitry Andric   if (Options.AllowOverlappingLoads &&
2850b57cec5SDimitry Andric       (LoadSequence.empty() || LoadSequence.size() > 2)) {
2860b57cec5SDimitry Andric     unsigned OverlappingNumLoadsNonOneByte = 0;
2870b57cec5SDimitry Andric     auto OverlappingLoads = computeOverlappingLoadSequence(
2880b57cec5SDimitry Andric         Size, MaxLoadSize, Options.MaxNumLoads, OverlappingNumLoadsNonOneByte);
2890b57cec5SDimitry Andric     if (!OverlappingLoads.empty() &&
2900b57cec5SDimitry Andric         (LoadSequence.empty() ||
2910b57cec5SDimitry Andric          OverlappingLoads.size() < LoadSequence.size())) {
2920b57cec5SDimitry Andric       LoadSequence = OverlappingLoads;
2930b57cec5SDimitry Andric       NumLoadsNonOneByte = OverlappingNumLoadsNonOneByte;
2940b57cec5SDimitry Andric     }
2950b57cec5SDimitry Andric   }
2960b57cec5SDimitry Andric   assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
2975f757f3fSDimitry Andric   optimiseLoadSequence(LoadSequence, Options, IsUsedForZeroCmp);
2980b57cec5SDimitry Andric }
2990b57cec5SDimitry Andric 
getNumBlocks()3000b57cec5SDimitry Andric unsigned MemCmpExpansion::getNumBlocks() {
3010b57cec5SDimitry Andric   if (IsUsedForZeroCmp)
3020b57cec5SDimitry Andric     return getNumLoads() / NumLoadsPerBlockForZeroCmp +
3030b57cec5SDimitry Andric            (getNumLoads() % NumLoadsPerBlockForZeroCmp != 0 ? 1 : 0);
3040b57cec5SDimitry Andric   return getNumLoads();
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric 
createLoadCmpBlocks()3070b57cec5SDimitry Andric void MemCmpExpansion::createLoadCmpBlocks() {
3080b57cec5SDimitry Andric   for (unsigned i = 0; i < getNumBlocks(); i++) {
3090b57cec5SDimitry Andric     BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
3100b57cec5SDimitry Andric                                         EndBlock->getParent(), EndBlock);
3110b57cec5SDimitry Andric     LoadCmpBlocks.push_back(BB);
3120b57cec5SDimitry Andric   }
3130b57cec5SDimitry Andric }
3140b57cec5SDimitry Andric 
createResultBlock()3150b57cec5SDimitry Andric void MemCmpExpansion::createResultBlock() {
3160b57cec5SDimitry Andric   ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
3170b57cec5SDimitry Andric                                    EndBlock->getParent(), EndBlock);
3180b57cec5SDimitry Andric }
3190b57cec5SDimitry Andric 
getLoadPair(Type * LoadSizeType,Type * BSwapSizeType,Type * CmpSizeType,unsigned OffsetBytes)3205ffd83dbSDimitry Andric MemCmpExpansion::LoadPair MemCmpExpansion::getLoadPair(Type *LoadSizeType,
3215f757f3fSDimitry Andric                                                        Type *BSwapSizeType,
3225ffd83dbSDimitry Andric                                                        Type *CmpSizeType,
3235ffd83dbSDimitry Andric                                                        unsigned OffsetBytes) {
3245ffd83dbSDimitry Andric   // Get the memory source at offset `OffsetBytes`.
3255ffd83dbSDimitry Andric   Value *LhsSource = CI->getArgOperand(0);
3265ffd83dbSDimitry Andric   Value *RhsSource = CI->getArgOperand(1);
3275ffd83dbSDimitry Andric   Align LhsAlign = LhsSource->getPointerAlignment(DL);
3285ffd83dbSDimitry Andric   Align RhsAlign = RhsSource->getPointerAlignment(DL);
3290b57cec5SDimitry Andric   if (OffsetBytes > 0) {
3300b57cec5SDimitry Andric     auto *ByteType = Type::getInt8Ty(CI->getContext());
33106c3fb27SDimitry Andric     LhsSource = Builder.CreateConstGEP1_64(ByteType, LhsSource, OffsetBytes);
33206c3fb27SDimitry Andric     RhsSource = Builder.CreateConstGEP1_64(ByteType, RhsSource, OffsetBytes);
3335ffd83dbSDimitry Andric     LhsAlign = commonAlignment(LhsAlign, OffsetBytes);
3345ffd83dbSDimitry Andric     RhsAlign = commonAlignment(RhsAlign, OffsetBytes);
3350b57cec5SDimitry Andric   }
3365ffd83dbSDimitry Andric 
3375ffd83dbSDimitry Andric   // Create a constant or a load from the source.
3385ffd83dbSDimitry Andric   Value *Lhs = nullptr;
3395ffd83dbSDimitry Andric   if (auto *C = dyn_cast<Constant>(LhsSource))
3405ffd83dbSDimitry Andric     Lhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
3415ffd83dbSDimitry Andric   if (!Lhs)
3425ffd83dbSDimitry Andric     Lhs = Builder.CreateAlignedLoad(LoadSizeType, LhsSource, LhsAlign);
3435ffd83dbSDimitry Andric 
3445ffd83dbSDimitry Andric   Value *Rhs = nullptr;
3455ffd83dbSDimitry Andric   if (auto *C = dyn_cast<Constant>(RhsSource))
3465ffd83dbSDimitry Andric     Rhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
3475ffd83dbSDimitry Andric   if (!Rhs)
3485ffd83dbSDimitry Andric     Rhs = Builder.CreateAlignedLoad(LoadSizeType, RhsSource, RhsAlign);
3495ffd83dbSDimitry Andric 
3505f757f3fSDimitry Andric   // Zero extend if Byte Swap intrinsic has different type
3515f757f3fSDimitry Andric   if (BSwapSizeType && LoadSizeType != BSwapSizeType) {
3525f757f3fSDimitry Andric     Lhs = Builder.CreateZExt(Lhs, BSwapSizeType);
3535f757f3fSDimitry Andric     Rhs = Builder.CreateZExt(Rhs, BSwapSizeType);
3545f757f3fSDimitry Andric   }
3555f757f3fSDimitry Andric 
3565ffd83dbSDimitry Andric   // Swap bytes if required.
3575f757f3fSDimitry Andric   if (BSwapSizeType) {
3585f757f3fSDimitry Andric     Function *Bswap = Intrinsic::getDeclaration(
3595f757f3fSDimitry Andric         CI->getModule(), Intrinsic::bswap, BSwapSizeType);
3605ffd83dbSDimitry Andric     Lhs = Builder.CreateCall(Bswap, Lhs);
3615ffd83dbSDimitry Andric     Rhs = Builder.CreateCall(Bswap, Rhs);
3625ffd83dbSDimitry Andric   }
3635ffd83dbSDimitry Andric 
3645ffd83dbSDimitry Andric   // Zero extend if required.
3655f757f3fSDimitry Andric   if (CmpSizeType != nullptr && CmpSizeType != Lhs->getType()) {
3665ffd83dbSDimitry Andric     Lhs = Builder.CreateZExt(Lhs, CmpSizeType);
3675ffd83dbSDimitry Andric     Rhs = Builder.CreateZExt(Rhs, CmpSizeType);
3685ffd83dbSDimitry Andric   }
3695ffd83dbSDimitry Andric   return {Lhs, Rhs};
3700b57cec5SDimitry Andric }
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric // This function creates the IR instructions for loading and comparing 1 byte.
3730b57cec5SDimitry Andric // It loads 1 byte from each source of the memcmp parameters with the given
3740b57cec5SDimitry Andric // GEPIndex. It then subtracts the two loaded values and adds this result to the
3750b57cec5SDimitry Andric // final phi node for selecting the memcmp result.
emitLoadCompareByteBlock(unsigned BlockIndex,unsigned OffsetBytes)3760b57cec5SDimitry Andric void MemCmpExpansion::emitLoadCompareByteBlock(unsigned BlockIndex,
3770b57cec5SDimitry Andric                                                unsigned OffsetBytes) {
378fe6060f1SDimitry Andric   BasicBlock *BB = LoadCmpBlocks[BlockIndex];
379fe6060f1SDimitry Andric   Builder.SetInsertPoint(BB);
3805ffd83dbSDimitry Andric   const LoadPair Loads =
3815f757f3fSDimitry Andric       getLoadPair(Type::getInt8Ty(CI->getContext()), nullptr,
3825ffd83dbSDimitry Andric                   Type::getInt32Ty(CI->getContext()), OffsetBytes);
3835ffd83dbSDimitry Andric   Value *Diff = Builder.CreateSub(Loads.Lhs, Loads.Rhs);
3840b57cec5SDimitry Andric 
385fe6060f1SDimitry Andric   PhiRes->addIncoming(Diff, BB);
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric   if (BlockIndex < (LoadCmpBlocks.size() - 1)) {
3880b57cec5SDimitry Andric     // Early exit branch if difference found to EndBlock. Otherwise, continue to
3890b57cec5SDimitry Andric     // next LoadCmpBlock,
3900b57cec5SDimitry Andric     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
3910b57cec5SDimitry Andric                                     ConstantInt::get(Diff->getType(), 0));
3920b57cec5SDimitry Andric     BranchInst *CmpBr =
3930b57cec5SDimitry Andric         BranchInst::Create(EndBlock, LoadCmpBlocks[BlockIndex + 1], Cmp);
394349cc55cSDimitry Andric     Builder.Insert(CmpBr);
395fe6060f1SDimitry Andric     if (DTU)
396fe6060f1SDimitry Andric       DTU->applyUpdates(
397fe6060f1SDimitry Andric           {{DominatorTree::Insert, BB, EndBlock},
398fe6060f1SDimitry Andric            {DominatorTree::Insert, BB, LoadCmpBlocks[BlockIndex + 1]}});
3990b57cec5SDimitry Andric   } else {
4000b57cec5SDimitry Andric     // The last block has an unconditional branch to EndBlock.
4010b57cec5SDimitry Andric     BranchInst *CmpBr = BranchInst::Create(EndBlock);
402349cc55cSDimitry Andric     Builder.Insert(CmpBr);
403fe6060f1SDimitry Andric     if (DTU)
404fe6060f1SDimitry Andric       DTU->applyUpdates({{DominatorTree::Insert, BB, EndBlock}});
4050b57cec5SDimitry Andric   }
4060b57cec5SDimitry Andric }
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric /// Generate an equality comparison for one or more pairs of loaded values.
4090b57cec5SDimitry Andric /// This is used in the case where the memcmp() call is compared equal or not
4100b57cec5SDimitry Andric /// equal to zero.
getCompareLoadPairs(unsigned BlockIndex,unsigned & LoadIndex)4110b57cec5SDimitry Andric Value *MemCmpExpansion::getCompareLoadPairs(unsigned BlockIndex,
4120b57cec5SDimitry Andric                                             unsigned &LoadIndex) {
4130b57cec5SDimitry Andric   assert(LoadIndex < getNumLoads() &&
4140b57cec5SDimitry Andric          "getCompareLoadPairs() called with no remaining loads");
4150b57cec5SDimitry Andric   std::vector<Value *> XorList, OrList;
4160b57cec5SDimitry Andric   Value *Diff = nullptr;
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   const unsigned NumLoads =
4190b57cec5SDimitry Andric       std::min(getNumLoads() - LoadIndex, NumLoadsPerBlockForZeroCmp);
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   // For a single-block expansion, start inserting before the memcmp call.
4220b57cec5SDimitry Andric   if (LoadCmpBlocks.empty())
4230b57cec5SDimitry Andric     Builder.SetInsertPoint(CI);
4240b57cec5SDimitry Andric   else
4250b57cec5SDimitry Andric     Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric   Value *Cmp = nullptr;
4280b57cec5SDimitry Andric   // If we have multiple loads per block, we need to generate a composite
4290b57cec5SDimitry Andric   // comparison using xor+or. The type for the combinations is the largest load
4300b57cec5SDimitry Andric   // type.
4310b57cec5SDimitry Andric   IntegerType *const MaxLoadType =
4320b57cec5SDimitry Andric       NumLoads == 1 ? nullptr
4330b57cec5SDimitry Andric                     : IntegerType::get(CI->getContext(), MaxLoadSize * 8);
4345f757f3fSDimitry Andric 
4350b57cec5SDimitry Andric   for (unsigned i = 0; i < NumLoads; ++i, ++LoadIndex) {
4360b57cec5SDimitry Andric     const LoadEntry &CurLoadEntry = LoadSequence[LoadIndex];
4375ffd83dbSDimitry Andric     const LoadPair Loads = getLoadPair(
4385f757f3fSDimitry Andric         IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8), nullptr,
4395f757f3fSDimitry Andric         MaxLoadType, CurLoadEntry.Offset);
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric     if (NumLoads != 1) {
4420b57cec5SDimitry Andric       // If we have multiple loads per block, we need to generate a composite
4430b57cec5SDimitry Andric       // comparison using xor+or.
4445ffd83dbSDimitry Andric       Diff = Builder.CreateXor(Loads.Lhs, Loads.Rhs);
4450b57cec5SDimitry Andric       Diff = Builder.CreateZExt(Diff, MaxLoadType);
4460b57cec5SDimitry Andric       XorList.push_back(Diff);
4470b57cec5SDimitry Andric     } else {
4480b57cec5SDimitry Andric       // If there's only one load per block, we just compare the loaded values.
4495ffd83dbSDimitry Andric       Cmp = Builder.CreateICmpNE(Loads.Lhs, Loads.Rhs);
4500b57cec5SDimitry Andric     }
4510b57cec5SDimitry Andric   }
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
4540b57cec5SDimitry Andric     std::vector<Value *> OutList;
4550b57cec5SDimitry Andric     for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
4560b57cec5SDimitry Andric       Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
4570b57cec5SDimitry Andric       OutList.push_back(Or);
4580b57cec5SDimitry Andric     }
4590b57cec5SDimitry Andric     if (InList.size() % 2 != 0)
4600b57cec5SDimitry Andric       OutList.push_back(InList.back());
4610b57cec5SDimitry Andric     return OutList;
4620b57cec5SDimitry Andric   };
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   if (!Cmp) {
4650b57cec5SDimitry Andric     // Pairwise OR the XOR results.
4660b57cec5SDimitry Andric     OrList = pairWiseOr(XorList);
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric     // Pairwise OR the OR results until one result left.
4690b57cec5SDimitry Andric     while (OrList.size() != 1) {
4700b57cec5SDimitry Andric       OrList = pairWiseOr(OrList);
4710b57cec5SDimitry Andric     }
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric     assert(Diff && "Failed to find comparison diff");
4740b57cec5SDimitry Andric     Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
4750b57cec5SDimitry Andric   }
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   return Cmp;
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric 
emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,unsigned & LoadIndex)4800b57cec5SDimitry Andric void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
4810b57cec5SDimitry Andric                                                         unsigned &LoadIndex) {
4820b57cec5SDimitry Andric   Value *Cmp = getCompareLoadPairs(BlockIndex, LoadIndex);
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
4850b57cec5SDimitry Andric                            ? EndBlock
4860b57cec5SDimitry Andric                            : LoadCmpBlocks[BlockIndex + 1];
4870b57cec5SDimitry Andric   // Early exit branch if difference found to ResultBlock. Otherwise,
4880b57cec5SDimitry Andric   // continue to next LoadCmpBlock or EndBlock.
489fe6060f1SDimitry Andric   BasicBlock *BB = Builder.GetInsertBlock();
4900b57cec5SDimitry Andric   BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
4910b57cec5SDimitry Andric   Builder.Insert(CmpBr);
492fe6060f1SDimitry Andric   if (DTU)
493fe6060f1SDimitry Andric     DTU->applyUpdates({{DominatorTree::Insert, BB, ResBlock.BB},
494fe6060f1SDimitry Andric                        {DominatorTree::Insert, BB, NextBB}});
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
4970b57cec5SDimitry Andric   // since early exit to ResultBlock was not taken (no difference was found in
4980b57cec5SDimitry Andric   // any of the bytes).
4990b57cec5SDimitry Andric   if (BlockIndex == LoadCmpBlocks.size() - 1) {
5000b57cec5SDimitry Andric     Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
5010b57cec5SDimitry Andric     PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
5020b57cec5SDimitry Andric   }
5030b57cec5SDimitry Andric }
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric // This function creates the IR intructions for loading and comparing using the
5060b57cec5SDimitry Andric // given LoadSize. It loads the number of bytes specified by LoadSize from each
5070b57cec5SDimitry Andric // source of the memcmp parameters. It then does a subtract to see if there was
5080b57cec5SDimitry Andric // a difference in the loaded values. If a difference is found, it branches
5090b57cec5SDimitry Andric // with an early exit to the ResultBlock for calculating which source was
5100b57cec5SDimitry Andric // larger. Otherwise, it falls through to the either the next LoadCmpBlock or
5110b57cec5SDimitry Andric // the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
5120b57cec5SDimitry Andric // a special case through emitLoadCompareByteBlock. The special handling can
5130b57cec5SDimitry Andric // simply subtract the loaded values and add it to the result phi node.
emitLoadCompareBlock(unsigned BlockIndex)5140b57cec5SDimitry Andric void MemCmpExpansion::emitLoadCompareBlock(unsigned BlockIndex) {
5150b57cec5SDimitry Andric   // There is one load per block in this case, BlockIndex == LoadIndex.
5160b57cec5SDimitry Andric   const LoadEntry &CurLoadEntry = LoadSequence[BlockIndex];
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   if (CurLoadEntry.LoadSize == 1) {
5190b57cec5SDimitry Andric     MemCmpExpansion::emitLoadCompareByteBlock(BlockIndex, CurLoadEntry.Offset);
5200b57cec5SDimitry Andric     return;
5210b57cec5SDimitry Andric   }
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   Type *LoadSizeType =
5240b57cec5SDimitry Andric       IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8);
5255f757f3fSDimitry Andric   Type *BSwapSizeType =
5265f757f3fSDimitry Andric       DL.isLittleEndian()
5275f757f3fSDimitry Andric           ? IntegerType::get(CI->getContext(),
5285f757f3fSDimitry Andric                              PowerOf2Ceil(CurLoadEntry.LoadSize * 8))
5295f757f3fSDimitry Andric           : nullptr;
5305f757f3fSDimitry Andric   Type *MaxLoadType = IntegerType::get(
5315f757f3fSDimitry Andric       CI->getContext(),
5325f757f3fSDimitry Andric       std::max(MaxLoadSize, (unsigned)PowerOf2Ceil(CurLoadEntry.LoadSize)) * 8);
5330b57cec5SDimitry Andric   assert(CurLoadEntry.LoadSize <= MaxLoadSize && "Unexpected load type");
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric   Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
5360b57cec5SDimitry Andric 
5375f757f3fSDimitry Andric   const LoadPair Loads = getLoadPair(LoadSizeType, BSwapSizeType, MaxLoadType,
5380b57cec5SDimitry Andric                                      CurLoadEntry.Offset);
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric   // Add the loaded values to the phi nodes for calculating memcmp result only
5410b57cec5SDimitry Andric   // if result is not used in a zero equality.
5420b57cec5SDimitry Andric   if (!IsUsedForZeroCmp) {
5435ffd83dbSDimitry Andric     ResBlock.PhiSrc1->addIncoming(Loads.Lhs, LoadCmpBlocks[BlockIndex]);
5445ffd83dbSDimitry Andric     ResBlock.PhiSrc2->addIncoming(Loads.Rhs, LoadCmpBlocks[BlockIndex]);
5450b57cec5SDimitry Andric   }
5460b57cec5SDimitry Andric 
5475ffd83dbSDimitry Andric   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Loads.Lhs, Loads.Rhs);
5480b57cec5SDimitry Andric   BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
5490b57cec5SDimitry Andric                            ? EndBlock
5500b57cec5SDimitry Andric                            : LoadCmpBlocks[BlockIndex + 1];
5510b57cec5SDimitry Andric   // Early exit branch if difference found to ResultBlock. Otherwise, continue
5520b57cec5SDimitry Andric   // to next LoadCmpBlock or EndBlock.
553fe6060f1SDimitry Andric   BasicBlock *BB = Builder.GetInsertBlock();
5540b57cec5SDimitry Andric   BranchInst *CmpBr = BranchInst::Create(NextBB, ResBlock.BB, Cmp);
5550b57cec5SDimitry Andric   Builder.Insert(CmpBr);
556fe6060f1SDimitry Andric   if (DTU)
557fe6060f1SDimitry Andric     DTU->applyUpdates({{DominatorTree::Insert, BB, NextBB},
558fe6060f1SDimitry Andric                        {DominatorTree::Insert, BB, ResBlock.BB}});
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric   // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
5610b57cec5SDimitry Andric   // since early exit to ResultBlock was not taken (no difference was found in
5620b57cec5SDimitry Andric   // any of the bytes).
5630b57cec5SDimitry Andric   if (BlockIndex == LoadCmpBlocks.size() - 1) {
5640b57cec5SDimitry Andric     Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
5650b57cec5SDimitry Andric     PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
5660b57cec5SDimitry Andric   }
5670b57cec5SDimitry Andric }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric // This function populates the ResultBlock with a sequence to calculate the
5700b57cec5SDimitry Andric // memcmp result. It compares the two loaded source values and returns -1 if
5710b57cec5SDimitry Andric // src1 < src2 and 1 if src1 > src2.
emitMemCmpResultBlock()5720b57cec5SDimitry Andric void MemCmpExpansion::emitMemCmpResultBlock() {
5730b57cec5SDimitry Andric   // Special case: if memcmp result is used in a zero equality, result does not
5740b57cec5SDimitry Andric   // need to be calculated and can simply return 1.
5750b57cec5SDimitry Andric   if (IsUsedForZeroCmp) {
5760b57cec5SDimitry Andric     BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
5770b57cec5SDimitry Andric     Builder.SetInsertPoint(ResBlock.BB, InsertPt);
5780b57cec5SDimitry Andric     Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
5790b57cec5SDimitry Andric     PhiRes->addIncoming(Res, ResBlock.BB);
5800b57cec5SDimitry Andric     BranchInst *NewBr = BranchInst::Create(EndBlock);
5810b57cec5SDimitry Andric     Builder.Insert(NewBr);
582fe6060f1SDimitry Andric     if (DTU)
583fe6060f1SDimitry Andric       DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
5840b57cec5SDimitry Andric     return;
5850b57cec5SDimitry Andric   }
5860b57cec5SDimitry Andric   BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
5870b57cec5SDimitry Andric   Builder.SetInsertPoint(ResBlock.BB, InsertPt);
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
5900b57cec5SDimitry Andric                                   ResBlock.PhiSrc2);
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric   Value *Res =
5930b57cec5SDimitry Andric       Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1),
5940b57cec5SDimitry Andric                            ConstantInt::get(Builder.getInt32Ty(), 1));
5950b57cec5SDimitry Andric 
596fe6060f1SDimitry Andric   PhiRes->addIncoming(Res, ResBlock.BB);
5970b57cec5SDimitry Andric   BranchInst *NewBr = BranchInst::Create(EndBlock);
5980b57cec5SDimitry Andric   Builder.Insert(NewBr);
599fe6060f1SDimitry Andric   if (DTU)
600fe6060f1SDimitry Andric     DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
6010b57cec5SDimitry Andric }
6020b57cec5SDimitry Andric 
setupResultBlockPHINodes()6030b57cec5SDimitry Andric void MemCmpExpansion::setupResultBlockPHINodes() {
6040b57cec5SDimitry Andric   Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
6050b57cec5SDimitry Andric   Builder.SetInsertPoint(ResBlock.BB);
6060b57cec5SDimitry Andric   // Note: this assumes one load per block.
6070b57cec5SDimitry Andric   ResBlock.PhiSrc1 =
6080b57cec5SDimitry Andric       Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src1");
6090b57cec5SDimitry Andric   ResBlock.PhiSrc2 =
6100b57cec5SDimitry Andric       Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src2");
6110b57cec5SDimitry Andric }
6120b57cec5SDimitry Andric 
setupEndBlockPHINodes()6130b57cec5SDimitry Andric void MemCmpExpansion::setupEndBlockPHINodes() {
6145f757f3fSDimitry Andric   Builder.SetInsertPoint(EndBlock, EndBlock->begin());
6150b57cec5SDimitry Andric   PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
6160b57cec5SDimitry Andric }
6170b57cec5SDimitry Andric 
getMemCmpExpansionZeroCase()6180b57cec5SDimitry Andric Value *MemCmpExpansion::getMemCmpExpansionZeroCase() {
6190b57cec5SDimitry Andric   unsigned LoadIndex = 0;
6200b57cec5SDimitry Andric   // This loop populates each of the LoadCmpBlocks with the IR sequence to
6210b57cec5SDimitry Andric   // handle multiple loads per block.
6220b57cec5SDimitry Andric   for (unsigned I = 0; I < getNumBlocks(); ++I) {
6230b57cec5SDimitry Andric     emitLoadCompareBlockMultipleLoads(I, LoadIndex);
6240b57cec5SDimitry Andric   }
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   emitMemCmpResultBlock();
6270b57cec5SDimitry Andric   return PhiRes;
6280b57cec5SDimitry Andric }
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric /// A memcmp expansion that compares equality with 0 and only has one block of
6310b57cec5SDimitry Andric /// load and compare can bypass the compare, branch, and phi IR that is required
6320b57cec5SDimitry Andric /// in the general case.
getMemCmpEqZeroOneBlock()6330b57cec5SDimitry Andric Value *MemCmpExpansion::getMemCmpEqZeroOneBlock() {
6340b57cec5SDimitry Andric   unsigned LoadIndex = 0;
6350b57cec5SDimitry Andric   Value *Cmp = getCompareLoadPairs(0, LoadIndex);
6360b57cec5SDimitry Andric   assert(LoadIndex == getNumLoads() && "some entries were not consumed");
6370b57cec5SDimitry Andric   return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext()));
6380b57cec5SDimitry Andric }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric /// A memcmp expansion that only has one block of load and compare can bypass
6410b57cec5SDimitry Andric /// the compare, branch, and phi IR that is required in the general case.
6425f757f3fSDimitry Andric /// This function also analyses users of memcmp, and if there is only one user
6435f757f3fSDimitry Andric /// from which we can conclude that only 2 out of 3 memcmp outcomes really
6445f757f3fSDimitry Andric /// matter, then it generates more efficient code with only one comparison.
getMemCmpOneBlock()6450b57cec5SDimitry Andric Value *MemCmpExpansion::getMemCmpOneBlock() {
6465ffd83dbSDimitry Andric   bool NeedsBSwap = DL.isLittleEndian() && Size != 1;
6475f757f3fSDimitry Andric   Type *LoadSizeType = IntegerType::get(CI->getContext(), Size * 8);
6485f757f3fSDimitry Andric   Type *BSwapSizeType =
6495f757f3fSDimitry Andric       NeedsBSwap ? IntegerType::get(CI->getContext(), PowerOf2Ceil(Size * 8))
6505f757f3fSDimitry Andric                  : nullptr;
6515f757f3fSDimitry Andric   Type *MaxLoadType =
6525f757f3fSDimitry Andric       IntegerType::get(CI->getContext(),
6535f757f3fSDimitry Andric                        std::max(MaxLoadSize, (unsigned)PowerOf2Ceil(Size)) * 8);
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric   // The i8 and i16 cases don't need compares. We zext the loaded values and
6560b57cec5SDimitry Andric   // subtract them to get the suitable negative, zero, or positive i32 result.
6575f757f3fSDimitry Andric   if (Size == 1 || Size == 2) {
6585f757f3fSDimitry Andric     const LoadPair Loads = getLoadPair(LoadSizeType, BSwapSizeType,
6595f757f3fSDimitry Andric                                        Builder.getInt32Ty(), /*Offset*/ 0);
6605ffd83dbSDimitry Andric     return Builder.CreateSub(Loads.Lhs, Loads.Rhs);
6610b57cec5SDimitry Andric   }
6620b57cec5SDimitry Andric 
6635f757f3fSDimitry Andric   const LoadPair Loads = getLoadPair(LoadSizeType, BSwapSizeType, MaxLoadType,
6645ffd83dbSDimitry Andric                                      /*Offset*/ 0);
6655f757f3fSDimitry Andric 
6665f757f3fSDimitry Andric   // If a user of memcmp cares only about two outcomes, for example:
6675f757f3fSDimitry Andric   //    bool result = memcmp(a, b, NBYTES) > 0;
6685f757f3fSDimitry Andric   // We can generate more optimal code with a smaller number of operations
6695f757f3fSDimitry Andric   if (CI->hasOneUser()) {
6705f757f3fSDimitry Andric     auto *UI = cast<Instruction>(*CI->user_begin());
6715f757f3fSDimitry Andric     ICmpInst::Predicate Pred = ICmpInst::Predicate::BAD_ICMP_PREDICATE;
6725f757f3fSDimitry Andric     uint64_t Shift;
6735f757f3fSDimitry Andric     bool NeedsZExt = false;
6745f757f3fSDimitry Andric     // This is a special case because instead of checking if the result is less
6755f757f3fSDimitry Andric     // than zero:
6765f757f3fSDimitry Andric     //    bool result = memcmp(a, b, NBYTES) < 0;
6775f757f3fSDimitry Andric     // Compiler is clever enough to generate the following code:
6785f757f3fSDimitry Andric     //    bool result = memcmp(a, b, NBYTES) >> 31;
6795f757f3fSDimitry Andric     if (match(UI, m_LShr(m_Value(), m_ConstantInt(Shift))) &&
6805f757f3fSDimitry Andric         Shift == (CI->getType()->getIntegerBitWidth() - 1)) {
6815f757f3fSDimitry Andric       Pred = ICmpInst::ICMP_SLT;
6825f757f3fSDimitry Andric       NeedsZExt = true;
6835f757f3fSDimitry Andric     } else {
6845f757f3fSDimitry Andric       // In case of a successful match this call will set `Pred` variable
6855f757f3fSDimitry Andric       match(UI, m_ICmp(Pred, m_Specific(CI), m_Zero()));
6865f757f3fSDimitry Andric     }
6875f757f3fSDimitry Andric     // Generate new code and remove the original memcmp call and the user
6885f757f3fSDimitry Andric     if (ICmpInst::isSigned(Pred)) {
6895f757f3fSDimitry Andric       Value *Cmp = Builder.CreateICmp(CmpInst::getUnsignedPredicate(Pred),
6905f757f3fSDimitry Andric                                       Loads.Lhs, Loads.Rhs);
6915f757f3fSDimitry Andric       auto *Result = NeedsZExt ? Builder.CreateZExt(Cmp, UI->getType()) : Cmp;
6925f757f3fSDimitry Andric       UI->replaceAllUsesWith(Result);
6935f757f3fSDimitry Andric       UI->eraseFromParent();
6945f757f3fSDimitry Andric       CI->eraseFromParent();
6955f757f3fSDimitry Andric       return nullptr;
6965f757f3fSDimitry Andric     }
6975f757f3fSDimitry Andric   }
6985f757f3fSDimitry Andric 
6990b57cec5SDimitry Andric   // The result of memcmp is negative, zero, or positive, so produce that by
7000b57cec5SDimitry Andric   // subtracting 2 extended compare bits: sub (ugt, ult).
7010b57cec5SDimitry Andric   // If a target prefers to use selects to get -1/0/1, they should be able
7020b57cec5SDimitry Andric   // to transform this later. The inverse transform (going from selects to math)
7030b57cec5SDimitry Andric   // may not be possible in the DAG because the selects got converted into
7040b57cec5SDimitry Andric   // branches before we got there.
7055ffd83dbSDimitry Andric   Value *CmpUGT = Builder.CreateICmpUGT(Loads.Lhs, Loads.Rhs);
7065ffd83dbSDimitry Andric   Value *CmpULT = Builder.CreateICmpULT(Loads.Lhs, Loads.Rhs);
7070b57cec5SDimitry Andric   Value *ZextUGT = Builder.CreateZExt(CmpUGT, Builder.getInt32Ty());
7080b57cec5SDimitry Andric   Value *ZextULT = Builder.CreateZExt(CmpULT, Builder.getInt32Ty());
7090b57cec5SDimitry Andric   return Builder.CreateSub(ZextUGT, ZextULT);
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric // This function expands the memcmp call into an inline expansion and returns
7135f757f3fSDimitry Andric // the memcmp result. Returns nullptr if the memcmp is already replaced.
getMemCmpExpansion()7140b57cec5SDimitry Andric Value *MemCmpExpansion::getMemCmpExpansion() {
7150b57cec5SDimitry Andric   // Create the basic block framework for a multi-block expansion.
7160b57cec5SDimitry Andric   if (getNumBlocks() != 1) {
7170b57cec5SDimitry Andric     BasicBlock *StartBlock = CI->getParent();
718fe6060f1SDimitry Andric     EndBlock = SplitBlock(StartBlock, CI, DTU, /*LI=*/nullptr,
719fe6060f1SDimitry Andric                           /*MSSAU=*/nullptr, "endblock");
7200b57cec5SDimitry Andric     setupEndBlockPHINodes();
7210b57cec5SDimitry Andric     createResultBlock();
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric     // If return value of memcmp is not used in a zero equality, we need to
7240b57cec5SDimitry Andric     // calculate which source was larger. The calculation requires the
7250b57cec5SDimitry Andric     // two loaded source values of each load compare block.
7260b57cec5SDimitry Andric     // These will be saved in the phi nodes created by setupResultBlockPHINodes.
7270b57cec5SDimitry Andric     if (!IsUsedForZeroCmp) setupResultBlockPHINodes();
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric     // Create the number of required load compare basic blocks.
7300b57cec5SDimitry Andric     createLoadCmpBlocks();
7310b57cec5SDimitry Andric 
732fe6060f1SDimitry Andric     // Update the terminator added by SplitBlock to branch to the first
7330b57cec5SDimitry Andric     // LoadCmpBlock.
7340b57cec5SDimitry Andric     StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]);
735fe6060f1SDimitry Andric     if (DTU)
736fe6060f1SDimitry Andric       DTU->applyUpdates({{DominatorTree::Insert, StartBlock, LoadCmpBlocks[0]},
737fe6060f1SDimitry Andric                          {DominatorTree::Delete, StartBlock, EndBlock}});
7380b57cec5SDimitry Andric   }
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   if (IsUsedForZeroCmp)
7430b57cec5SDimitry Andric     return getNumBlocks() == 1 ? getMemCmpEqZeroOneBlock()
7440b57cec5SDimitry Andric                                : getMemCmpExpansionZeroCase();
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric   if (getNumBlocks() == 1)
7470b57cec5SDimitry Andric     return getMemCmpOneBlock();
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric   for (unsigned I = 0; I < getNumBlocks(); ++I) {
7500b57cec5SDimitry Andric     emitLoadCompareBlock(I);
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   emitMemCmpResultBlock();
7540b57cec5SDimitry Andric   return PhiRes;
7550b57cec5SDimitry Andric }
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric // This function checks to see if an expansion of memcmp can be generated.
7580b57cec5SDimitry Andric // It checks for constant compare size that is less than the max inline size.
7590b57cec5SDimitry Andric // If an expansion cannot occur, returns false to leave as a library call.
7600b57cec5SDimitry Andric // Otherwise, the library call is replaced with a new IR instruction sequence.
7610b57cec5SDimitry Andric /// We want to transform:
7620b57cec5SDimitry Andric /// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
7630b57cec5SDimitry Andric /// To:
7640b57cec5SDimitry Andric /// loadbb:
7650b57cec5SDimitry Andric ///  %0 = bitcast i32* %buffer2 to i8*
7660b57cec5SDimitry Andric ///  %1 = bitcast i32* %buffer1 to i8*
7670b57cec5SDimitry Andric ///  %2 = bitcast i8* %1 to i64*
7680b57cec5SDimitry Andric ///  %3 = bitcast i8* %0 to i64*
7690b57cec5SDimitry Andric ///  %4 = load i64, i64* %2
7700b57cec5SDimitry Andric ///  %5 = load i64, i64* %3
7710b57cec5SDimitry Andric ///  %6 = call i64 @llvm.bswap.i64(i64 %4)
7720b57cec5SDimitry Andric ///  %7 = call i64 @llvm.bswap.i64(i64 %5)
7730b57cec5SDimitry Andric ///  %8 = sub i64 %6, %7
7740b57cec5SDimitry Andric ///  %9 = icmp ne i64 %8, 0
7750b57cec5SDimitry Andric ///  br i1 %9, label %res_block, label %loadbb1
7760b57cec5SDimitry Andric /// res_block:                                        ; preds = %loadbb2,
7770b57cec5SDimitry Andric /// %loadbb1, %loadbb
7780b57cec5SDimitry Andric ///  %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
7790b57cec5SDimitry Andric ///  %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
7800b57cec5SDimitry Andric ///  %10 = icmp ult i64 %phi.src1, %phi.src2
7810b57cec5SDimitry Andric ///  %11 = select i1 %10, i32 -1, i32 1
7820b57cec5SDimitry Andric ///  br label %endblock
7830b57cec5SDimitry Andric /// loadbb1:                                          ; preds = %loadbb
7840b57cec5SDimitry Andric ///  %12 = bitcast i32* %buffer2 to i8*
7850b57cec5SDimitry Andric ///  %13 = bitcast i32* %buffer1 to i8*
7860b57cec5SDimitry Andric ///  %14 = bitcast i8* %13 to i32*
7870b57cec5SDimitry Andric ///  %15 = bitcast i8* %12 to i32*
7880b57cec5SDimitry Andric ///  %16 = getelementptr i32, i32* %14, i32 2
7890b57cec5SDimitry Andric ///  %17 = getelementptr i32, i32* %15, i32 2
7900b57cec5SDimitry Andric ///  %18 = load i32, i32* %16
7910b57cec5SDimitry Andric ///  %19 = load i32, i32* %17
7920b57cec5SDimitry Andric ///  %20 = call i32 @llvm.bswap.i32(i32 %18)
7930b57cec5SDimitry Andric ///  %21 = call i32 @llvm.bswap.i32(i32 %19)
7940b57cec5SDimitry Andric ///  %22 = zext i32 %20 to i64
7950b57cec5SDimitry Andric ///  %23 = zext i32 %21 to i64
7960b57cec5SDimitry Andric ///  %24 = sub i64 %22, %23
7970b57cec5SDimitry Andric ///  %25 = icmp ne i64 %24, 0
7980b57cec5SDimitry Andric ///  br i1 %25, label %res_block, label %loadbb2
7990b57cec5SDimitry Andric /// loadbb2:                                          ; preds = %loadbb1
8000b57cec5SDimitry Andric ///  %26 = bitcast i32* %buffer2 to i8*
8010b57cec5SDimitry Andric ///  %27 = bitcast i32* %buffer1 to i8*
8020b57cec5SDimitry Andric ///  %28 = bitcast i8* %27 to i16*
8030b57cec5SDimitry Andric ///  %29 = bitcast i8* %26 to i16*
8040b57cec5SDimitry Andric ///  %30 = getelementptr i16, i16* %28, i16 6
8050b57cec5SDimitry Andric ///  %31 = getelementptr i16, i16* %29, i16 6
8060b57cec5SDimitry Andric ///  %32 = load i16, i16* %30
8070b57cec5SDimitry Andric ///  %33 = load i16, i16* %31
8080b57cec5SDimitry Andric ///  %34 = call i16 @llvm.bswap.i16(i16 %32)
8090b57cec5SDimitry Andric ///  %35 = call i16 @llvm.bswap.i16(i16 %33)
8100b57cec5SDimitry Andric ///  %36 = zext i16 %34 to i64
8110b57cec5SDimitry Andric ///  %37 = zext i16 %35 to i64
8120b57cec5SDimitry Andric ///  %38 = sub i64 %36, %37
8130b57cec5SDimitry Andric ///  %39 = icmp ne i64 %38, 0
8140b57cec5SDimitry Andric ///  br i1 %39, label %res_block, label %loadbb3
8150b57cec5SDimitry Andric /// loadbb3:                                          ; preds = %loadbb2
8160b57cec5SDimitry Andric ///  %40 = bitcast i32* %buffer2 to i8*
8170b57cec5SDimitry Andric ///  %41 = bitcast i32* %buffer1 to i8*
8180b57cec5SDimitry Andric ///  %42 = getelementptr i8, i8* %41, i8 14
8190b57cec5SDimitry Andric ///  %43 = getelementptr i8, i8* %40, i8 14
8200b57cec5SDimitry Andric ///  %44 = load i8, i8* %42
8210b57cec5SDimitry Andric ///  %45 = load i8, i8* %43
8220b57cec5SDimitry Andric ///  %46 = zext i8 %44 to i32
8230b57cec5SDimitry Andric ///  %47 = zext i8 %45 to i32
8240b57cec5SDimitry Andric ///  %48 = sub i32 %46, %47
8250b57cec5SDimitry Andric ///  br label %endblock
8260b57cec5SDimitry Andric /// endblock:                                         ; preds = %res_block,
8270b57cec5SDimitry Andric /// %loadbb3
8280b57cec5SDimitry Andric ///  %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
8290b57cec5SDimitry Andric ///  ret i32 %phi.res
expandMemCmp(CallInst * CI,const TargetTransformInfo * TTI,const TargetLowering * TLI,const DataLayout * DL,ProfileSummaryInfo * PSI,BlockFrequencyInfo * BFI,DomTreeUpdater * DTU,const bool IsBCmp)8300b57cec5SDimitry Andric static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
831480093f4SDimitry Andric                          const TargetLowering *TLI, const DataLayout *DL,
832fe6060f1SDimitry Andric                          ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
83381ad6265SDimitry Andric                          DomTreeUpdater *DTU, const bool IsBCmp) {
8340b57cec5SDimitry Andric   NumMemCmpCalls++;
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   // Early exit from expansion if -Oz.
8370b57cec5SDimitry Andric   if (CI->getFunction()->hasMinSize())
8380b57cec5SDimitry Andric     return false;
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   // Early exit from expansion if size is not a constant.
8410b57cec5SDimitry Andric   ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
8420b57cec5SDimitry Andric   if (!SizeCast) {
8430b57cec5SDimitry Andric     NumMemCmpNotConstant++;
8440b57cec5SDimitry Andric     return false;
8450b57cec5SDimitry Andric   }
8460b57cec5SDimitry Andric   const uint64_t SizeVal = SizeCast->getZExtValue();
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   if (SizeVal == 0) {
8490b57cec5SDimitry Andric     return false;
8500b57cec5SDimitry Andric   }
8510b57cec5SDimitry Andric   // TTI call to check if target would like to expand memcmp. Also, get the
8520b57cec5SDimitry Andric   // available load sizes.
85381ad6265SDimitry Andric   const bool IsUsedForZeroCmp =
85481ad6265SDimitry Andric       IsBCmp || isOnlyUsedInZeroEqualityComparison(CI);
855480093f4SDimitry Andric   bool OptForSize = CI->getFunction()->hasOptSize() ||
856480093f4SDimitry Andric                     llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
857480093f4SDimitry Andric   auto Options = TTI->enableMemCmpExpansion(OptForSize,
8580b57cec5SDimitry Andric                                             IsUsedForZeroCmp);
8590b57cec5SDimitry Andric   if (!Options) return false;
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   if (MemCmpEqZeroNumLoadsPerBlock.getNumOccurrences())
8620b57cec5SDimitry Andric     Options.NumLoadsPerBlock = MemCmpEqZeroNumLoadsPerBlock;
8630b57cec5SDimitry Andric 
864480093f4SDimitry Andric   if (OptForSize &&
8650b57cec5SDimitry Andric       MaxLoadsPerMemcmpOptSize.getNumOccurrences())
8660b57cec5SDimitry Andric     Options.MaxNumLoads = MaxLoadsPerMemcmpOptSize;
8670b57cec5SDimitry Andric 
868480093f4SDimitry Andric   if (!OptForSize && MaxLoadsPerMemcmp.getNumOccurrences())
8690b57cec5SDimitry Andric     Options.MaxNumLoads = MaxLoadsPerMemcmp;
8700b57cec5SDimitry Andric 
871fe6060f1SDimitry Andric   MemCmpExpansion Expansion(CI, SizeVal, Options, IsUsedForZeroCmp, *DL, DTU);
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric   // Don't expand if this will require more loads than desired by the target.
8740b57cec5SDimitry Andric   if (Expansion.getNumLoads() == 0) {
8750b57cec5SDimitry Andric     NumMemCmpGreaterThanMax++;
8760b57cec5SDimitry Andric     return false;
8770b57cec5SDimitry Andric   }
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric   NumMemCmpInlined++;
8800b57cec5SDimitry Andric 
8815f757f3fSDimitry Andric   if (Value *Res = Expansion.getMemCmpExpansion()) {
8820b57cec5SDimitry Andric     // Replace call with result of expansion and erase call.
8830b57cec5SDimitry Andric     CI->replaceAllUsesWith(Res);
8840b57cec5SDimitry Andric     CI->eraseFromParent();
8855f757f3fSDimitry Andric   }
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric   return true;
8880b57cec5SDimitry Andric }
8890b57cec5SDimitry Andric 
8905f757f3fSDimitry Andric // Returns true if a change was made.
8915f757f3fSDimitry Andric static bool runOnBlock(BasicBlock &BB, const TargetLibraryInfo *TLI,
8925f757f3fSDimitry Andric                        const TargetTransformInfo *TTI, const TargetLowering *TL,
8935f757f3fSDimitry Andric                        const DataLayout &DL, ProfileSummaryInfo *PSI,
8945f757f3fSDimitry Andric                        BlockFrequencyInfo *BFI, DomTreeUpdater *DTU);
8955f757f3fSDimitry Andric 
8965f757f3fSDimitry Andric static PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
8975f757f3fSDimitry Andric                                  const TargetTransformInfo *TTI,
8985f757f3fSDimitry Andric                                  const TargetLowering *TL,
8995f757f3fSDimitry Andric                                  ProfileSummaryInfo *PSI,
9005f757f3fSDimitry Andric                                  BlockFrequencyInfo *BFI, DominatorTree *DT);
9015f757f3fSDimitry Andric 
9025f757f3fSDimitry Andric class ExpandMemCmpLegacyPass : public FunctionPass {
9030b57cec5SDimitry Andric public:
9040b57cec5SDimitry Andric   static char ID;
9050b57cec5SDimitry Andric 
ExpandMemCmpLegacyPass()9065f757f3fSDimitry Andric   ExpandMemCmpLegacyPass() : FunctionPass(ID) {
9075f757f3fSDimitry Andric     initializeExpandMemCmpLegacyPassPass(*PassRegistry::getPassRegistry());
9080b57cec5SDimitry Andric   }
9090b57cec5SDimitry Andric 
runOnFunction(Function & F)9100b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
9110b57cec5SDimitry Andric     if (skipFunction(F)) return false;
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric     auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
9140b57cec5SDimitry Andric     if (!TPC) {
9150b57cec5SDimitry Andric       return false;
9160b57cec5SDimitry Andric     }
9170b57cec5SDimitry Andric     const TargetLowering* TL =
9180b57cec5SDimitry Andric         TPC->getTM<TargetMachine>().getSubtargetImpl(F)->getTargetLowering();
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric     const TargetLibraryInfo *TLI =
9218bcb0991SDimitry Andric         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
9220b57cec5SDimitry Andric     const TargetTransformInfo *TTI =
9230b57cec5SDimitry Andric         &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
924480093f4SDimitry Andric     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
925480093f4SDimitry Andric     auto *BFI = (PSI && PSI->hasProfileSummary()) ?
926480093f4SDimitry Andric            &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
927480093f4SDimitry Andric            nullptr;
928fe6060f1SDimitry Andric     DominatorTree *DT = nullptr;
929fe6060f1SDimitry Andric     if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
930fe6060f1SDimitry Andric       DT = &DTWP->getDomTree();
931fe6060f1SDimitry Andric     auto PA = runImpl(F, TLI, TTI, TL, PSI, BFI, DT);
9320b57cec5SDimitry Andric     return !PA.areAllPreserved();
9330b57cec5SDimitry Andric   }
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric private:
getAnalysisUsage(AnalysisUsage & AU) const9360b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
9370b57cec5SDimitry Andric     AU.addRequired<TargetLibraryInfoWrapperPass>();
9380b57cec5SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
939480093f4SDimitry Andric     AU.addRequired<ProfileSummaryInfoWrapperPass>();
940fe6060f1SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
941480093f4SDimitry Andric     LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
9420b57cec5SDimitry Andric     FunctionPass::getAnalysisUsage(AU);
9430b57cec5SDimitry Andric   }
9445f757f3fSDimitry Andric };
9450b57cec5SDimitry Andric 
runOnBlock(BasicBlock & BB,const TargetLibraryInfo * TLI,const TargetTransformInfo * TTI,const TargetLowering * TL,const DataLayout & DL,ProfileSummaryInfo * PSI,BlockFrequencyInfo * BFI,DomTreeUpdater * DTU)9460b57cec5SDimitry Andric bool runOnBlock(BasicBlock &BB, const TargetLibraryInfo *TLI,
9470b57cec5SDimitry Andric                 const TargetTransformInfo *TTI, const TargetLowering *TL,
948480093f4SDimitry Andric                 const DataLayout &DL, ProfileSummaryInfo *PSI,
9495f757f3fSDimitry Andric                 BlockFrequencyInfo *BFI, DomTreeUpdater *DTU) {
9500b57cec5SDimitry Andric   for (Instruction &I : BB) {
9510b57cec5SDimitry Andric     CallInst *CI = dyn_cast<CallInst>(&I);
9520b57cec5SDimitry Andric     if (!CI) {
9530b57cec5SDimitry Andric       continue;
9540b57cec5SDimitry Andric     }
9550b57cec5SDimitry Andric     LibFunc Func;
9565ffd83dbSDimitry Andric     if (TLI->getLibFunc(*CI, Func) &&
9570b57cec5SDimitry Andric         (Func == LibFunc_memcmp || Func == LibFunc_bcmp) &&
95881ad6265SDimitry Andric         expandMemCmp(CI, TTI, TL, &DL, PSI, BFI, DTU, Func == LibFunc_bcmp)) {
9590b57cec5SDimitry Andric       return true;
9600b57cec5SDimitry Andric     }
9610b57cec5SDimitry Andric   }
9620b57cec5SDimitry Andric   return false;
9630b57cec5SDimitry Andric }
9640b57cec5SDimitry Andric 
runImpl(Function & F,const TargetLibraryInfo * TLI,const TargetTransformInfo * TTI,const TargetLowering * TL,ProfileSummaryInfo * PSI,BlockFrequencyInfo * BFI,DominatorTree * DT)9655f757f3fSDimitry Andric PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
966fe6060f1SDimitry Andric                           const TargetTransformInfo *TTI,
967480093f4SDimitry Andric                           const TargetLowering *TL, ProfileSummaryInfo *PSI,
968fe6060f1SDimitry Andric                           BlockFrequencyInfo *BFI, DominatorTree *DT) {
969bdd1243dSDimitry Andric   std::optional<DomTreeUpdater> DTU;
970fe6060f1SDimitry Andric   if (DT)
971fe6060f1SDimitry Andric     DTU.emplace(DT, DomTreeUpdater::UpdateStrategy::Lazy);
972fe6060f1SDimitry Andric 
973*0fca6ea1SDimitry Andric   const DataLayout& DL = F.getDataLayout();
9740b57cec5SDimitry Andric   bool MadeChanges = false;
9750b57cec5SDimitry Andric   for (auto BBIt = F.begin(); BBIt != F.end();) {
976bdd1243dSDimitry Andric     if (runOnBlock(*BBIt, TLI, TTI, TL, DL, PSI, BFI, DTU ? &*DTU : nullptr)) {
9770b57cec5SDimitry Andric       MadeChanges = true;
9780b57cec5SDimitry Andric       // If changes were made, restart the function from the beginning, since
9790b57cec5SDimitry Andric       // the structure of the function was changed.
9800b57cec5SDimitry Andric       BBIt = F.begin();
9810b57cec5SDimitry Andric     } else {
9820b57cec5SDimitry Andric       ++BBIt;
9830b57cec5SDimitry Andric     }
9840b57cec5SDimitry Andric   }
9855ffd83dbSDimitry Andric   if (MadeChanges)
9865ffd83dbSDimitry Andric     for (BasicBlock &BB : F)
9875ffd83dbSDimitry Andric       SimplifyInstructionsInBlock(&BB);
988fe6060f1SDimitry Andric   if (!MadeChanges)
989fe6060f1SDimitry Andric     return PreservedAnalyses::all();
990fe6060f1SDimitry Andric   PreservedAnalyses PA;
991fe6060f1SDimitry Andric   PA.preserve<DominatorTreeAnalysis>();
992fe6060f1SDimitry Andric   return PA;
9930b57cec5SDimitry Andric }
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric } // namespace
9960b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)9975f757f3fSDimitry Andric PreservedAnalyses ExpandMemCmpPass::run(Function &F,
9985f757f3fSDimitry Andric                                         FunctionAnalysisManager &FAM) {
9995f757f3fSDimitry Andric   const auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
10005f757f3fSDimitry Andric   const auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
10015f757f3fSDimitry Andric   const auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
10025f757f3fSDimitry Andric   auto *PSI = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F)
10035f757f3fSDimitry Andric                   .getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10045f757f3fSDimitry Andric   BlockFrequencyInfo *BFI = (PSI && PSI->hasProfileSummary())
10055f757f3fSDimitry Andric                                 ? &FAM.getResult<BlockFrequencyAnalysis>(F)
10065f757f3fSDimitry Andric                                 : nullptr;
10075f757f3fSDimitry Andric   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
10085f757f3fSDimitry Andric 
10095f757f3fSDimitry Andric   return runImpl(F, &TLI, &TTI, TL, PSI, BFI, DT);
10105f757f3fSDimitry Andric }
10115f757f3fSDimitry Andric 
10125f757f3fSDimitry Andric char ExpandMemCmpLegacyPass::ID = 0;
10135f757f3fSDimitry Andric INITIALIZE_PASS_BEGIN(ExpandMemCmpLegacyPass, DEBUG_TYPE,
10140b57cec5SDimitry Andric                       "Expand memcmp() to load/stores", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)10150b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10160b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1017480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
1018480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1019fe6060f1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10205f757f3fSDimitry Andric INITIALIZE_PASS_END(ExpandMemCmpLegacyPass, DEBUG_TYPE,
10210b57cec5SDimitry Andric                     "Expand memcmp() to load/stores", false, false)
10220b57cec5SDimitry Andric 
10235f757f3fSDimitry Andric FunctionPass *llvm::createExpandMemCmpLegacyPass() {
10245f757f3fSDimitry Andric   return new ExpandMemCmpLegacyPass();
10250b57cec5SDimitry Andric }
1026