1//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
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 munges the code in the input function to better prepare it for
10// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/CodeGenPrepare.h"
16#include "CodeGenOptions.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/PointerIntPair.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Analysis/BlockFrequencyInfo.h"
27#include "llvm/Analysis/BranchProbabilityInfo.h"
28#include "llvm/Analysis/DomTreeUpdater.h"
29#include "llvm/Analysis/FloatingPointPredicateUtils.h"
30#include "llvm/Analysis/InstructionSimplify.h"
31#include "llvm/Analysis/LoopInfo.h"
32#include "llvm/Analysis/ProfileSummaryInfo.h"
33#include "llvm/Analysis/ScalarEvolutionExpressions.h"
34#include "llvm/Analysis/TargetLibraryInfo.h"
35#include "llvm/Analysis/TargetTransformInfo.h"
36#include "llvm/Analysis/ValueTracking.h"
37#include "llvm/Analysis/VectorUtils.h"
38#include "llvm/CodeGen/Analysis.h"
39#include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
40#include "llvm/CodeGen/ISDOpcodes.h"
41#include "llvm/CodeGen/SelectionDAGNodes.h"
42#include "llvm/CodeGen/TargetLowering.h"
43#include "llvm/CodeGen/TargetPassConfig.h"
44#include "llvm/CodeGen/TargetSubtargetInfo.h"
45#include "llvm/CodeGen/ValueTypes.h"
46#include "llvm/CodeGenTypes/MachineValueType.h"
47#include "llvm/Config/llvm-config.h"
48#include "llvm/IR/Argument.h"
49#include "llvm/IR/Attributes.h"
50#include "llvm/IR/BasicBlock.h"
51#include "llvm/IR/CFG.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/CycleInfo.h"
55#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugInfo.h"
57#include "llvm/IR/DerivedTypes.h"
58#include "llvm/IR/Dominators.h"
59#include "llvm/IR/Function.h"
60#include "llvm/IR/GetElementPtrTypeIterator.h"
61#include "llvm/IR/GlobalValue.h"
62#include "llvm/IR/GlobalVariable.h"
63#include "llvm/IR/IRBuilder.h"
64#include "llvm/IR/InlineAsm.h"
65#include "llvm/IR/InstrTypes.h"
66#include "llvm/IR/Instruction.h"
67#include "llvm/IR/Instructions.h"
68#include "llvm/IR/IntrinsicInst.h"
69#include "llvm/IR/Intrinsics.h"
70#include "llvm/IR/IntrinsicsAArch64.h"
71#include "llvm/IR/LLVMContext.h"
72#include "llvm/IR/MDBuilder.h"
73#include "llvm/IR/Module.h"
74#include "llvm/IR/Operator.h"
75#include "llvm/IR/PatternMatch.h"
76#include "llvm/IR/ProfDataUtils.h"
77#include "llvm/IR/Statepoint.h"
78#include "llvm/IR/Type.h"
79#include "llvm/IR/Use.h"
80#include "llvm/IR/User.h"
81#include "llvm/IR/Value.h"
82#include "llvm/IR/ValueHandle.h"
83#include "llvm/IR/ValueMap.h"
84#include "llvm/InitializePasses.h"
85#include "llvm/Pass.h"
86#include "llvm/Support/BlockFrequency.h"
87#include "llvm/Support/BranchProbability.h"
88#include "llvm/Support/Casting.h"
89#include "llvm/Support/CommandLine.h"
90#include "llvm/Support/Compiler.h"
91#include "llvm/Support/Debug.h"
92#include "llvm/Support/ErrorHandling.h"
93#include "llvm/Support/raw_ostream.h"
94#include "llvm/Target/TargetMachine.h"
95#include "llvm/Target/TargetOptions.h"
96#include "llvm/Transforms/Utils/BasicBlockUtils.h"
97#include "llvm/Transforms/Utils/BypassSlowDivision.h"
98#include "llvm/Transforms/Utils/Local.h"
99#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
100#include "llvm/Transforms/Utils/SizeOpts.h"
101#include <algorithm>
102#include <cassert>
103#include <cstdint>
104#include <iterator>
105#include <limits>
106#include <memory>
107#include <optional>
108#include <utility>
109#include <vector>
110
111using namespace llvm;
112using namespace llvm::PatternMatch;
113
114#define DEBUG_TYPE "codegenprepare"
115
116STATISTIC(NumBlocksElim, "Number of blocks eliminated");
117STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
118STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
119STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
120 "sunken Cmps");
121STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
122 "of sunken Casts");
123STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
124 "computations were sunk");
125STATISTIC(NumMemoryInstsPhiCreated,
126 "Number of phis created when address "
127 "computations were sunk to memory instructions");
128STATISTIC(NumMemoryInstsSelectCreated,
129 "Number of select created when address "
130 "computations were sunk to memory instructions");
131STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
132STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
133STATISTIC(NumAndsAdded,
134 "Number of and mask instructions added to form ext loads");
135STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
136STATISTIC(NumRetsDup, "Number of return instructions duplicated");
137STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
138STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
139STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
140
141namespace {
142
143enum ExtType {
144 ZeroExtension, // Zero extension has been seen.
145 SignExtension, // Sign extension has been seen.
146 BothExtension // This extension type is used if we saw sext after
147 // ZeroExtension had been set, or if we saw zext after
148 // SignExtension had been set. It makes the type
149 // information of a promoted instruction invalid.
150};
151
152enum ModifyDT {
153 NotModifyDT, // Not Modify any DT.
154 ModifyBBDT, // Modify the Basic Block Dominator Tree.
155 ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
156 // This usually means we move/delete/insert instruction
157 // in a Basic Block. So we should re-iterate instructions
158 // in such Basic Block.
159};
160
161using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
162using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
163using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
164using SExts = SmallVector<Instruction *, 16>;
165using ValueToSExts = MapVector<Value *, SExts>;
166
167class TypePromotionTransaction;
168
169class CodeGenPrepare {
170 friend class CodeGenPrepareLegacyPass;
171 const CodeGenOptions &Opts = CodeGenOptions::Global;
172 const TargetMachine *TM = nullptr;
173 const TargetSubtargetInfo *SubtargetInfo = nullptr;
174 const TargetLowering *TLI = nullptr;
175 const TargetRegisterInfo *TRI = nullptr;
176 const TargetTransformInfo *TTI = nullptr;
177 const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
178 const TargetLibraryInfo *TLInfo = nullptr;
179 DomTreeUpdater *DTU = nullptr;
180 LoopInfo *LI = nullptr;
181 BlockFrequencyInfo *BFI;
182 BranchProbabilityInfo *BPI;
183 ProfileSummaryInfo *PSI = nullptr;
184
185 /// As we scan instructions optimizing them, this is the next instruction
186 /// to optimize. Transforms that can invalidate this should update it.
187 BasicBlock::iterator CurInstIterator;
188
189 /// Keeps track of non-local addresses that have been sunk into a block.
190 /// This allows us to avoid inserting duplicate code for blocks with
191 /// multiple load/stores of the same address. The usage of WeakTrackingVH
192 /// enables SunkAddrs to be treated as a cache whose entries can be
193 /// invalidated if a sunken address computation has been erased.
194 ValueMap<Value *, WeakTrackingVH> SunkAddrs;
195
196 /// Keeps track of all instructions inserted for the current function.
197 SetOfInstrs InsertedInsts;
198
199 /// Keeps track of the type of the related instruction before their
200 /// promotion for the current function.
201 InstrToOrigTy PromotedInsts;
202
203 /// Keep track of instructions removed during promotion.
204 SetOfInstrs RemovedInsts;
205
206 /// Keep track of sext chains based on their initial value.
207 DenseMap<Value *, Instruction *> SeenChainsForSExt;
208
209 /// Keep track of GEPs accessing the same data structures such as structs or
210 /// arrays that are candidates to be split later because of their large
211 /// size.
212 MapVector<AssertingVH<Value>,
213 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
214 LargeOffsetGEPMap;
215
216 /// Keep track of new GEP base after splitting the GEPs having large offset.
217 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
218
219 /// Map serial numbers to Large offset GEPs.
220 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
221
222 /// Keep track of SExt promoted.
223 ValueToSExts ValToSExtendedUses;
224
225 /// True if the function has the OptSize attribute.
226 bool OptSize;
227
228 /// DataLayout for the Function being processed.
229 const DataLayout *DL = nullptr;
230
231public:
232 CodeGenPrepare() = default;
233 CodeGenPrepare(const TargetMachine *TM) : TM(TM){};
234 /// If encounter huge function, we need to limit the build time.
235 bool IsHugeFunc = false;
236
237 /// FreshBBs is like worklist, it collected the updated BBs which need
238 /// to be optimized again.
239 /// Note: Consider building time in this pass, when a BB updated, we need
240 /// to insert such BB into FreshBBs for huge function.
241 SmallPtrSet<BasicBlock *, 32> FreshBBs;
242
243 void releaseMemory() {
244 // Clear per function information.
245 InsertedInsts.clear();
246 PromotedInsts.clear();
247 FreshBBs.clear();
248 }
249
250 bool run(Function &F, FunctionAnalysisManager &AM);
251
252private:
253 template <typename F>
254 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
255 // Substituting can cause recursive simplifications, which can invalidate
256 // our iterator. Use a WeakTrackingVH to hold onto it in case this
257 // happens.
258 Value *CurValue = &*CurInstIterator;
259 WeakTrackingVH IterHandle(CurValue);
260
261 f();
262
263 // If the iterator instruction was recursively deleted, start over at the
264 // start of the block.
265 if (IterHandle != CurValue) {
266 CurInstIterator = BB->begin();
267 SunkAddrs.clear();
268 }
269 }
270
271 // Get the DominatorTree, updating it if necessary.
272 DominatorTree &getDT() { return DTU->getDomTree(); }
273
274 void removeAllAssertingVHReferences(Value *V);
275 bool eliminateAssumptions(Function &F);
276 bool eliminateFallThrough(Function &F);
277 bool eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI);
278 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
279 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
280 bool eliminateMostlyEmptyBlock(BasicBlock *BB);
281 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
282 bool isPreheader);
283 bool makeBitReverse(Instruction &I);
284 bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
285 bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
286 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
287 unsigned AddrSpace);
288 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
289 bool optimizeMulWithOverflow(Instruction *I, bool IsSigned,
290 ModifyDT &ModifiedDT);
291 bool optimizeInlineAsmInst(CallInst *CS);
292 bool optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT);
293 bool optimizeExt(Instruction *&I);
294 bool optimizeExtUses(Instruction *I);
295 bool optimizeLoadExt(LoadInst *Load);
296 bool optimizeShiftInst(BinaryOperator *BO);
297 bool optimizeFunnelShift(IntrinsicInst *Fsh);
298 bool optimizeSelectInst(SelectInst *SI);
299 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
300 bool optimizeSwitchType(SwitchInst *SI);
301 bool optimizeSwitchPhiConstants(SwitchInst *SI);
302 bool optimizeSwitchInst(SwitchInst *SI);
303 bool optimizeExtractElementInst(Instruction *Inst);
304 bool dupRetToEnableTailCallOpts(BasicBlock *BB, ModifyDT &ModifiedDT);
305 bool fixupDbgVariableRecord(DbgVariableRecord &I);
306 bool fixupDbgVariableRecordsOnInst(Instruction &I);
307 bool placeDbgValues(Function &F);
308 bool placePseudoProbes(Function &F);
309 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
310 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
311 bool tryToPromoteExts(TypePromotionTransaction &TPT,
312 const SmallVectorImpl<Instruction *> &Exts,
313 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
314 unsigned CreatedInstsCost = 0);
315 bool mergeSExts(Function &F);
316 bool splitLargeGEPOffsets();
317 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
318 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
319 bool optimizePhiTypes(Function &F);
320 bool performAddressTypePromotion(
321 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
322 bool HasPromoted, TypePromotionTransaction &TPT,
323 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
324 bool splitBranchCondition(Function &F);
325 bool simplifyOffsetableRelocate(GCStatepointInst &I);
326
327 bool tryToSinkFreeOperands(Instruction *I);
328 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
329 CmpInst *Cmp, Intrinsic::ID IID);
330 bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
331 bool optimizeURem(Instruction *Rem);
332 bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
333 bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
334 bool unfoldPowerOf2Test(CmpInst *Cmp);
335 void verifyBFIUpdates(Function &F);
336 bool _run(Function &F);
337};
338
339class CodeGenPrepareLegacyPass : public FunctionPass {
340public:
341 static char ID; // Pass identification, replacement for typeid
342
343 CodeGenPrepareLegacyPass() : FunctionPass(ID) {}
344
345 bool runOnFunction(Function &F) override;
346
347 StringRef getPassName() const override { return "CodeGen Prepare"; }
348
349 void getAnalysisUsage(AnalysisUsage &AU) const override {
350 // FIXME: When we can selectively preserve passes, preserve the domtree.
351 AU.addRequired<ProfileSummaryInfoWrapperPass>();
352 AU.addRequired<TargetLibraryInfoWrapperPass>();
353 AU.addRequired<TargetPassConfig>();
354 AU.addRequired<TargetTransformInfoWrapperPass>();
355 AU.addRequired<DominatorTreeWrapperPass>();
356 AU.addRequired<LoopInfoWrapperPass>();
357 AU.addRequired<BranchProbabilityInfoWrapperPass>();
358 AU.addRequired<BlockFrequencyInfoWrapperPass>();
359 AU.addUsedIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
360 }
361};
362
363} // end anonymous namespace
364
365char CodeGenPrepareLegacyPass::ID = 0;
366
367bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
368 if (skipFunction(F))
369 return false;
370 auto TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
371 CodeGenPrepare CGP(TM);
372 CGP.DL = &F.getDataLayout();
373 CGP.SubtargetInfo = TM->getSubtargetImpl(F);
374 CGP.TLI = CGP.SubtargetInfo->getTargetLowering();
375 CGP.TRI = CGP.SubtargetInfo->getRegisterInfo();
376 CGP.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
377 CGP.TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
378 CGP.LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
379 CGP.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
380 CGP.BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
381 CGP.PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
382 auto BBSPRWP =
383 getAnalysisIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
384 CGP.BBSectionsProfileReader = BBSPRWP ? &BBSPRWP->getBBSPR() : nullptr;
385 DomTreeUpdater DTUpdater(
386 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
387 DomTreeUpdater::UpdateStrategy::Lazy);
388 CGP.DTU = &DTUpdater;
389
390 return CGP._run(F);
391}
392
393INITIALIZE_PASS_BEGIN(CodeGenPrepareLegacyPass, DEBUG_TYPE,
394 "Optimize for code generation", false, false)
395INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReaderWrapperPass)
396INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
397INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
398INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
399INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
400INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
401INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
402INITIALIZE_PASS_END(CodeGenPrepareLegacyPass, DEBUG_TYPE,
403 "Optimize for code generation", false, false)
404
405FunctionPass *llvm::createCodeGenPrepareLegacyPass() {
406 return new CodeGenPrepareLegacyPass();
407}
408
409PreservedAnalyses CodeGenPreparePass::run(Function &F,
410 FunctionAnalysisManager &AM) {
411 CodeGenPrepare CGP(TM);
412
413 bool Changed = CGP.run(F, AM);
414 if (!Changed)
415 return PreservedAnalyses::all();
416
417 PreservedAnalyses PA;
418 PA.preserve<TargetLibraryAnalysis>();
419 PA.preserve<TargetIRAnalysis>();
420 return PA;
421}
422
423bool CodeGenPrepare::run(Function &F, FunctionAnalysisManager &AM) {
424 DL = &F.getDataLayout();
425 SubtargetInfo = TM->getSubtargetImpl(F);
426 TLI = SubtargetInfo->getTargetLowering();
427 TRI = SubtargetInfo->getRegisterInfo();
428 TLInfo = &AM.getResult<TargetLibraryAnalysis>(IR&: F);
429 TTI = &AM.getResult<TargetIRAnalysis>(IR&: F);
430 LI = &AM.getResult<LoopAnalysis>(IR&: F);
431 BPI = &AM.getResult<BranchProbabilityAnalysis>(IR&: F);
432 BFI = &AM.getResult<BlockFrequencyAnalysis>(IR&: F);
433 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(IR&: F);
434 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(IR&: *F.getParent());
435 if (!PSI)
436 reportFatalUsageError(reason: "this pass requires the profile-summary module "
437 "analysis to be available");
438 BBSectionsProfileReader =
439 AM.getCachedResult<BasicBlockSectionsProfileReaderAnalysis>(IR&: F);
440 DomTreeUpdater DTUpdater(&AM.getResult<DominatorTreeAnalysis>(IR&: F),
441 DomTreeUpdater::UpdateStrategy::Lazy);
442 DTU = &DTUpdater;
443 return _run(F);
444}
445
446bool CodeGenPrepare::_run(Function &F) {
447 bool EverMadeChange = false;
448
449 OptSize = F.hasOptSize();
450 // Use the basic-block-sections profile to promote hot functions to .text.hot
451 // if requested.
452 if (Opts.bbsections_guided_section_prefix && BBSectionsProfileReader &&
453 BBSectionsProfileReader->isFunctionHot(FuncName: F.getName())) {
454 (void)F.setSectionPrefix("hot");
455 } else if (Opts.profile_guided_section_prefix) {
456 // The hot attribute overwrites profile count based hotness while profile
457 // counts based hotness overwrite the cold attribute.
458 // This is a conservative behabvior.
459 if (F.hasFnAttribute(Kind: Attribute::Hot) ||
460 PSI->isFunctionHotInCallGraph(F: &F, BFI&: *BFI))
461 (void)F.setSectionPrefix("hot");
462 // If PSI shows this function is not hot, we will placed the function
463 // into unlikely section if (1) PSI shows this is a cold function, or
464 // (2) the function has a attribute of cold.
465 else if (PSI->isFunctionColdInCallGraph(F: &F, BFI&: *BFI) ||
466 F.hasFnAttribute(Kind: Attribute::Cold))
467 (void)F.setSectionPrefix("unlikely");
468 else if (Opts.profile_unknown_in_special_section &&
469 PSI->hasPartialSampleProfile() && PSI->isFunctionHotnessUnknown(F))
470 (void)F.setSectionPrefix("unknown");
471 }
472
473 /// This optimization identifies DIV instructions that can be
474 /// profitably bypassed and carried out with a shorter, faster divide.
475 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
476 const DenseMap<unsigned int, unsigned int> &BypassWidths =
477 TLI->getBypassSlowDivWidths();
478 BasicBlock *BB = &*F.begin();
479 while (BB != nullptr) {
480 // bypassSlowDivision may create new BBs, but we don't want to reapply the
481 // optimization to those blocks.
482 BasicBlock *Next = BB->getNextNode();
483 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI))
484 EverMadeChange |= bypassSlowDivision(BB, BypassWidth: BypassWidths, DTU, LI, BPI);
485 BB = Next;
486 }
487 }
488
489 // Get rid of @llvm.assume builtins before attempting to eliminate empty
490 // blocks, since there might be blocks that only contain @llvm.assume calls
491 // (plus arguments that we can get rid of).
492 EverMadeChange |= eliminateAssumptions(F);
493
494 auto resetLoopInfo = [this]() {
495 LI->releaseMemory();
496 LI->analyze(DomTree: DTU->getDomTree());
497 };
498
499 // Eliminate blocks that contain only PHI nodes and an
500 // unconditional branch.
501 bool ResetLI = false;
502 EverMadeChange |= eliminateMostlyEmptyBlocks(F, ResetLI);
503 if (ResetLI)
504 resetLoopInfo();
505
506 if (Opts.cgp_branch_opts)
507 EverMadeChange |= splitBranchCondition(F);
508
509 // Split some critical edges where one of the sources is an indirect branch,
510 // to help generate sane code for PHIs involving such edges.
511 bool Split = SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true,
512 BPI, BFI, DTU);
513 EverMadeChange |= Split;
514 if (Split)
515 resetLoopInfo();
516
517#ifndef NDEBUG
518 if (VerifyDomInfo)
519 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
520 "Incorrect DominatorTree updates in CGP");
521
522 if (VerifyLoopInfo)
523 LI->verify();
524#endif
525
526 // If we are optimzing huge function, we need to consider the build time.
527 // Because the basic algorithm's complex is near O(N!).
528 IsHugeFunc = F.size() > Opts.cgp_huge_func;
529
530 bool MadeChange = true;
531 bool FuncIterated = false;
532 while (MadeChange) {
533 MadeChange = false;
534
535 // This is required because optimizeBlock() calls getDT() inside the loop
536 // below, which flushes pending updates and may delete dead blocks, leading
537 // to iterator invalidation.
538 DTU->flush();
539
540 for (BasicBlock &BB : llvm::make_early_inc_range(Range&: F)) {
541 if (FuncIterated && !FreshBBs.contains(Ptr: &BB))
542 continue;
543
544 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
545 bool Changed = optimizeBlock(BB, ModifiedDT&: ModifiedDTOnIteration);
546
547 MadeChange |= Changed;
548 if (IsHugeFunc) {
549 // If the BB is updated, it may still has chance to be optimized.
550 // This usually happen at sink optimization.
551 // For example:
552 //
553 // bb0:
554 // %and = and i32 %a, 4
555 // %cmp = icmp eq i32 %and, 0
556 //
557 // If the %cmp sink to other BB, the %and will has chance to sink.
558 if (Changed)
559 FreshBBs.insert(Ptr: &BB);
560 else if (FuncIterated)
561 FreshBBs.erase(Ptr: &BB);
562 } else {
563 // For small/normal functions, we restart BB iteration if the dominator
564 // tree of the Function was changed.
565 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
566 break;
567 }
568 }
569 // We have iterated all the BB in the (only work for huge) function.
570 FuncIterated = IsHugeFunc;
571
572 if (Opts.cgp_type_promotion_merge && !ValToSExtendedUses.empty())
573 MadeChange |= mergeSExts(F);
574 if (!LargeOffsetGEPMap.empty())
575 MadeChange |= splitLargeGEPOffsets();
576 MadeChange |= optimizePhiTypes(F);
577
578 if (MadeChange)
579 eliminateFallThrough(F);
580
581#ifndef NDEBUG
582 if (VerifyDomInfo)
583 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
584 "Incorrect DominatorTree updates in CGP");
585
586 if (VerifyLoopInfo)
587 LI->verify();
588#endif
589
590 // Really free removed instructions during promotion.
591 for (Instruction *I : RemovedInsts)
592 I->deleteValue();
593
594 EverMadeChange |= MadeChange;
595 SeenChainsForSExt.clear();
596 ValToSExtendedUses.clear();
597 RemovedInsts.clear();
598 LargeOffsetGEPMap.clear();
599 LargeOffsetGEPID.clear();
600 }
601
602 NewGEPBases.clear();
603 SunkAddrs.clear();
604
605 // LoopInfo is not needed anymore and ConstantFoldTerminator can break it.
606 LI = nullptr;
607
608 if (Opts.cgp_branch_opts) {
609 MadeChange = false;
610 // Use a set vector to get deterministic iteration order. The order the
611 // blocks are removed may affect whether or not PHI nodes in successors
612 // are removed.
613 SmallSetVector<BasicBlock *, 8> WorkList;
614 for (BasicBlock &BB : F) {
615 SmallVector<BasicBlock *, 2> Successors(successors(BB: &BB));
616 MadeChange |= ConstantFoldTerminator(BB: &BB, DeleteDeadConditions: true, TLI: nullptr, DTU);
617 if (!MadeChange)
618 continue;
619
620 for (BasicBlock *Succ : Successors)
621 if (pred_empty(BB: Succ))
622 WorkList.insert(X: Succ);
623 }
624
625 // Delete the dead blocks and any of their dead successors.
626 MadeChange |= !WorkList.empty();
627 while (!WorkList.empty()) {
628 BasicBlock *BB = WorkList.pop_back_val();
629 SmallVector<BasicBlock *, 2> Successors(successors(BB));
630
631 DeleteDeadBlock(BB, DTU);
632
633 for (BasicBlock *Succ : Successors)
634 if (pred_empty(BB: Succ))
635 WorkList.insert(X: Succ);
636 }
637
638 // Flush pending DT updates in order to finalise deletion of dead blocks.
639 DTU->flush();
640
641 // Merge pairs of basic blocks with unconditional branches, connected by
642 // a single edge.
643 if (EverMadeChange || MadeChange)
644 MadeChange |= eliminateFallThrough(F);
645
646 EverMadeChange |= MadeChange;
647 }
648
649 if (Opts.cgp_gc_opts) {
650 SmallVector<GCStatepointInst *, 2> Statepoints;
651 for (BasicBlock &BB : F)
652 for (Instruction &I : BB)
653 if (auto *SP = dyn_cast<GCStatepointInst>(Val: &I))
654 Statepoints.push_back(Elt: SP);
655 for (auto &I : Statepoints)
656 EverMadeChange |= simplifyOffsetableRelocate(I&: *I);
657 }
658
659 // Do this last to clean up use-before-def scenarios introduced by other
660 // preparatory transforms.
661 EverMadeChange |= placeDbgValues(F);
662 EverMadeChange |= placePseudoProbes(F);
663
664#ifndef NDEBUG
665 if (Opts.cgp_verify_bfi_updates)
666 verifyBFIUpdates(F);
667#endif
668
669 return EverMadeChange;
670}
671
672bool CodeGenPrepare::eliminateAssumptions(Function &F) {
673 bool MadeChange = false;
674 for (BasicBlock &BB : F) {
675 CurInstIterator = BB.begin();
676 while (CurInstIterator != BB.end()) {
677 Instruction *I = &*(CurInstIterator++);
678 if (auto *Assume = dyn_cast<AssumeInst>(Val: I)) {
679 MadeChange = true;
680 Value *Operand = Assume->getOperand(i_nocapture: 0);
681 Assume->eraseFromParent();
682
683 resetIteratorIfInvalidatedWhileCalling(BB: &BB, f: [&]() {
684 RecursivelyDeleteTriviallyDeadInstructions(V: Operand, TLI: TLInfo, MSSAU: nullptr);
685 });
686 }
687 }
688 }
689 return MadeChange;
690}
691
692/// An instruction is about to be deleted, so remove all references to it in our
693/// GEP-tracking data strcutures.
694void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
695 LargeOffsetGEPMap.erase(Key: V);
696 NewGEPBases.erase(V);
697
698 auto GEP = dyn_cast<GetElementPtrInst>(Val: V);
699 if (!GEP)
700 return;
701
702 LargeOffsetGEPID.erase(Val: GEP);
703
704 auto VecI = LargeOffsetGEPMap.find(Key: GEP->getPointerOperand());
705 if (VecI == LargeOffsetGEPMap.end())
706 return;
707
708 auto &GEPVector = VecI->second;
709 llvm::erase_if(C&: GEPVector, P: [=](auto &Elt) { return Elt.first == GEP; });
710
711 if (GEPVector.empty())
712 LargeOffsetGEPMap.erase(Iterator: VecI);
713}
714
715// Verify BFI has been updated correctly by recomputing BFI and comparing them.
716[[maybe_unused]] void CodeGenPrepare::verifyBFIUpdates(Function &F) {
717 DominatorTree NewDT(F);
718 CycleInfo NewCI;
719 NewCI.compute(F);
720 BranchProbabilityInfo NewBPI(F, NewCI, TLInfo);
721 BlockFrequencyInfo NewBFI(F, NewBPI, NewCI);
722 NewBFI.verifyMatch(Other&: *BFI);
723}
724
725/// Merge basic blocks which are connected by a single edge, where one of the
726/// basic blocks has a single successor pointing to the other basic block,
727/// which has a single predecessor.
728bool CodeGenPrepare::eliminateFallThrough(Function &F) {
729 bool Changed = false;
730 SmallPtrSet<BasicBlock *, 8> Preds;
731 // Scan all of the blocks in the function, except for the entry block.
732 for (auto &Block : llvm::drop_begin(RangeOrContainer&: F)) {
733 auto *BB = &Block;
734 if (DTU->isBBPendingDeletion(DelBB: BB))
735 continue;
736 // If the destination block has a single pred, then this is a trivial
737 // edge, just collapse it.
738 BasicBlock *SinglePred = BB->getSinglePredecessor();
739
740 // Don't merge if BB's address is taken.
741 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
742 continue;
743
744 if (isa<UncondBrInst>(Val: SinglePred->getTerminator())) {
745 Changed = true;
746 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
747
748 // Merge BB into SinglePred and delete it.
749 MergeBlockIntoPredecessor(BB, DTU, LI);
750 Preds.insert(Ptr: SinglePred);
751
752 if (IsHugeFunc) {
753 // Update FreshBBs to optimize the merged BB.
754 FreshBBs.insert(Ptr: SinglePred);
755 FreshBBs.erase(Ptr: BB);
756 }
757 }
758 }
759
760 // (Repeatedly) merging blocks into their predecessors can create redundant
761 // debug intrinsics.
762 for (auto *Pred : Preds)
763 if (!DTU->isBBPendingDeletion(DelBB: Pred))
764 RemoveRedundantDbgInstrs(BB: Pred);
765
766 return Changed;
767}
768
769/// Find a destination block from BB if BB is mergeable empty block.
770BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
771 // If this block doesn't end with an uncond branch, ignore it.
772 UncondBrInst *BI = dyn_cast<UncondBrInst>(Val: BB->getTerminator());
773 if (!BI)
774 return nullptr;
775
776 // If the instruction before the branch (skipping debug info) isn't a phi
777 // node, then other stuff is happening here.
778 BasicBlock::iterator BBI = BI->getIterator();
779 if (BBI != BB->begin()) {
780 --BBI;
781 if (!isa<PHINode>(Val: BBI))
782 return nullptr;
783 }
784
785 // Do not break infinite loops.
786 BasicBlock *DestBB = BI->getSuccessor();
787 if (DestBB == BB)
788 return nullptr;
789
790 if (!canMergeBlocks(BB, DestBB))
791 DestBB = nullptr;
792
793 return DestBB;
794}
795
796/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
797/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
798/// edges in ways that are non-optimal for isel. Start by eliminating these
799/// blocks so we can split them the way we want them.
800bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI) {
801 SmallPtrSet<BasicBlock *, 16> Preheaders;
802 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
803 while (!LoopList.empty()) {
804 Loop *L = LoopList.pop_back_val();
805 llvm::append_range(C&: LoopList, R&: *L);
806 if (BasicBlock *Preheader = L->getLoopPreheader())
807 Preheaders.insert(Ptr: Preheader);
808 }
809
810 ResetLI = false;
811 bool MadeChange = false;
812 SmallPtrSet<PHINode *, 32> KnownNonDeadPHIs;
813 // Note that this intentionally skips the entry block.
814 for (auto &Block : llvm::drop_begin(RangeOrContainer&: F)) {
815 // Delete phi nodes that could block deleting other empty blocks.
816 if (Opts.cgp_delete_phis)
817 MadeChange |= DeleteDeadPHIs(BB: &Block, TLI: TLInfo, MSSAU: nullptr, KnownNonDeadPHIs: &KnownNonDeadPHIs);
818 }
819
820 for (auto &Block : llvm::drop_begin(RangeOrContainer&: F)) {
821 auto *BB = &Block;
822 if (DTU->isBBPendingDeletion(DelBB: BB))
823 continue;
824 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
825 if (!DestBB ||
826 !isMergingEmptyBlockProfitable(BB, DestBB, isPreheader: Preheaders.count(Ptr: BB)))
827 continue;
828
829 ResetLI |= eliminateMostlyEmptyBlock(BB);
830 MadeChange = true;
831 }
832 return MadeChange;
833}
834
835bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
836 BasicBlock *DestBB,
837 bool isPreheader) {
838 // Do not delete loop preheaders if doing so would create a critical edge.
839 // Loop preheaders can be good locations to spill registers. If the
840 // preheader is deleted and we create a critical edge, registers may be
841 // spilled in the loop body instead.
842 if (Opts.cgp_preheader_prot && isPreheader &&
843 !(BB->getSinglePredecessor() &&
844 BB->getSinglePredecessor()->getSingleSuccessor()))
845 return false;
846
847 // Skip merging if the block's successor is also a successor to any callbr
848 // that leads to this block.
849 // FIXME: Is this really needed? Is this a correctness issue?
850 for (BasicBlock *Pred : predecessors(BB)) {
851 if (isa<CallBrInst>(Val: Pred->getTerminator()) &&
852 llvm::is_contained(Range: successors(BB: Pred), Element: DestBB))
853 return false;
854 }
855
856 // Try to skip merging if the unique predecessor of BB is terminated by a
857 // switch or indirect branch instruction, and BB is used as an incoming block
858 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
859 // add COPY instructions in the predecessor of BB instead of BB (if it is not
860 // merged). Note that the critical edge created by merging such blocks wont be
861 // split in MachineSink because the jump table is not analyzable. By keeping
862 // such empty block (BB), ISel will place COPY instructions in BB, not in the
863 // predecessor of BB.
864 BasicBlock *Pred = BB->getUniquePredecessor();
865 if (!Pred || !(isa<SwitchInst>(Val: Pred->getTerminator()) ||
866 isa<IndirectBrInst>(Val: Pred->getTerminator())))
867 return true;
868
869 if (BB->getTerminator() != &*BB->getFirstNonPHIOrDbg())
870 return true;
871
872 // We use a simple cost heuristic which determine skipping merging is
873 // profitable if the cost of skipping merging is less than the cost of
874 // merging : Cost(skipping merging) < Cost(merging BB), where the
875 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
876 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
877 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
878 // Freq(Pred) / Freq(BB) > 2.
879 // Note that if there are multiple empty blocks sharing the same incoming
880 // value for the PHIs in the DestBB, we consider them together. In such
881 // case, Cost(merging BB) will be the sum of their frequencies.
882
883 if (!isa<PHINode>(Val: DestBB->begin()))
884 return true;
885
886 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
887
888 // Find all other incoming blocks from which incoming values of all PHIs in
889 // DestBB are the same as the ones from BB.
890 for (BasicBlock *DestBBPred : predecessors(BB: DestBB)) {
891 if (DestBBPred == BB)
892 continue;
893
894 if (llvm::all_of(Range: DestBB->phis(), P: [&](const PHINode &DestPN) {
895 return DestPN.getIncomingValueForBlock(BB) ==
896 DestPN.getIncomingValueForBlock(BB: DestBBPred);
897 }))
898 SameIncomingValueBBs.insert(Ptr: DestBBPred);
899 }
900
901 // See if all BB's incoming values are same as the value from Pred. In this
902 // case, no reason to skip merging because COPYs are expected to be place in
903 // Pred already.
904 if (SameIncomingValueBBs.count(Ptr: Pred))
905 return true;
906
907 BlockFrequency PredFreq = BFI->getBlockFreq(BB: Pred);
908 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
909
910 for (auto *SameValueBB : SameIncomingValueBBs)
911 if (SameValueBB->getUniquePredecessor() == Pred &&
912 DestBB == findDestBlockOfMergeableEmptyBlock(BB: SameValueBB))
913 BBFreq += BFI->getBlockFreq(BB: SameValueBB);
914
915 std::optional<BlockFrequency> Limit =
916 BBFreq.mul(Factor: Opts.cgp_freq_ratio_to_skip_merge);
917 return !Limit || PredFreq <= *Limit;
918}
919
920/// Return true if we can merge BB into DestBB if there is a single
921/// unconditional branch between them, and BB contains no other non-phi
922/// instructions.
923bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
924 const BasicBlock *DestBB) const {
925 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
926 // the successor. If there are more complex condition (e.g. preheaders),
927 // don't mess around with them.
928 for (const PHINode &PN : BB->phis()) {
929 for (const User *U : PN.users()) {
930 const Instruction *UI = cast<Instruction>(Val: U);
931 if (UI->getParent() != DestBB || !isa<PHINode>(Val: UI))
932 return false;
933 // If User is inside DestBB block and it is a PHINode then check
934 // incoming value. If incoming value is not from BB then this is
935 // a complex condition (e.g. preheaders) we want to avoid here.
936 if (UI->getParent() == DestBB) {
937 if (const PHINode *UPN = dyn_cast<PHINode>(Val: UI))
938 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
939 Instruction *Insn = dyn_cast<Instruction>(Val: UPN->getIncomingValue(i: I));
940 if (Insn && Insn->getParent() == BB &&
941 Insn->getParent() != UPN->getIncomingBlock(i: I))
942 return false;
943 }
944 }
945 }
946 }
947
948 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
949 // and DestBB may have conflicting incoming values for the block. If so, we
950 // can't merge the block.
951 const PHINode *DestBBPN = dyn_cast<PHINode>(Val: DestBB->begin());
952 if (!DestBBPN)
953 return true; // no conflict.
954
955 // Collect the preds of BB.
956 SmallPtrSet<const BasicBlock *, 16> BBPreds;
957 if (const PHINode *BBPN = dyn_cast<PHINode>(Val: BB->begin())) {
958 // It is faster to get preds from a PHI than with pred_iterator.
959 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
960 BBPreds.insert(Ptr: BBPN->getIncomingBlock(i));
961 } else {
962 BBPreds.insert_range(R: predecessors(BB));
963 }
964
965 // Walk the preds of DestBB.
966 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
967 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
968 if (BBPreds.count(Ptr: Pred)) { // Common predecessor?
969 for (const PHINode &PN : DestBB->phis()) {
970 const Value *V1 = PN.getIncomingValueForBlock(BB: Pred);
971 const Value *V2 = PN.getIncomingValueForBlock(BB);
972
973 // If V2 is a phi node in BB, look up what the mapped value will be.
974 if (const PHINode *V2PN = dyn_cast<PHINode>(Val: V2))
975 if (V2PN->getParent() == BB)
976 V2 = V2PN->getIncomingValueForBlock(BB: Pred);
977
978 // If there is a conflict, bail out.
979 if (V1 != V2)
980 return false;
981 }
982 }
983 }
984
985 return true;
986}
987
988/// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
989static void replaceAllUsesWith(Value *Old, Value *New,
990 SmallPtrSet<BasicBlock *, 32> &FreshBBs,
991 bool IsHuge) {
992 auto *OldI = dyn_cast<Instruction>(Val: Old);
993 if (OldI) {
994 for (Instruction::user_iterator UI = OldI->user_begin(),
995 E = OldI->user_end();
996 UI != E; ++UI) {
997 Instruction *User = cast<Instruction>(Val: *UI);
998 if (IsHuge)
999 FreshBBs.insert(Ptr: User->getParent());
1000 }
1001 }
1002 Old->replaceAllUsesWith(V: New);
1003}
1004
1005/// Eliminate a basic block that has only phi's and an unconditional branch in
1006/// it.
1007/// Indicate that the LoopInfo was modified only if it wasn't updated.
1008bool CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1009 UncondBrInst *BI = cast<UncondBrInst>(Val: BB->getTerminator());
1010 BasicBlock *DestBB = BI->getSuccessor();
1011
1012 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
1013 << *BB << *DestBB);
1014
1015 // If the destination block has a single pred, then this is a trivial edge,
1016 // just collapse it.
1017 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1018 if (SinglePred != DestBB) {
1019 assert(SinglePred == BB &&
1020 "Single predecessor not the same as predecessor");
1021 // Merge DestBB into SinglePred/BB and delete it.
1022 MergeBlockIntoPredecessor(BB: DestBB, DTU, LI);
1023 // Note: BB(=SinglePred) will not be deleted on this path.
1024 // DestBB(=its single successor) is the one that was deleted.
1025 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
1026
1027 if (IsHugeFunc) {
1028 // Update FreshBBs to optimize the merged BB.
1029 FreshBBs.insert(Ptr: SinglePred);
1030 FreshBBs.erase(Ptr: DestBB);
1031 }
1032 return false;
1033 }
1034 }
1035
1036 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1037 // to handle the new incoming edges it is about to have.
1038 for (PHINode &PN : DestBB->phis()) {
1039 // Remove the incoming value for BB, and remember it.
1040 Value *InVal = PN.removeIncomingValue(BB, DeletePHIIfEmpty: false);
1041
1042 // Two options: either the InVal is a phi node defined in BB or it is some
1043 // value that dominates BB.
1044 PHINode *InValPhi = dyn_cast<PHINode>(Val: InVal);
1045 if (InValPhi && InValPhi->getParent() == BB) {
1046 // Add all of the input values of the input PHI as inputs of this phi.
1047 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1048 PN.addIncoming(V: InValPhi->getIncomingValue(i),
1049 BB: InValPhi->getIncomingBlock(i));
1050 } else {
1051 // Otherwise, add one instance of the dominating value for each edge that
1052 // we will be adding.
1053 if (PHINode *BBPN = dyn_cast<PHINode>(Val: BB->begin())) {
1054 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1055 PN.addIncoming(V: InVal, BB: BBPN->getIncomingBlock(i));
1056 } else {
1057 for (BasicBlock *Pred : predecessors(BB))
1058 PN.addIncoming(V: InVal, BB: Pred);
1059 }
1060 }
1061 }
1062
1063 // Preserve loop Metadata.
1064 if (BI->hasMetadata(KindID: LLVMContext::MD_loop)) {
1065 for (auto *Pred : predecessors(BB))
1066 Pred->getTerminator()->copyMetadata(SrcInst: *BI, WL: LLVMContext::MD_loop);
1067 }
1068
1069 // The PHIs are now updated, change everything that refers to BB to use
1070 // DestBB and remove BB.
1071 SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1072 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1073 SmallPtrSet<BasicBlock *, 8> PredOfDestBB(llvm::from_range,
1074 predecessors(BB: DestBB));
1075 for (auto *Pred : predecessors(BB)) {
1076 if (!PredOfDestBB.contains(Ptr: Pred)) {
1077 if (SeenPreds.insert(Ptr: Pred).second)
1078 DTUpdates.push_back(Elt: {DominatorTree::Insert, Pred, DestBB});
1079 }
1080 }
1081 SeenPreds.clear();
1082 for (auto *Pred : predecessors(BB)) {
1083 if (SeenPreds.insert(Ptr: Pred).second)
1084 DTUpdates.push_back(Elt: {DominatorTree::Delete, Pred, BB});
1085 }
1086 DTUpdates.push_back(Elt: {DominatorTree::Delete, BB, DestBB});
1087 BB->replaceAllUsesWith(V: DestBB);
1088 DTU->applyUpdates(Updates: DTUpdates);
1089 DTU->deleteBB(DelBB: BB);
1090 ++NumBlocksElim;
1091
1092 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1093 return true;
1094}
1095
1096// Computes a map of base pointer relocation instructions to corresponding
1097// derived pointer relocation instructions given a vector of all relocate calls
1098static void computeBaseDerivedRelocateMap(
1099 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1100 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>>
1101 &RelocateInstMap) {
1102 // Collect information in two maps: one primarily for locating the base object
1103 // while filling the second map; the second map is the final structure holding
1104 // a mapping between Base and corresponding Derived relocate calls
1105 MapVector<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1106 for (auto *ThisRelocate : AllRelocateCalls) {
1107 auto K = std::make_pair(x: ThisRelocate->getBasePtrIndex(),
1108 y: ThisRelocate->getDerivedPtrIndex());
1109 RelocateIdxMap.insert(KV: std::make_pair(x&: K, y&: ThisRelocate));
1110 }
1111 for (auto &Item : RelocateIdxMap) {
1112 std::pair<unsigned, unsigned> Key = Item.first;
1113 if (Key.first == Key.second)
1114 // Base relocation: nothing to insert
1115 continue;
1116
1117 GCRelocateInst *I = Item.second;
1118 auto BaseKey = std::make_pair(x&: Key.first, y&: Key.first);
1119
1120 // We're iterating over RelocateIdxMap so we cannot modify it.
1121 auto MaybeBase = RelocateIdxMap.find(Key: BaseKey);
1122 if (MaybeBase == RelocateIdxMap.end())
1123 // TODO: We might want to insert a new base object relocate and gep off
1124 // that, if there are enough derived object relocates.
1125 continue;
1126
1127 RelocateInstMap[MaybeBase->second].push_back(Elt: I);
1128 }
1129}
1130
1131// Accepts a GEP and extracts the operands into a vector provided they're all
1132// small integer constants
1133static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1134 SmallVectorImpl<Value *> &OffsetV) {
1135 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1136 // Only accept small constant integer operands
1137 auto *Op = dyn_cast<ConstantInt>(Val: GEP->getOperand(i_nocapture: i));
1138 if (!Op || Op->getZExtValue() > 20)
1139 return false;
1140 }
1141
1142 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1143 OffsetV.push_back(Elt: GEP->getOperand(i_nocapture: i));
1144 return true;
1145}
1146
1147// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1148// replace, computes a replacement, and affects it.
1149static bool
1150simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1151 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1152 bool MadeChange = false;
1153 // We must ensure the relocation of derived pointer is defined after
1154 // relocation of base pointer. If we find a relocation corresponding to base
1155 // defined earlier than relocation of base then we move relocation of base
1156 // right before found relocation. We consider only relocation in the same
1157 // basic block as relocation of base. Relocations from other basic block will
1158 // be skipped by optimization and we do not care about them.
1159 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1160 &*R != RelocatedBase; ++R)
1161 if (auto *RI = dyn_cast<GCRelocateInst>(Val&: R))
1162 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1163 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1164 RelocatedBase->moveBefore(InsertPos: RI->getIterator());
1165 MadeChange = true;
1166 break;
1167 }
1168
1169 for (GCRelocateInst *ToReplace : Targets) {
1170 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1171 "Not relocating a derived object of the original base object");
1172 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1173 // A duplicate relocate call. TODO: coalesce duplicates.
1174 continue;
1175 }
1176
1177 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1178 // Base and derived relocates are in different basic blocks.
1179 // In this case transform is only valid when base dominates derived
1180 // relocate. However it would be too expensive to check dominance
1181 // for each such relocate, so we skip the whole transformation.
1182 continue;
1183 }
1184
1185 Value *Base = ToReplace->getBasePtr();
1186 auto *Derived = dyn_cast<GetElementPtrInst>(Val: ToReplace->getDerivedPtr());
1187 if (!Derived || Derived->getPointerOperand() != Base)
1188 continue;
1189
1190 SmallVector<Value *, 2> OffsetV;
1191 if (!getGEPSmallConstantIntOffsetV(GEP: Derived, OffsetV))
1192 continue;
1193
1194 // Create a Builder and replace the target callsite with a gep
1195 assert(RelocatedBase->getNextNode() &&
1196 "Should always have one since it's not a terminator");
1197
1198 // Insert after RelocatedBase
1199 IRBuilder<> Builder(RelocatedBase->getNextNode());
1200 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1201
1202 // If gc_relocate does not match the actual type, cast it to the right type.
1203 // In theory, there must be a bitcast after gc_relocate if the type does not
1204 // match, and we should reuse it to get the derived pointer. But it could be
1205 // cases like this:
1206 // bb1:
1207 // ...
1208 // %g1 = call coldcc i8 addrspace(1)*
1209 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1210 //
1211 // bb2:
1212 // ...
1213 // %g2 = call coldcc i8 addrspace(1)*
1214 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1215 //
1216 // merge:
1217 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1218 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1219 //
1220 // In this case, we can not find the bitcast any more. So we insert a new
1221 // bitcast no matter there is already one or not. In this way, we can handle
1222 // all cases, and the extra bitcast should be optimized away in later
1223 // passes.
1224 Value *ActualRelocatedBase = RelocatedBase;
1225 if (RelocatedBase->getType() != Base->getType()) {
1226 ActualRelocatedBase =
1227 Builder.CreateBitCast(V: RelocatedBase, DestTy: Base->getType());
1228 }
1229 Value *Replacement =
1230 Builder.CreateGEP(Ty: Derived->getSourceElementType(), Ptr: ActualRelocatedBase,
1231 IdxList: ArrayRef(OffsetV));
1232 Replacement->takeName(V: ToReplace);
1233 // If the newly generated derived pointer's type does not match the original
1234 // derived pointer's type, cast the new derived pointer to match it. Same
1235 // reasoning as above.
1236 Value *ActualReplacement = Replacement;
1237 if (Replacement->getType() != ToReplace->getType()) {
1238 ActualReplacement =
1239 Builder.CreateBitCast(V: Replacement, DestTy: ToReplace->getType());
1240 }
1241 ToReplace->replaceAllUsesWith(V: ActualReplacement);
1242 ToReplace->eraseFromParent();
1243
1244 MadeChange = true;
1245 }
1246 return MadeChange;
1247}
1248
1249// Turns this:
1250//
1251// %base = ...
1252// %ptr = gep %base + 15
1253// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1254// %base' = relocate(%tok, i32 4, i32 4)
1255// %ptr' = relocate(%tok, i32 4, i32 5)
1256// %val = load %ptr'
1257//
1258// into this:
1259//
1260// %base = ...
1261// %ptr = gep %base + 15
1262// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1263// %base' = gc.relocate(%tok, i32 4, i32 4)
1264// %ptr' = gep %base' + 15
1265// %val = load %ptr'
1266bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1267 bool MadeChange = false;
1268 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1269 for (auto *U : I.users())
1270 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(Val: U))
1271 // Collect all the relocate calls associated with a statepoint
1272 AllRelocateCalls.push_back(Elt: Relocate);
1273
1274 // We need at least one base pointer relocation + one derived pointer
1275 // relocation to mangle
1276 if (AllRelocateCalls.size() < 2)
1277 return false;
1278
1279 // RelocateInstMap is a mapping from the base relocate instruction to the
1280 // corresponding derived relocate instructions
1281 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>> RelocateInstMap;
1282 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1283 if (RelocateInstMap.empty())
1284 return false;
1285
1286 for (auto &Item : RelocateInstMap)
1287 // Item.first is the RelocatedBase to offset against
1288 // Item.second is the vector of Targets to replace
1289 MadeChange = simplifyRelocatesOffABase(RelocatedBase: Item.first, Targets: Item.second);
1290 return MadeChange;
1291}
1292
1293/// Sink the specified cast instruction into its user blocks.
1294static bool SinkCast(CastInst *CI) {
1295 BasicBlock *DefBB = CI->getParent();
1296
1297 /// InsertedCasts - Only insert a cast in each block once.
1298 DenseMap<BasicBlock *, CastInst *> InsertedCasts;
1299
1300 bool MadeChange = false;
1301 for (Instruction::user_iterator UI = CI->user_begin(), E = CI->user_end();
1302 UI != E;) {
1303 Use &TheUse = UI.getUse();
1304 Instruction *User = cast<Instruction>(Val: *UI);
1305
1306 // Figure out which BB this cast is used in. For PHI's this is the
1307 // appropriate predecessor block.
1308 BasicBlock *UserBB = User->getParent();
1309 if (PHINode *PN = dyn_cast<PHINode>(Val: User)) {
1310 UserBB = PN->getIncomingBlock(U: TheUse);
1311 }
1312
1313 // Preincrement use iterator so we don't invalidate it.
1314 ++UI;
1315
1316 // The first insertion point of a block containing an EH pad is after the
1317 // pad. If the pad is the user, we cannot sink the cast past the pad.
1318 if (User->isEHPad())
1319 continue;
1320
1321 // If the block selected to receive the cast is an EH pad that does not
1322 // allow non-PHI instructions before the terminator, we can't sink the
1323 // cast.
1324 if (UserBB->getTerminator()->isEHPad())
1325 continue;
1326
1327 // If this user is in the same block as the cast, don't change the cast.
1328 if (UserBB == DefBB)
1329 continue;
1330
1331 // If we have already inserted a cast into this block, use it.
1332 CastInst *&InsertedCast = InsertedCasts[UserBB];
1333
1334 if (!InsertedCast) {
1335 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1336 assert(InsertPt != UserBB->end());
1337 InsertedCast = cast<CastInst>(Val: CI->clone());
1338 InsertedCast->insertBefore(BB&: *UserBB, InsertPos: InsertPt);
1339 }
1340
1341 // Replace a use of the cast with a use of the new cast.
1342 TheUse = InsertedCast;
1343 MadeChange = true;
1344 ++NumCastUses;
1345 }
1346
1347 // If we removed all uses, nuke the cast.
1348 if (CI->use_empty()) {
1349 salvageDebugInfo(I&: *CI);
1350 CI->eraseFromParent();
1351 MadeChange = true;
1352 }
1353
1354 return MadeChange;
1355}
1356
1357/// Hoists bitcasts to the source block to reduce register pressure
1358static bool optimizeBitCast(BitCastInst *BCI, const TargetLowering &TLI,
1359 const DataLayout &DL) {
1360 auto *SrcInst = dyn_cast<Instruction>(Val: BCI->getOperand(i_nocapture: 0));
1361 if (!SrcInst || SrcInst->getParent() == BCI->getParent() ||
1362 SrcInst->isTerminator())
1363 return false;
1364
1365 Type *DestTy = BCI->getType();
1366 Type *SrcTy = SrcInst->getType();
1367 EVT SrcVT = TLI.getValueType(DL, Ty: SrcTy);
1368 EVT DestVT = TLI.getValueType(DL, Ty: DestTy);
1369
1370 // Bail out on scalable vectors and illegal destination types
1371 if (SrcVT.isScalableVector() || DestVT.isScalableVector())
1372 return false;
1373
1374 // Only hoist if it reduces physical register count
1375 if (TLI.getNumRegisters(Context&: BCI->getContext(), VT: SrcVT) <=
1376 TLI.getNumRegisters(Context&: BCI->getContext(), VT: DestVT))
1377 return false;
1378
1379 // Block large or cross-domain scalars to prevent spills and broken atomics.
1380 bool IsCrossDomain = DestTy->isFPOrFPVectorTy() != SrcTy->isFPOrFPVectorTy();
1381
1382 // A scalar is large if it requires more than one native register.
1383 unsigned NativeWidth = DL.getPointerSizeInBits();
1384 bool IsLargeScalar =
1385 !DestTy->isVectorTy() &&
1386 DL.getTypeSizeInBits(Ty: DestTy).getFixedValue() > NativeWidth;
1387
1388 if (IsCrossDomain || IsLargeScalar)
1389 return false;
1390
1391 // Hoist the bitcast
1392 BasicBlock *SrcBB = SrcInst->getParent();
1393 auto InsertPt = isa<PHINode>(Val: SrcInst) ? SrcBB->getFirstInsertionPt()
1394 : std::next(x: SrcInst->getIterator());
1395 BCI->moveBefore(BB&: *SrcBB, I: InsertPt);
1396
1397 return true;
1398}
1399
1400/// If the specified cast instruction is a noop copy (e.g. it's casting from
1401/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1402/// reduce the number of virtual registers that must be created and coalesced.
1403///
1404/// Return true if any changes are made.
1405static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1406 const DataLayout &DL) {
1407 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1408 // than sinking only nop casts, but is helpful on some platforms.
1409 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(Val: CI)) {
1410 if (!TLI.isFreeAddrSpaceCast(DL, SrcAS: ASC->getSrcAddressSpace(),
1411 DestAS: ASC->getDestAddressSpace()))
1412 return false;
1413 }
1414
1415 // If this is a noop copy,
1416 EVT SrcVT = TLI.getValueType(DL, Ty: CI->getOperand(i_nocapture: 0)->getType());
1417 EVT DstVT = TLI.getValueType(DL, Ty: CI->getType());
1418
1419 // This is an fp<->int conversion?
1420 if (SrcVT.isInteger() != DstVT.isInteger())
1421 return false;
1422
1423 // If this is an extension, it will be a zero or sign extension, which
1424 // isn't a noop.
1425 if (SrcVT.bitsLT(VT: DstVT))
1426 return false;
1427
1428 // If these values will be promoted, find out what they will be promoted
1429 // to. This helps us consider truncates on PPC as noop copies when they
1430 // are.
1431 if (TLI.getTypeAction(Context&: CI->getContext(), VT: SrcVT) ==
1432 TargetLowering::TypePromoteInteger)
1433 SrcVT = TLI.getTypeToTransformTo(Context&: CI->getContext(), VT: SrcVT);
1434 if (TLI.getTypeAction(Context&: CI->getContext(), VT: DstVT) ==
1435 TargetLowering::TypePromoteInteger)
1436 DstVT = TLI.getTypeToTransformTo(Context&: CI->getContext(), VT: DstVT);
1437
1438 // If, after promotion, these are the same types, this is a noop copy.
1439 if (SrcVT != DstVT)
1440 return false;
1441
1442 return SinkCast(CI);
1443}
1444
1445// Match a simple increment by constant operation. Note that if a sub is
1446// matched, the step is negated (as if the step had been canonicalized to
1447// an add, even though we leave the instruction alone.)
1448static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1449 Constant *&Step) {
1450 if (match(V: IVInc, P: m_Add(L: m_Instruction(I&: LHS), R: m_Constant(C&: Step))) ||
1451 match(V: IVInc, P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::uadd_with_overflow>(
1452 Ops: m_Instruction(I&: LHS), Ops: m_Constant(C&: Step)))))
1453 return true;
1454 if (match(V: IVInc, P: m_Sub(L: m_Instruction(I&: LHS), R: m_Constant(C&: Step))) ||
1455 match(V: IVInc, P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::usub_with_overflow>(
1456 Ops: m_Instruction(I&: LHS), Ops: m_Constant(C&: Step))))) {
1457 Step = ConstantExpr::getNeg(C: Step);
1458 return true;
1459 }
1460 return false;
1461}
1462
1463/// If given \p PN is an inductive variable with value IVInc coming from the
1464/// backedge, and on each iteration it gets increased by Step, return pair
1465/// <IVInc, Step>. Otherwise, return std::nullopt.
1466static std::optional<std::pair<Instruction *, Constant *>>
1467getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1468 const Loop *L = LI->getLoopFor(BB: PN->getParent());
1469 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1470 return std::nullopt;
1471 auto *IVInc =
1472 dyn_cast<Instruction>(Val: PN->getIncomingValueForBlock(BB: L->getLoopLatch()));
1473 if (!IVInc || LI->getLoopFor(BB: IVInc->getParent()) != L)
1474 return std::nullopt;
1475 Instruction *LHS = nullptr;
1476 Constant *Step = nullptr;
1477 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1478 return std::make_pair(x&: IVInc, y&: Step);
1479 return std::nullopt;
1480}
1481
1482static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1483 auto *I = dyn_cast<Instruction>(Val: V);
1484 if (!I)
1485 return false;
1486 Instruction *LHS = nullptr;
1487 Constant *Step = nullptr;
1488 if (!matchIncrement(IVInc: I, LHS, Step))
1489 return false;
1490 if (auto *PN = dyn_cast<PHINode>(Val: LHS))
1491 if (auto IVInc = getIVIncrement(PN, LI))
1492 return IVInc->first == I;
1493 return false;
1494}
1495
1496bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1497 Value *Arg0, Value *Arg1,
1498 CmpInst *Cmp,
1499 Intrinsic::ID IID) {
1500 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1501 if (!isIVIncrement(V: BO, LI))
1502 return false;
1503 const Loop *L = LI->getLoopFor(BB: BO->getParent());
1504 assert(L && "L should not be null after isIVIncrement()");
1505 // Do not risk on moving increment into a child loop.
1506 if (LI->getLoopFor(BB: Cmp->getParent()) != L)
1507 return false;
1508
1509 // Finally, we need to ensure that the insert point will dominate all
1510 // existing uses of the increment.
1511
1512 auto &DT = getDT();
1513 if (DT.dominates(A: Cmp->getParent(), B: BO->getParent()))
1514 // If we're moving up the dom tree, all uses are trivially dominated.
1515 // (This is the common case for code produced by LSR.)
1516 return true;
1517
1518 // Otherwise, special case the single use in the phi recurrence.
1519 return BO->hasOneUse() && DT.dominates(A: Cmp->getParent(), B: L->getLoopLatch());
1520 };
1521 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1522 // We used to use a dominator tree here to allow multi-block optimization.
1523 // But that was problematic because:
1524 // 1. It could cause a perf regression by hoisting the math op into the
1525 // critical path.
1526 // 2. It could cause a perf regression by creating a value that was live
1527 // across multiple blocks and increasing register pressure.
1528 // 3. Use of a dominator tree could cause large compile-time regression.
1529 // This is because we recompute the DT on every change in the main CGP
1530 // run-loop. The recomputing is probably unnecessary in many cases, so if
1531 // that was fixed, using a DT here would be ok.
1532 //
1533 // There is one important particular case we still want to handle: if BO is
1534 // the IV increment. Important properties that make it profitable:
1535 // - We can speculate IV increment anywhere in the loop (as long as the
1536 // indvar Phi is its only user);
1537 // - Upon computing Cmp, we effectively compute something equivalent to the
1538 // IV increment (despite it loops differently in the IR). So moving it up
1539 // to the cmp point does not really increase register pressure.
1540 return false;
1541 }
1542
1543 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1544 if (BO->getOpcode() == Instruction::Add &&
1545 IID == Intrinsic::usub_with_overflow) {
1546 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1547 Arg1 = ConstantExpr::getNeg(C: cast<Constant>(Val: Arg1));
1548 }
1549
1550 // Insert at the first instruction of the pair.
1551 Instruction *InsertPt = nullptr;
1552 for (Instruction &Iter : *Cmp->getParent()) {
1553 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1554 // the overflow intrinsic are defined.
1555 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1556 InsertPt = &Iter;
1557 break;
1558 }
1559 }
1560 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
1561
1562 IRBuilder<> Builder(InsertPt);
1563 Value *MathOV = Builder.CreateBinaryIntrinsic(ID: IID, LHS: Arg0, RHS: Arg1);
1564 if (BO->getOpcode() != Instruction::Xor) {
1565 Value *Math = Builder.CreateExtractValue(Agg: MathOV, Idxs: 0, Name: "math");
1566 replaceAllUsesWith(Old: BO, New: Math, FreshBBs, IsHuge: IsHugeFunc);
1567 } else
1568 assert(BO->hasOneUse() &&
1569 "Patterns with XOr should use the BO only in the compare");
1570 Value *OV = Builder.CreateExtractValue(Agg: MathOV, Idxs: 1, Name: "ov");
1571 replaceAllUsesWith(Old: Cmp, New: OV, FreshBBs, IsHuge: IsHugeFunc);
1572 Cmp->eraseFromParent();
1573 BO->eraseFromParent();
1574 return true;
1575}
1576
1577/// Match special-case patterns that check for unsigned add overflow.
1578static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
1579 BinaryOperator *&Add) {
1580 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1581 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1582 Value *A = Cmp->getOperand(i_nocapture: 0), *B = Cmp->getOperand(i_nocapture: 1);
1583
1584 // We are not expecting non-canonical/degenerate code. Just bail out.
1585 if (isa<Constant>(Val: A))
1586 return false;
1587
1588 ICmpInst::Predicate Pred = Cmp->getPredicate();
1589 if (Pred == ICmpInst::ICMP_EQ && match(V: B, P: m_AllOnes()))
1590 B = ConstantInt::get(Ty: B->getType(), V: 1);
1591 else if (Pred == ICmpInst::ICMP_NE && match(V: B, P: m_ZeroInt()))
1592 B = Constant::getAllOnesValue(Ty: B->getType());
1593 else
1594 return false;
1595
1596 // Check the users of the variable operand of the compare looking for an add
1597 // with the adjusted constant.
1598 for (User *U : A->users()) {
1599 if (match(V: U, P: m_Add(L: m_Specific(V: A), R: m_Specific(V: B)))) {
1600 Add = cast<BinaryOperator>(Val: U);
1601 return true;
1602 }
1603 }
1604 return false;
1605}
1606
1607/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1608/// intrinsic. Return true if any changes were made.
1609bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1610 ModifyDT &ModifiedDT) {
1611 bool EdgeCase = false;
1612 Value *A, *B;
1613 BinaryOperator *Add;
1614 if (!match(V: Cmp, P: m_UAddWithOverflow(L: m_Value(V&: A), R: m_Value(V&: B), S: m_BinOp(I&: Add)))) {
1615 if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
1616 return false;
1617 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1618 A = Add->getOperand(i_nocapture: 0);
1619 B = Add->getOperand(i_nocapture: 1);
1620 EdgeCase = true;
1621 }
1622
1623 if (!TLI->shouldFormOverflowOp(Opcode: ISD::UADDO,
1624 VT: TLI->getValueType(DL: *DL, Ty: Add->getType()),
1625 MathUsed: Add->hasNUsesOrMore(N: EdgeCase ? 1 : 2)))
1626 return false;
1627
1628 // We don't want to move around uses of condition values this late, so we
1629 // check if it is legal to create the call to the intrinsic in the basic
1630 // block containing the icmp.
1631 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1632 return false;
1633
1634 if (!replaceMathCmpWithIntrinsic(BO: Add, Arg0: A, Arg1: B, Cmp,
1635 IID: Intrinsic::uadd_with_overflow))
1636 return false;
1637
1638 // Reset callers - do not crash by iterating over a dead instruction.
1639 ModifiedDT = ModifyDT::ModifyInstDT;
1640 return true;
1641}
1642
1643bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1644 ModifyDT &ModifiedDT) {
1645 // We are not expecting non-canonical/degenerate code. Just bail out.
1646 Value *A = Cmp->getOperand(i_nocapture: 0), *B = Cmp->getOperand(i_nocapture: 1);
1647 if (isa<Constant>(Val: A) && isa<Constant>(Val: B))
1648 return false;
1649
1650 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1651 ICmpInst::Predicate Pred = Cmp->getPredicate();
1652 if (Pred == ICmpInst::ICMP_UGT) {
1653 std::swap(a&: A, b&: B);
1654 Pred = ICmpInst::ICMP_ULT;
1655 }
1656 // Convert special-case: (A == 0) is the same as (A u< 1).
1657 if (Pred == ICmpInst::ICMP_EQ && match(V: B, P: m_ZeroInt())) {
1658 B = ConstantInt::get(Ty: B->getType(), V: 1);
1659 Pred = ICmpInst::ICMP_ULT;
1660 }
1661 // Convert special-case: (A != 0) is the same as (0 u< A).
1662 if (Pred == ICmpInst::ICMP_NE && match(V: B, P: m_ZeroInt())) {
1663 std::swap(a&: A, b&: B);
1664 Pred = ICmpInst::ICMP_ULT;
1665 }
1666 if (Pred != ICmpInst::ICMP_ULT)
1667 return false;
1668
1669 // Walk the users of a variable operand of a compare looking for a subtract or
1670 // add with that same operand. Also match the 2nd operand of the compare to
1671 // the add/sub, but that may be a negated constant operand of an add.
1672 Value *CmpVariableOperand = isa<Constant>(Val: A) ? B : A;
1673 BinaryOperator *Sub = nullptr;
1674 for (User *U : CmpVariableOperand->users()) {
1675 // A - B, A u< B --> usubo(A, B)
1676 if (match(V: U, P: m_Sub(L: m_Specific(V: A), R: m_Specific(V: B)))) {
1677 Sub = cast<BinaryOperator>(Val: U);
1678 break;
1679 }
1680
1681 // A + (-C), A u< C (canonicalized form of (sub A, C))
1682 const APInt *CmpC, *AddC;
1683 if (match(V: U, P: m_Add(L: m_Specific(V: A), R: m_APInt(Res&: AddC))) &&
1684 match(V: B, P: m_APInt(Res&: CmpC)) && *AddC == -(*CmpC)) {
1685 Sub = cast<BinaryOperator>(Val: U);
1686 break;
1687 }
1688 }
1689 if (!Sub)
1690 return false;
1691
1692 if (!TLI->shouldFormOverflowOp(Opcode: ISD::USUBO,
1693 VT: TLI->getValueType(DL: *DL, Ty: Sub->getType()),
1694 MathUsed: Sub->hasNUsesOrMore(N: 1)))
1695 return false;
1696
1697 // We don't want to move around uses of condition values this late, so we
1698 // check if it is legal to create the call to the intrinsic in the basic
1699 // block containing the icmp.
1700 if (Sub->getParent() != Cmp->getParent() && !Sub->hasOneUse())
1701 return false;
1702
1703 if (!replaceMathCmpWithIntrinsic(BO: Sub, Arg0: Sub->getOperand(i_nocapture: 0), Arg1: Sub->getOperand(i_nocapture: 1),
1704 Cmp, IID: Intrinsic::usub_with_overflow))
1705 return false;
1706
1707 // Reset callers - do not crash by iterating over a dead instruction.
1708 ModifiedDT = ModifyDT::ModifyInstDT;
1709 return true;
1710}
1711
1712// Decanonicalizes icmp+ctpop power-of-two test if ctpop is slow.
1713// The same transformation exists in DAG combiner, but we repeat it here because
1714// DAG builder can break the pattern by moving icmp into a successor block.
1715bool CodeGenPrepare::unfoldPowerOf2Test(CmpInst *Cmp) {
1716 CmpPredicate Pred;
1717 Value *X;
1718 const APInt *C;
1719
1720 // (icmp (ctpop x), c)
1721 if (!match(V: Cmp, P: m_ICmp(Pred, L: m_Ctpop(Op0: m_Value(V&: X)), R: m_APIntAllowPoison(Res&: C))))
1722 return false;
1723
1724 // We're only interested in "is power of 2 [or zero]" patterns.
1725 bool IsStrictlyPowerOf2Test = ICmpInst::isEquality(P: Pred) && *C == 1;
1726 bool IsPowerOf2OrZeroTest = (Pred == CmpInst::ICMP_ULT && *C == 2) ||
1727 (Pred == CmpInst::ICMP_UGT && *C == 1);
1728 if (!IsStrictlyPowerOf2Test && !IsPowerOf2OrZeroTest)
1729 return false;
1730
1731 // Some targets have better codegen for `ctpop(x) u</u>= 2/1`than for
1732 // `ctpop(x) ==/!= 1`. If ctpop is fast, only try changing the comparison,
1733 // and otherwise expand ctpop into a few simple instructions.
1734 Type *OpTy = X->getType();
1735 if (TLI->isCtpopFast(VT: TLI->getValueType(DL: *DL, Ty: OpTy))) {
1736 // Look for `ctpop(x) ==/!= 1`, where `ctpop(x)` is known to be non-zero.
1737 if (!IsStrictlyPowerOf2Test || !isKnownNonZero(V: Cmp->getOperand(i_nocapture: 0), Q: *DL))
1738 return false;
1739
1740 // ctpop(x) == 1 -> ctpop(x) u< 2
1741 // ctpop(x) != 1 -> ctpop(x) u> 1
1742 if (Pred == ICmpInst::ICMP_EQ) {
1743 Cmp->setOperand(i_nocapture: 1, Val_nocapture: ConstantInt::get(Ty: OpTy, V: 2));
1744 Cmp->setPredicate(ICmpInst::ICMP_ULT);
1745 } else {
1746 Cmp->setPredicate(ICmpInst::ICMP_UGT);
1747 }
1748 return true;
1749 }
1750
1751 Value *NewCmp;
1752 if (IsPowerOf2OrZeroTest ||
1753 (IsStrictlyPowerOf2Test && isKnownNonZero(V: Cmp->getOperand(i_nocapture: 0), Q: *DL))) {
1754 // ctpop(x) u< 2 -> (x & (x - 1)) == 0
1755 // ctpop(x) u> 1 -> (x & (x - 1)) != 0
1756 IRBuilder<> Builder(Cmp);
1757 Value *Sub = Builder.CreateAdd(LHS: X, RHS: Constant::getAllOnesValue(Ty: OpTy));
1758 Value *And = Builder.CreateAnd(LHS: X, RHS: Sub);
1759 CmpInst::Predicate NewPred =
1760 (Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_EQ)
1761 ? CmpInst::ICMP_EQ
1762 : CmpInst::ICMP_NE;
1763 NewCmp = Builder.CreateICmp(P: NewPred, LHS: And, RHS: ConstantInt::getNullValue(Ty: OpTy));
1764 } else {
1765 // ctpop(x) == 1 -> (x ^ (x - 1)) u> (x - 1)
1766 // ctpop(x) != 1 -> (x ^ (x - 1)) u<= (x - 1)
1767 IRBuilder<> Builder(Cmp);
1768 Value *Sub = Builder.CreateAdd(LHS: X, RHS: Constant::getAllOnesValue(Ty: OpTy));
1769 Value *Xor = Builder.CreateXor(LHS: X, RHS: Sub);
1770 CmpInst::Predicate NewPred =
1771 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
1772 NewCmp = Builder.CreateICmp(P: NewPred, LHS: Xor, RHS: Sub);
1773 }
1774
1775 Cmp->replaceAllUsesWith(V: NewCmp);
1776 RecursivelyDeleteTriviallyDeadInstructions(V: Cmp);
1777 return true;
1778}
1779
1780/// Sink the given CmpInst into user blocks to reduce the number of virtual
1781/// registers that must be created and coalesced. This is a clear win except on
1782/// targets with multiple condition code registers (PowerPC), where it might
1783/// lose; some adjustment may be wanted there.
1784///
1785/// Return true if any changes are made.
1786static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI,
1787 const DataLayout &DL) {
1788 if (TLI.hasMultipleConditionRegisters(VT: EVT::getEVT(Ty: Cmp->getType())))
1789 return false;
1790
1791 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1792 if (TLI.useSoftFloat() && isa<FCmpInst>(Val: Cmp))
1793 return false;
1794
1795 bool UsedInPhiOrCurrentBlock = any_of(Range: Cmp->users(), P: [Cmp](User *U) {
1796 return isa<PHINode>(Val: U) ||
1797 cast<Instruction>(Val: U)->getParent() == Cmp->getParent();
1798 });
1799
1800 // Avoid sinking larger than legal integer comparisons unless its ONLY used in
1801 // another BB.
1802 if (UsedInPhiOrCurrentBlock && Cmp->getOperand(i_nocapture: 0)->getType()->isIntegerTy() &&
1803 Cmp->getOperand(i_nocapture: 0)->getType()->getScalarSizeInBits() >
1804 DL.getLargestLegalIntTypeSizeInBits())
1805 return false;
1806
1807 // Only insert a cmp in each block once.
1808 DenseMap<BasicBlock *, CmpInst *> InsertedCmps;
1809
1810 bool MadeChange = false;
1811 for (Instruction::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1812 UI != E;) {
1813 Use &TheUse = UI.getUse();
1814 Instruction *User = cast<Instruction>(Val: *UI);
1815
1816 // Preincrement use iterator so we don't invalidate it.
1817 ++UI;
1818
1819 // Don't bother for PHI nodes.
1820 if (isa<PHINode>(Val: User))
1821 continue;
1822
1823 // Figure out which BB this cmp is used in.
1824 BasicBlock *UserBB = User->getParent();
1825 BasicBlock *DefBB = Cmp->getParent();
1826
1827 // If this user is in the same block as the cmp, don't change the cmp.
1828 if (UserBB == DefBB)
1829 continue;
1830
1831 // If we have already inserted a cmp into this block, use it.
1832 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1833
1834 if (!InsertedCmp) {
1835 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1836 assert(InsertPt != UserBB->end());
1837 InsertedCmp = CmpInst::Create(Op: Cmp->getOpcode(), Pred: Cmp->getPredicate(),
1838 S1: Cmp->getOperand(i_nocapture: 0), S2: Cmp->getOperand(i_nocapture: 1), Name: "");
1839 InsertedCmp->insertBefore(BB&: *UserBB, InsertPos: InsertPt);
1840 // Propagate the debug info.
1841 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1842 }
1843
1844 // Replace a use of the cmp with a use of the new cmp.
1845 TheUse = InsertedCmp;
1846 MadeChange = true;
1847 ++NumCmpUses;
1848 }
1849
1850 // If we removed all uses, nuke the cmp.
1851 if (Cmp->use_empty()) {
1852 Cmp->eraseFromParent();
1853 MadeChange = true;
1854 }
1855
1856 return MadeChange;
1857}
1858
1859/// For pattern like:
1860///
1861/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1862/// ...
1863/// DomBB:
1864/// ...
1865/// br DomCond, TrueBB, CmpBB
1866/// CmpBB: (with DomBB being the single predecessor)
1867/// ...
1868/// Cmp = icmp eq CmpOp0, CmpOp1
1869/// ...
1870///
1871/// It would use two comparison on targets that lowering of icmp sgt/slt is
1872/// different from lowering of icmp eq (PowerPC). This function try to convert
1873/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1874/// After that, DomCond and Cmp can use the same comparison so reduce one
1875/// comparison.
1876///
1877/// Return true if any changes are made.
1878static bool foldICmpWithDominatingICmp(CmpInst *Cmp, const TargetLowering &TLI,
1879 bool EnableICmpEqToICmpSt) {
1880 if (!EnableICmpEqToICmpSt && TLI.isEqualityCmpFoldedWithSignedCmp())
1881 return false;
1882
1883 ICmpInst::Predicate Pred = Cmp->getPredicate();
1884 if (Pred != ICmpInst::ICMP_EQ)
1885 return false;
1886
1887 // If icmp eq has users other than CondBrInst and SelectInst, converting it to
1888 // icmp slt/sgt would introduce more redundant LLVM IR.
1889 for (User *U : Cmp->users()) {
1890 if (isa<CondBrInst>(Val: U))
1891 continue;
1892 if (isa<SelectInst>(Val: U) && cast<SelectInst>(Val: U)->getCondition() == Cmp)
1893 continue;
1894 return false;
1895 }
1896
1897 // This is a cheap/incomplete check for dominance - just match a single
1898 // predecessor with a conditional branch.
1899 BasicBlock *CmpBB = Cmp->getParent();
1900 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1901 if (!DomBB)
1902 return false;
1903
1904 // We want to ensure that the only way control gets to the comparison of
1905 // interest is that a less/greater than comparison on the same operands is
1906 // false.
1907 Value *DomCond;
1908 BasicBlock *TrueBB, *FalseBB;
1909 if (!match(V: DomBB->getTerminator(), P: m_Br(C: m_Value(V&: DomCond), T&: TrueBB, F&: FalseBB)))
1910 return false;
1911 if (CmpBB != FalseBB)
1912 return false;
1913
1914 Value *CmpOp0 = Cmp->getOperand(i_nocapture: 0), *CmpOp1 = Cmp->getOperand(i_nocapture: 1);
1915 CmpPredicate DomPred;
1916 if (!match(V: DomCond, P: m_ICmp(Pred&: DomPred, L: m_Specific(V: CmpOp0), R: m_Specific(V: CmpOp1))))
1917 return false;
1918 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
1919 return false;
1920
1921 // Convert the equality comparison to the opposite of the dominating
1922 // comparison and swap the direction for all branch/select users.
1923 // We have conceptually converted:
1924 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
1925 // to
1926 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
1927 // And similarly for branches.
1928 for (User *U : Cmp->users()) {
1929 if (auto *BI = dyn_cast<CondBrInst>(Val: U)) {
1930 BI->swapSuccessors();
1931 continue;
1932 }
1933 if (auto *SI = dyn_cast<SelectInst>(Val: U)) {
1934 // Swap operands
1935 SI->swapValues();
1936 SI->swapProfMetadata();
1937 continue;
1938 }
1939 llvm_unreachable("Must be a branch or a select");
1940 }
1941 Cmp->setPredicate(CmpInst::getSwappedPredicate(pred: DomPred));
1942 return true;
1943}
1944
1945/// Many architectures use the same instruction for both subtract and cmp. Try
1946/// to swap cmp operands to match subtract operations to allow for CSE.
1947static bool swapICmpOperandsToExposeCSEOpportunities(CmpInst *Cmp) {
1948 Value *Op0 = Cmp->getOperand(i_nocapture: 0);
1949 Value *Op1 = Cmp->getOperand(i_nocapture: 1);
1950 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Val: Op0) ||
1951 isa<Constant>(Val: Op1) || Op0 == Op1)
1952 return false;
1953
1954 // If a subtract already has the same operands as a compare, swapping would be
1955 // bad. If a subtract has the same operands as a compare but in reverse order,
1956 // then swapping is good.
1957 int GoodToSwap = 0;
1958 unsigned NumInspected = 0;
1959 for (const User *U : Op0->users()) {
1960 // Avoid walking many users.
1961 if (++NumInspected > 128)
1962 return false;
1963 if (match(V: U, P: m_Sub(L: m_Specific(V: Op1), R: m_Specific(V: Op0))))
1964 GoodToSwap++;
1965 else if (match(V: U, P: m_Sub(L: m_Specific(V: Op0), R: m_Specific(V: Op1))))
1966 GoodToSwap--;
1967 }
1968
1969 if (GoodToSwap > 0) {
1970 Cmp->swapOperands();
1971 return true;
1972 }
1973 return false;
1974}
1975
1976static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI,
1977 const DataLayout &DL) {
1978 FCmpInst *FCmp = dyn_cast<FCmpInst>(Val: Cmp);
1979 if (!FCmp)
1980 return false;
1981
1982 // Don't fold if the target offers free fabs and the predicate is legal.
1983 EVT VT = TLI.getValueType(DL, Ty: Cmp->getOperand(i_nocapture: 0)->getType());
1984 if (TLI.isFAbsFree(VT) &&
1985 TLI.isCondCodeLegal(CC: getFCmpCondCode(Pred: FCmp->getPredicate()),
1986 VT: VT.getSimpleVT()))
1987 return false;
1988
1989 // Reverse the canonicalization if it is a FP class test
1990 auto ShouldReverseTransform = [](FPClassTest ClassTest) {
1991 return ClassTest == fcInf || ClassTest == (fcInf | fcNan);
1992 };
1993 auto [ClassVal, ClassTest] =
1994 fcmpToClassTest(Pred: FCmp->getPredicate(), F: *FCmp->getParent()->getParent(),
1995 LHS: FCmp->getOperand(i_nocapture: 0), RHS: FCmp->getOperand(i_nocapture: 1));
1996 if (!ClassVal)
1997 return false;
1998
1999 if (!ShouldReverseTransform(ClassTest) && !ShouldReverseTransform(~ClassTest))
2000 return false;
2001
2002 IRBuilder<> Builder(Cmp);
2003 Value *IsFPClass = Builder.createIsFPClass(FPNum: ClassVal, Test: ClassTest);
2004 Cmp->replaceAllUsesWith(V: IsFPClass);
2005 RecursivelyDeleteTriviallyDeadInstructions(V: Cmp);
2006 return true;
2007}
2008
2009static bool isRemOfLoopIncrementWithLoopInvariant(
2010 Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut,
2011 Value *&AddOffsetOut, PHINode *&LoopIncrPNOut) {
2012 Value *Incr, *RemAmt;
2013 // NB: If RemAmt is a power of 2 it *should* have been transformed by now.
2014 if (!match(V: Rem, P: m_URem(L: m_Value(V&: Incr), R: m_Value(V&: RemAmt))))
2015 return false;
2016
2017 Value *AddInst, *AddOffset;
2018 // Find out loop increment PHI.
2019 PHINode *PN = dyn_cast<PHINode>(Val: Incr);
2020 if (PN != nullptr) {
2021 AddInst = nullptr;
2022 AddOffset = nullptr;
2023 } else {
2024 // Search through a NUW add on top of the loop increment.
2025 if (!match(V: Incr, P: m_c_NUWAdd(L: m_Phi(PN), R: m_Value(V&: AddOffset))))
2026 return false;
2027 AddInst = Incr;
2028 }
2029
2030 if (!PN)
2031 return false;
2032
2033 // This isn't strictly necessary, what we really need is one increment and any
2034 // amount of initial values all being the same.
2035 if (PN->getNumIncomingValues() != 2)
2036 return false;
2037
2038 // Only trivially analyzable loops.
2039 Loop *L = LI->getLoopFor(BB: PN->getParent());
2040 if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
2041 return false;
2042
2043 // Req that the remainder is in the loop
2044 if (!L->contains(Inst: Rem))
2045 return false;
2046
2047 // Only works if the remainder amount is a loop invaraint
2048 if (!L->isLoopInvariant(V: RemAmt))
2049 return false;
2050
2051 // Only works if the AddOffset is a loop invaraint
2052 if (AddOffset && !L->isLoopInvariant(V: AddOffset))
2053 return false;
2054
2055 // Is the PHI a loop increment?
2056 auto LoopIncrInfo = getIVIncrement(PN, LI);
2057 if (!LoopIncrInfo)
2058 return false;
2059
2060 // We need remainder_amount % increment_amount to be zero. Increment of one
2061 // satisfies that without any special logic and is overwhelmingly the common
2062 // case.
2063 if (!match(V: LoopIncrInfo->second, P: m_One()))
2064 return false;
2065
2066 // Need the increment to not overflow.
2067 if (!match(V: LoopIncrInfo->first, P: m_c_NUWAdd(L: m_Specific(V: PN), R: m_Value())))
2068 return false;
2069
2070 // Set output variables.
2071 RemAmtOut = RemAmt;
2072 LoopIncrPNOut = PN;
2073 AddInstOut = AddInst;
2074 AddOffsetOut = AddOffset;
2075
2076 return true;
2077}
2078
2079// Try to transform:
2080//
2081// for(i = Start; i < End; ++i)
2082// Rem = (i nuw+ IncrLoopInvariant) u% RemAmtLoopInvariant;
2083//
2084// ->
2085//
2086// Rem = (Start nuw+ IncrLoopInvariant) % RemAmtLoopInvariant;
2087// for(i = Start; i < End; ++i, ++rem)
2088// Rem = rem == RemAmtLoopInvariant ? 0 : Rem;
2089static bool foldURemOfLoopIncrement(Instruction *Rem, const DataLayout *DL,
2090 const LoopInfo *LI,
2091 SmallPtrSet<BasicBlock *, 32> &FreshBBs,
2092 bool IsHuge) {
2093 Value *AddOffset, *RemAmt, *AddInst;
2094 PHINode *LoopIncrPN;
2095 if (!isRemOfLoopIncrementWithLoopInvariant(Rem, LI, RemAmtOut&: RemAmt, AddInstOut&: AddInst,
2096 AddOffsetOut&: AddOffset, LoopIncrPNOut&: LoopIncrPN))
2097 return false;
2098
2099 // Only non-constant remainder as the extra IV is probably not profitable
2100 // in that case.
2101 //
2102 // Potential TODO(1): `urem` of a const ends up as `mul` + `shift` + `add`. If
2103 // we can rule out register pressure and ensure this `urem` is executed each
2104 // iteration, its probably profitable to handle the const case as well.
2105 //
2106 // Potential TODO(2): Should we have a check for how "nested" this remainder
2107 // operation is? The new code runs every iteration so if the remainder is
2108 // guarded behind unlikely conditions this might not be worth it.
2109 if (match(V: RemAmt, P: m_ImmConstant()))
2110 return false;
2111
2112 Loop *L = LI->getLoopFor(BB: LoopIncrPN->getParent());
2113 Value *Start = LoopIncrPN->getIncomingValueForBlock(BB: L->getLoopPreheader());
2114 // If we have add create initial value for remainder.
2115 // The logic here is:
2116 // (urem (add nuw Start, IncrLoopInvariant), RemAmtLoopInvariant
2117 //
2118 // Only proceed if the expression simplifies (otherwise we can't fully
2119 // optimize out the urem).
2120 if (AddInst) {
2121 assert(AddOffset && "We found an add but missing values");
2122 // Without dom-condition/assumption cache we aren't likely to get much out
2123 // of a context instruction.
2124 Start = simplifyAddInst(LHS: Start, RHS: AddOffset,
2125 IsNSW: match(V: AddInst, P: m_NSWAdd(L: m_Value(), R: m_Value())),
2126 /*IsNUW=*/true, Q: *DL);
2127 if (!Start)
2128 return false;
2129 }
2130
2131 // If we can't fully optimize out the `rem`, skip this transform.
2132 Start = simplifyURemInst(LHS: Start, RHS: RemAmt, Q: *DL);
2133 if (!Start)
2134 return false;
2135
2136 // Create new remainder with induction variable.
2137 Type *Ty = Rem->getType();
2138 IRBuilder<> Builder(LoopIncrPN);
2139 PHINode *NewRem = Builder.CreatePHI(Ty, NumReservedValues: 2);
2140
2141 Builder.SetInsertPoint(cast<Instruction>(
2142 Val: LoopIncrPN->getIncomingValueForBlock(BB: L->getLoopLatch())));
2143 // `(add (urem x, y), 1)` is always nuw.
2144 Value *RemAdd = Builder.CreateNUWAdd(LHS: NewRem, RHS: ConstantInt::get(Ty, V: 1));
2145 Value *RemCmp = Builder.CreateICmp(P: ICmpInst::ICMP_EQ, LHS: RemAdd, RHS: RemAmt);
2146 Value *RemSel =
2147 Builder.CreateSelect(C: RemCmp, True: Constant::getNullValue(Ty), False: RemAdd);
2148
2149 NewRem->addIncoming(V: Start, BB: L->getLoopPreheader());
2150 NewRem->addIncoming(V: RemSel, BB: L->getLoopLatch());
2151
2152 // Insert all touched BBs.
2153 FreshBBs.insert(Ptr: LoopIncrPN->getParent());
2154 FreshBBs.insert(Ptr: L->getLoopLatch());
2155 FreshBBs.insert(Ptr: Rem->getParent());
2156 if (AddInst)
2157 FreshBBs.insert(Ptr: cast<Instruction>(Val: AddInst)->getParent());
2158 replaceAllUsesWith(Old: Rem, New: NewRem, FreshBBs, IsHuge);
2159 Rem->eraseFromParent();
2160 if (AddInst && AddInst->use_empty())
2161 cast<Instruction>(Val: AddInst)->eraseFromParent();
2162 return true;
2163}
2164
2165bool CodeGenPrepare::optimizeURem(Instruction *Rem) {
2166 if (foldURemOfLoopIncrement(Rem, DL, LI, FreshBBs, IsHuge: IsHugeFunc))
2167 return true;
2168 return false;
2169}
2170
2171bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
2172 if (sinkCmpExpression(Cmp, TLI: *TLI, DL: *DL))
2173 return true;
2174
2175 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
2176 return true;
2177
2178 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
2179 return true;
2180
2181 if (unfoldPowerOf2Test(Cmp))
2182 return true;
2183
2184 if (foldICmpWithDominatingICmp(Cmp, TLI: *TLI, EnableICmpEqToICmpSt: Opts.cgp_icmp_eq2icmp_st))
2185 return true;
2186
2187 if (swapICmpOperandsToExposeCSEOpportunities(Cmp))
2188 return true;
2189
2190 if (foldFCmpToFPClassTest(Cmp, TLI: *TLI, DL: *DL))
2191 return true;
2192
2193 return false;
2194}
2195
2196/// Duplicate and sink the given 'and' instruction into user blocks where it is
2197/// used in a compare to allow isel to generate better code for targets where
2198/// this operation can be combined.
2199///
2200/// Return true if any changes are made.
2201static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI,
2202 SetOfInstrs &InsertedInsts) {
2203 // Double-check that we're not trying to optimize an instruction that was
2204 // already optimized by some other part of this pass.
2205 assert(!InsertedInsts.count(AndI) &&
2206 "Attempting to optimize already optimized and instruction");
2207 (void)InsertedInsts;
2208
2209 // Nothing to do for single use in same basic block.
2210 if (AndI->hasOneUse() &&
2211 AndI->getParent() == cast<Instruction>(Val: *AndI->user_begin())->getParent())
2212 return false;
2213
2214 // Try to avoid cases where sinking/duplicating is likely to increase register
2215 // pressure.
2216 if (!isa<ConstantInt>(Val: AndI->getOperand(i: 0)) &&
2217 !isa<ConstantInt>(Val: AndI->getOperand(i: 1)) &&
2218 AndI->getOperand(i: 0)->hasOneUse() && AndI->getOperand(i: 1)->hasOneUse())
2219 return false;
2220
2221 for (auto *U : AndI->users()) {
2222 Instruction *User = cast<Instruction>(Val: U);
2223
2224 // Only sink 'and' feeding icmp with 0.
2225 if (!isa<ICmpInst>(Val: User))
2226 return false;
2227
2228 auto *CmpC = dyn_cast<ConstantInt>(Val: User->getOperand(i: 1));
2229 if (!CmpC || !CmpC->isZero())
2230 return false;
2231 }
2232
2233 if (!TLI.isMaskAndCmp0FoldingBeneficial(AndI: *AndI))
2234 return false;
2235
2236 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
2237 LLVM_DEBUG(AndI->getParent()->dump());
2238
2239 // Push the 'and' into the same block as the icmp 0. There should only be
2240 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
2241 // others, so we don't need to keep track of which BBs we insert into.
2242 for (Instruction::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
2243 UI != E;) {
2244 Use &TheUse = UI.getUse();
2245 Instruction *User = cast<Instruction>(Val: *UI);
2246
2247 // Preincrement use iterator so we don't invalidate it.
2248 ++UI;
2249
2250 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
2251
2252 // Keep the 'and' in the same place if the use is already in the same block.
2253 Instruction *InsertPt =
2254 User->getParent() == AndI->getParent() ? AndI : User;
2255 Instruction *InsertedAnd = BinaryOperator::Create(
2256 Op: Instruction::And, S1: AndI->getOperand(i: 0), S2: AndI->getOperand(i: 1), Name: "",
2257 InsertBefore: InsertPt->getIterator());
2258 // Propagate the debug info.
2259 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
2260
2261 // Replace a use of the 'and' with a use of the new 'and'.
2262 TheUse = InsertedAnd;
2263 ++NumAndUses;
2264 LLVM_DEBUG(User->getParent()->dump());
2265 }
2266
2267 // We removed all uses, nuke the and.
2268 AndI->eraseFromParent();
2269 return true;
2270}
2271
2272/// Check if the candidates could be combined with a shift instruction, which
2273/// includes:
2274/// 1. Truncate instruction
2275/// 2. And instruction and the imm is a mask of the low bits:
2276/// imm & (imm+1) == 0
2277static bool isExtractBitsCandidateUse(Instruction *User) {
2278 if (!isa<TruncInst>(Val: User)) {
2279 if (User->getOpcode() != Instruction::And ||
2280 !isa<ConstantInt>(Val: User->getOperand(i: 1)))
2281 return false;
2282
2283 const APInt &Cimm = cast<ConstantInt>(Val: User->getOperand(i: 1))->getValue();
2284
2285 if ((Cimm & (Cimm + 1)).getBoolValue())
2286 return false;
2287 }
2288 return true;
2289}
2290
2291/// Sink both shift and truncate instruction to the use of truncate's BB.
2292static bool
2293SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
2294 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
2295 const TargetLowering &TLI, const DataLayout &DL) {
2296 BasicBlock *UserBB = User->getParent();
2297 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
2298 auto *TruncI = cast<TruncInst>(Val: User);
2299 bool MadeChange = false;
2300
2301 for (Instruction::user_iterator TruncUI = TruncI->user_begin(),
2302 TruncE = TruncI->user_end();
2303 TruncUI != TruncE;) {
2304
2305 Use &TruncTheUse = TruncUI.getUse();
2306 Instruction *TruncUser = cast<Instruction>(Val: *TruncUI);
2307 // Preincrement use iterator so we don't invalidate it.
2308
2309 ++TruncUI;
2310
2311 int ISDOpcode = TLI.InstructionOpcodeToISD(Opcode: TruncUser->getOpcode());
2312 if (!ISDOpcode)
2313 continue;
2314
2315 // If the use is actually a legal node, there will not be an
2316 // implicit truncate.
2317 // FIXME: always querying the result type is just an
2318 // approximation; some nodes' legality is determined by the
2319 // operand or other means. There's no good way to find out though.
2320 if (TLI.isOperationLegalOrCustom(
2321 Op: ISDOpcode, VT: TLI.getValueType(DL, Ty: TruncUser->getType(), AllowUnknown: true)))
2322 continue;
2323
2324 // Don't bother for PHI nodes.
2325 if (isa<PHINode>(Val: TruncUser))
2326 continue;
2327
2328 BasicBlock *TruncUserBB = TruncUser->getParent();
2329
2330 if (UserBB == TruncUserBB)
2331 continue;
2332
2333 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2334 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2335
2336 if (!InsertedShift && !InsertedTrunc) {
2337 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2338 assert(InsertPt != TruncUserBB->end());
2339 // Sink the shift
2340 if (ShiftI->getOpcode() == Instruction::AShr)
2341 InsertedShift =
2342 BinaryOperator::CreateAShr(V1: ShiftI->getOperand(i_nocapture: 0), V2: CI, Name: "");
2343 else
2344 InsertedShift =
2345 BinaryOperator::CreateLShr(V1: ShiftI->getOperand(i_nocapture: 0), V2: CI, Name: "");
2346 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2347 InsertedShift->insertBefore(BB&: *TruncUserBB, InsertPos: InsertPt);
2348
2349 // Sink the trunc
2350 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2351 TruncInsertPt++;
2352 // It will go ahead of any debug-info.
2353 TruncInsertPt.setHeadBit(true);
2354 assert(TruncInsertPt != TruncUserBB->end());
2355
2356 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), S: InsertedShift,
2357 Ty: TruncI->getType(), Name: "");
2358 InsertedTrunc->insertBefore(BB&: *TruncUserBB, InsertPos: TruncInsertPt);
2359 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2360
2361 MadeChange = true;
2362
2363 TruncTheUse = InsertedTrunc;
2364 }
2365 }
2366 return MadeChange;
2367}
2368
2369/// Sink the shift *right* instruction into user blocks if the uses could
2370/// potentially be combined with this shift instruction and generate BitExtract
2371/// instruction. It will only be applied if the architecture supports BitExtract
2372/// instruction. Here is an example:
2373/// BB1:
2374/// %x.extract.shift = lshr i64 %arg1, 32
2375/// BB2:
2376/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2377/// ==>
2378///
2379/// BB2:
2380/// %x.extract.shift.1 = lshr i64 %arg1, 32
2381/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2382///
2383/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2384/// instruction.
2385/// Return true if any changes are made.
2386static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
2387 const TargetLowering &TLI,
2388 const DataLayout &DL) {
2389 BasicBlock *DefBB = ShiftI->getParent();
2390
2391 /// Only insert instructions in each block once.
2392 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
2393
2394 bool shiftIsLegal = TLI.isTypeLegal(VT: TLI.getValueType(DL, Ty: ShiftI->getType()));
2395
2396 bool MadeChange = false;
2397 for (Instruction::user_iterator UI = ShiftI->user_begin(),
2398 E = ShiftI->user_end();
2399 UI != E;) {
2400 Use &TheUse = UI.getUse();
2401 Instruction *User = cast<Instruction>(Val: *UI);
2402 // Preincrement use iterator so we don't invalidate it.
2403 ++UI;
2404
2405 // Don't bother for PHI nodes.
2406 if (isa<PHINode>(Val: User))
2407 continue;
2408
2409 if (!isExtractBitsCandidateUse(User))
2410 continue;
2411
2412 BasicBlock *UserBB = User->getParent();
2413
2414 if (UserBB == DefBB) {
2415 // If the shift and truncate instruction are in the same BB. The use of
2416 // the truncate(TruncUse) may still introduce another truncate if not
2417 // legal. In this case, we would like to sink both shift and truncate
2418 // instruction to the BB of TruncUse.
2419 // for example:
2420 // BB1:
2421 // i64 shift.result = lshr i64 opnd, imm
2422 // trunc.result = trunc shift.result to i16
2423 //
2424 // BB2:
2425 // ----> We will have an implicit truncate here if the architecture does
2426 // not have i16 compare.
2427 // cmp i16 trunc.result, opnd2
2428 //
2429 if (isa<TruncInst>(Val: User) &&
2430 shiftIsLegal
2431 // If the type of the truncate is legal, no truncate will be
2432 // introduced in other basic blocks.
2433 && (!TLI.isTypeLegal(VT: TLI.getValueType(DL, Ty: User->getType()))))
2434 MadeChange =
2435 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2436
2437 continue;
2438 }
2439 // If we have already inserted a shift into this block, use it.
2440 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2441
2442 if (!InsertedShift) {
2443 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2444 assert(InsertPt != UserBB->end());
2445
2446 if (ShiftI->getOpcode() == Instruction::AShr)
2447 InsertedShift =
2448 BinaryOperator::CreateAShr(V1: ShiftI->getOperand(i_nocapture: 0), V2: CI, Name: "");
2449 else
2450 InsertedShift =
2451 BinaryOperator::CreateLShr(V1: ShiftI->getOperand(i_nocapture: 0), V2: CI, Name: "");
2452 InsertedShift->insertBefore(BB&: *UserBB, InsertPos: InsertPt);
2453 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2454
2455 MadeChange = true;
2456 }
2457
2458 // Replace a use of the shift with a use of the new shift.
2459 TheUse = InsertedShift;
2460 }
2461
2462 // If we removed all uses, or there are none, nuke the shift.
2463 if (ShiftI->use_empty()) {
2464 salvageDebugInfo(I&: *ShiftI);
2465 ShiftI->eraseFromParent();
2466 MadeChange = true;
2467 }
2468
2469 return MadeChange;
2470}
2471
2472/// If counting leading or trailing zeros is an expensive operation and a zero
2473/// input is defined, add a check for zero to avoid calling the intrinsic.
2474///
2475/// We want to transform:
2476/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2477///
2478/// into:
2479/// entry:
2480/// %cmpz = icmp eq i64 %A, 0
2481/// br i1 %cmpz, label %cond.end, label %cond.false
2482/// cond.false:
2483/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2484/// br label %cond.end
2485/// cond.end:
2486/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2487///
2488/// If the transform is performed, return true and set ModifiedDT to true.
2489static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2490 DomTreeUpdater *DTU, LoopInfo *LI,
2491 const TargetLowering *TLI,
2492 const DataLayout *DL, ModifyDT &ModifiedDT,
2493 SmallPtrSet<BasicBlock *, 32> &FreshBBs,
2494 bool IsHugeFunc) {
2495 // If a zero input is undefined, it doesn't make sense to despeculate that.
2496 if (match(V: CountZeros->getOperand(i_nocapture: 1), P: m_One()))
2497 return false;
2498
2499 // If it's cheap to speculate, there's nothing to do.
2500 Type *Ty = CountZeros->getType();
2501 auto IntrinsicID = CountZeros->getIntrinsicID();
2502 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2503 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2504 return false;
2505
2506 // Only handle scalar cases. Anything else requires too much work.
2507 unsigned SizeInBits = Ty->getScalarSizeInBits();
2508 if (Ty->isVectorTy())
2509 return false;
2510
2511 // Bail if the value is never zero.
2512 Use &Op = CountZeros->getOperandUse(i: 0);
2513 if (isKnownNonZero(V: Op, Q: *DL))
2514 return false;
2515
2516 // The intrinsic will be sunk behind a compare against zero and branch.
2517 BasicBlock *StartBlock = CountZeros->getParent();
2518 BasicBlock *CallBlock = SplitBlock(Old: StartBlock, SplitPt: CountZeros, DTU, LI,
2519 /* MSSAU */ nullptr, BBName: "cond.false");
2520 if (IsHugeFunc)
2521 FreshBBs.insert(Ptr: CallBlock);
2522
2523 // Create another block after the count zero intrinsic. A PHI will be added
2524 // in this block to select the result of the intrinsic or the bit-width
2525 // constant if the input to the intrinsic is zero.
2526 BasicBlock::iterator SplitPt = std::next(x: BasicBlock::iterator(CountZeros));
2527 // Any debug-info after CountZeros should not be included.
2528 SplitPt.setHeadBit(true);
2529 BasicBlock *EndBlock = SplitBlock(Old: CallBlock, SplitPt: &*SplitPt, DTU, LI,
2530 /* MSSAU */ nullptr, BBName: "cond.end");
2531 if (IsHugeFunc)
2532 FreshBBs.insert(Ptr: EndBlock);
2533
2534 // Set up a builder to create a compare, conditional branch, and PHI.
2535 IRBuilder<> Builder(StartBlock->getTerminator());
2536 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2537
2538 // Replace the unconditional branch that was created by the first split with
2539 // a compare against zero and a conditional branch.
2540 Value *Zero = Constant::getNullValue(Ty);
2541 // Avoid introducing branch on poison. This also replaces the ctz operand.
2542 if (!isGuaranteedNotToBeUndefOrPoison(V: Op))
2543 Op = Builder.CreateFreeze(V: Op, Name: Op->getName() + ".fr");
2544 Value *Cmp = Builder.CreateICmpEQ(LHS: Op, RHS: Zero, Name: "cmpz");
2545 Builder.CreateCondBr(Cond: Cmp, True: EndBlock, False: CallBlock);
2546 StartBlock->getTerminator()->eraseFromParent();
2547 DTU->applyUpdates(Updates: {{DominatorTree::Insert, StartBlock, EndBlock}});
2548
2549 // Create a PHI in the end block to select either the output of the intrinsic
2550 // or the bit width of the operand.
2551 Builder.SetInsertPoint(EndBlock->begin());
2552 PHINode *PN = Builder.CreatePHI(Ty, NumReservedValues: 2, Name: "ctz");
2553 replaceAllUsesWith(Old: CountZeros, New: PN, FreshBBs, IsHuge: IsHugeFunc);
2554 Value *BitWidth = Builder.getInt(AI: APInt(SizeInBits, SizeInBits));
2555 PN->addIncoming(V: BitWidth, BB: StartBlock);
2556 PN->addIncoming(V: CountZeros, BB: CallBlock);
2557
2558 // We are explicitly handling the zero case, so we can set the intrinsic's
2559 // undefined zero argument to 'true'. This will also prevent reprocessing the
2560 // intrinsic; we only despeculate when a zero input is defined.
2561 CountZeros->setArgOperand(i: 1, v: Builder.getTrue());
2562 ModifiedDT = ModifyDT::ModifyBBDT;
2563 return true;
2564}
2565
2566bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2567 BasicBlock *BB = CI->getParent();
2568
2569 // Sink address computing for memory operands into the block.
2570 if (CI->isInlineAsm() && optimizeInlineAsmInst(CS: CI))
2571 return true;
2572
2573 // Align the pointer arguments to this call if the target thinks it's a good
2574 // idea
2575 unsigned MinSize;
2576 Align PrefAlign;
2577 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2578 for (auto &Arg : CI->args()) {
2579 // We want to align both objects whose address is used directly and
2580 // objects whose address is used in casts and GEPs, though it only makes
2581 // sense for GEPs if the offset is a multiple of the desired alignment and
2582 // if size - offset meets the size threshold.
2583 if (!Arg->getType()->isPointerTy())
2584 continue;
2585 APInt Offset(DL->getIndexSizeInBits(
2586 AS: cast<PointerType>(Val: Arg->getType())->getAddressSpace()),
2587 0);
2588 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(DL: *DL, Offset);
2589 uint64_t Offset2 = Offset.getLimitedValue();
2590 if (!isAligned(Lhs: PrefAlign, SizeInBytes: Offset2))
2591 continue;
2592 AllocaInst *AI;
2593 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign) {
2594 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL: *DL);
2595 if (AllocaSize && AllocaSize->getKnownMinValue() >= MinSize + Offset2)
2596 AI->setAlignment(PrefAlign);
2597 }
2598 // Global variables can only be aligned if they are defined in this
2599 // object (i.e. they are uniquely initialized in this object), and
2600 // over-aligning global variables that have an explicit section is
2601 // forbidden.
2602 GlobalVariable *GV;
2603 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2604 GV->getPointerAlignment(DL: *DL) < PrefAlign &&
2605 GV->getGlobalSize(DL: *DL) >= MinSize + Offset2)
2606 GV->setAlignment(PrefAlign);
2607 }
2608 }
2609 // If this is a memcpy (or similar) then we may be able to improve the
2610 // alignment.
2611 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Val: CI)) {
2612 Align DestAlign = getKnownAlignment(V: MI->getDest(), DL: *DL);
2613 MaybeAlign MIDestAlign = MI->getDestAlign();
2614 if (!MIDestAlign || DestAlign > *MIDestAlign)
2615 MI->setDestAlignment(DestAlign);
2616 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Val: MI)) {
2617 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2618 Align SrcAlign = getKnownAlignment(V: MTI->getSource(), DL: *DL);
2619 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2620 MTI->setSourceAlignment(SrcAlign);
2621 }
2622 }
2623
2624 // If we have a cold call site, try to sink addressing computation into the
2625 // cold block. This interacts with our handling for loads and stores to
2626 // ensure that we can fold all uses of a potential addressing computation
2627 // into their uses. TODO: generalize this to work over profiling data
2628 if (CI->hasFnAttr(Kind: Attribute::Cold) &&
2629 !llvm::shouldOptimizeForSize(BB, PSI, BFI))
2630 for (auto &Arg : CI->args()) {
2631 if (!Arg->getType()->isPointerTy())
2632 continue;
2633 unsigned AS = Arg->getType()->getPointerAddressSpace();
2634 if (optimizeMemoryInst(MemoryInst: CI, Addr: Arg, AccessTy: Arg->getType(), AddrSpace: AS))
2635 return true;
2636 }
2637
2638 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: CI);
2639 if (II) {
2640 switch (II->getIntrinsicID()) {
2641 default:
2642 break;
2643 case Intrinsic::assume:
2644 llvm_unreachable("llvm.assume should have been removed already");
2645 case Intrinsic::allow_runtime_check:
2646 case Intrinsic::allow_ubsan_check:
2647 case Intrinsic::experimental_widenable_condition: {
2648 // Give up on future widening opportunities so that we can fold away dead
2649 // paths and merge blocks before going into block-local instruction
2650 // selection.
2651 if (II->use_empty()) {
2652 II->eraseFromParent();
2653 return true;
2654 }
2655 Constant *RetVal = ConstantInt::getTrue(Context&: II->getContext());
2656 resetIteratorIfInvalidatedWhileCalling(BB, f: [&]() {
2657 replaceAndRecursivelySimplify(I: CI, SimpleV: RetVal, TLI: TLInfo, DT: nullptr);
2658 });
2659 return true;
2660 }
2661 case Intrinsic::objectsize:
2662 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2663 case Intrinsic::is_constant:
2664 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2665 case Intrinsic::aarch64_stlxr:
2666 case Intrinsic::aarch64_stxr: {
2667 ZExtInst *ExtVal = dyn_cast<ZExtInst>(Val: CI->getArgOperand(i: 0));
2668 if (!ExtVal || !ExtVal->hasOneUse() ||
2669 ExtVal->getParent() == CI->getParent())
2670 return false;
2671 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2672 ExtVal->moveBefore(InsertPos: CI->getIterator());
2673 // Mark this instruction as "inserted by CGP", so that other
2674 // optimizations don't touch it.
2675 InsertedInsts.insert(Ptr: ExtVal);
2676 return true;
2677 }
2678
2679 case Intrinsic::launder_invariant_group: {
2680 Value *ArgVal = II->getArgOperand(i: 0);
2681 auto it = LargeOffsetGEPMap.find(Key: II);
2682 if (it != LargeOffsetGEPMap.end()) {
2683 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2684 // Make sure not to have to deal with iterator invalidation
2685 // after possibly adding ArgVal to LargeOffsetGEPMap.
2686 auto GEPs = std::move(it->second);
2687 LargeOffsetGEPMap[ArgVal].append(in_start: GEPs.begin(), in_end: GEPs.end());
2688 LargeOffsetGEPMap.erase(Key: II);
2689 }
2690
2691 replaceAllUsesWith(Old: II, New: ArgVal, FreshBBs, IsHuge: IsHugeFunc);
2692 II->eraseFromParent();
2693 return true;
2694 }
2695 case Intrinsic::cttz:
2696 case Intrinsic::ctlz:
2697 // If counting zeros is expensive, try to avoid it.
2698 return despeculateCountZeros(CountZeros: II, DTU, LI, TLI, DL, ModifiedDT, FreshBBs,
2699 IsHugeFunc);
2700 case Intrinsic::fshl:
2701 case Intrinsic::fshr:
2702 return optimizeFunnelShift(Fsh: II);
2703 case Intrinsic::masked_gather:
2704 return optimizeGatherScatterInst(MemoryInst: II, Ptr: II->getArgOperand(i: 0));
2705 case Intrinsic::masked_scatter:
2706 return optimizeGatherScatterInst(MemoryInst: II, Ptr: II->getArgOperand(i: 1));
2707 case Intrinsic::masked_load:
2708 // Treat v1X masked load as load X type.
2709 if (auto *VT = dyn_cast<FixedVectorType>(Val: II->getType())) {
2710 if (VT->getNumElements() == 1) {
2711 Value *PtrVal = II->getArgOperand(i: 0);
2712 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2713 if (optimizeMemoryInst(MemoryInst: II, Addr: PtrVal, AccessTy: VT->getElementType(), AddrSpace: AS))
2714 return true;
2715 }
2716 }
2717 return false;
2718 case Intrinsic::masked_store:
2719 // Treat v1X masked store as store X type.
2720 if (auto *VT =
2721 dyn_cast<FixedVectorType>(Val: II->getArgOperand(i: 0)->getType())) {
2722 if (VT->getNumElements() == 1) {
2723 Value *PtrVal = II->getArgOperand(i: 1);
2724 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2725 if (optimizeMemoryInst(MemoryInst: II, Addr: PtrVal, AccessTy: VT->getElementType(), AddrSpace: AS))
2726 return true;
2727 }
2728 }
2729 return false;
2730 case Intrinsic::umul_with_overflow:
2731 return optimizeMulWithOverflow(I: II, /*IsSigned=*/false, ModifiedDT);
2732 case Intrinsic::smul_with_overflow:
2733 return optimizeMulWithOverflow(I: II, /*IsSigned=*/true, ModifiedDT);
2734 }
2735
2736 SmallVector<Value *, 2> PtrOps;
2737 Type *AccessTy;
2738 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2739 while (!PtrOps.empty()) {
2740 Value *PtrVal = PtrOps.pop_back_val();
2741 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2742 if (optimizeMemoryInst(MemoryInst: II, Addr: PtrVal, AccessTy, AddrSpace: AS))
2743 return true;
2744 }
2745 }
2746
2747 // From here on out we're working with named functions.
2748 auto *Callee = CI->getCalledFunction();
2749 if (!Callee)
2750 return false;
2751
2752 // Lower all default uses of _chk calls. This is very similar
2753 // to what InstCombineCalls does, but here we are only lowering calls
2754 // to fortified library functions (e.g. __memcpy_chk) that have the default
2755 // "don't know" as the objectsize. Anything else should be left alone.
2756 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2757 IRBuilder<> Builder(CI);
2758 if (Value *V = Simplifier.optimizeCall(CI, B&: Builder)) {
2759 replaceAllUsesWith(Old: CI, New: V, FreshBBs, IsHuge: IsHugeFunc);
2760 CI->eraseFromParent();
2761 return true;
2762 }
2763
2764 // SCCP may have propagated, among other things, C++ static variables across
2765 // calls. If this happens to be the case, we may want to undo it in order to
2766 // avoid redundant pointer computation of the constant, as the function method
2767 // returning the constant needs to be executed anyways.
2768 auto GetUniformReturnValue = [](const Function *F) -> GlobalVariable * {
2769 if (!F->getReturnType()->isPointerTy())
2770 return nullptr;
2771
2772 GlobalVariable *UniformValue = nullptr;
2773 for (auto &BB : *F) {
2774 if (auto *RI = dyn_cast<ReturnInst>(Val: BB.getTerminator())) {
2775 if (auto *V = dyn_cast<GlobalVariable>(Val: RI->getReturnValue())) {
2776 if (!UniformValue)
2777 UniformValue = V;
2778 else if (V != UniformValue)
2779 return nullptr;
2780 } else {
2781 return nullptr;
2782 }
2783 }
2784 }
2785
2786 return UniformValue;
2787 };
2788
2789 if (Callee->hasExactDefinition()) {
2790 if (GlobalVariable *RV = GetUniformReturnValue(Callee)) {
2791 bool MadeChange = false;
2792 for (Use &U : make_early_inc_range(Range: RV->uses())) {
2793 auto *I = dyn_cast<Instruction>(Val: U.getUser());
2794 if (!I || I->getParent() != CI->getParent()) {
2795 // Limit to the same basic block to avoid extending the call-site live
2796 // range, which otherwise could increase register pressure.
2797 continue;
2798 }
2799 if (CI->comesBefore(Other: I)) {
2800 U.set(CI);
2801 MadeChange = true;
2802 }
2803 }
2804
2805 return MadeChange;
2806 }
2807 }
2808
2809 return false;
2810}
2811
2812static bool isIntrinsicOrLFToBeTailCalled(const TargetLibraryInfo *TLInfo,
2813 const CallInst *CI) {
2814 assert(CI && CI->use_empty());
2815
2816 if (const auto *II = dyn_cast<IntrinsicInst>(Val: CI))
2817 switch (II->getIntrinsicID()) {
2818 case Intrinsic::memset:
2819 case Intrinsic::memcpy:
2820 case Intrinsic::memmove:
2821 return true;
2822 default:
2823 return false;
2824 }
2825
2826 Function *Callee = CI->getCalledFunction();
2827 if (Callee && TLInfo)
2828 switch (TLInfo->getLibFunc(FDecl: *Callee)) {
2829 case LibFunc_strcpy:
2830 case LibFunc_strncpy:
2831 case LibFunc_strcat:
2832 case LibFunc_strncat:
2833 return true;
2834 default:
2835 return false;
2836 }
2837
2838 return false;
2839}
2840
2841/// Look for opportunities to duplicate return instructions to the predecessor
2842/// to enable tail call optimizations. The case it is currently looking for is
2843/// the following one. Known intrinsics or library function that may be tail
2844/// called are taken into account as well.
2845/// @code
2846/// bb0:
2847/// %tmp0 = tail call i32 @f0()
2848/// br label %return
2849/// bb1:
2850/// %tmp1 = tail call i32 @f1()
2851/// br label %return
2852/// bb2:
2853/// %tmp2 = tail call i32 @f2()
2854/// br label %return
2855/// return:
2856/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2857/// ret i32 %retval
2858/// @endcode
2859///
2860/// =>
2861///
2862/// @code
2863/// bb0:
2864/// %tmp0 = tail call i32 @f0()
2865/// ret i32 %tmp0
2866/// bb1:
2867/// %tmp1 = tail call i32 @f1()
2868/// ret i32 %tmp1
2869/// bb2:
2870/// %tmp2 = tail call i32 @f2()
2871/// ret i32 %tmp2
2872/// @endcode
2873bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2874 ModifyDT &ModifiedDT) {
2875 if (!BB->getTerminator())
2876 return false;
2877
2878 ReturnInst *RetI = dyn_cast<ReturnInst>(Val: BB->getTerminator());
2879 if (!RetI)
2880 return false;
2881
2882 assert(LI->getLoopFor(BB) == nullptr && "A return block cannot be in a loop");
2883
2884 PHINode *PN = nullptr;
2885 ExtractValueInst *EVI = nullptr;
2886 BitCastInst *BCI = nullptr;
2887 Value *V = RetI->getReturnValue();
2888 if (V) {
2889 BCI = dyn_cast<BitCastInst>(Val: V);
2890 if (BCI)
2891 V = BCI->getOperand(i_nocapture: 0);
2892
2893 EVI = dyn_cast<ExtractValueInst>(Val: V);
2894 if (EVI) {
2895 V = EVI->getOperand(i_nocapture: 0);
2896 if (!llvm::all_of(Range: EVI->indices(), P: equal_to(Arg: 0)))
2897 return false;
2898 }
2899
2900 PN = dyn_cast<PHINode>(Val: V);
2901 }
2902
2903 if (PN && PN->getParent() != BB)
2904 return false;
2905
2906 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
2907 const BitCastInst *BC = dyn_cast<BitCastInst>(Val: Inst);
2908 if (BC && BC->hasOneUse())
2909 Inst = BC->user_back();
2910
2911 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: Inst))
2912 return II->getIntrinsicID() == Intrinsic::lifetime_end;
2913 return false;
2914 };
2915
2916 SmallVector<const IntrinsicInst *, 4> FakeUses;
2917
2918 auto isFakeUse = [&FakeUses](const Instruction *Inst) {
2919 if (auto *II = dyn_cast<IntrinsicInst>(Val: Inst);
2920 II && II->getIntrinsicID() == Intrinsic::fake_use) {
2921 // Record the instruction so it can be preserved when the exit block is
2922 // removed. Do not preserve the fake use that uses the result of the
2923 // PHI instruction.
2924 // Do not copy fake uses that use the result of a PHI node.
2925 // FIXME: If we do want to copy the fake use into the return blocks, we
2926 // have to figure out which of the PHI node operands to use for each
2927 // copy.
2928 if (!isa<PHINode>(Val: II->getOperand(i_nocapture: 0))) {
2929 FakeUses.push_back(Elt: II);
2930 }
2931 return true;
2932 }
2933
2934 return false;
2935 };
2936
2937 // Make sure there are no instructions between the first instruction
2938 // and return.
2939 BasicBlock::const_iterator BI = BB->getFirstNonPHIIt();
2940 // Skip over pseudo-probes and the bitcast.
2941 while (&*BI == BCI || &*BI == EVI || isa<PseudoProbeInst>(Val: BI) ||
2942 isLifetimeEndOrBitCastFor(&*BI) || isFakeUse(&*BI))
2943 BI = std::next(x: BI);
2944 if (&*BI != RetI)
2945 return false;
2946
2947 // Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2948 // call.
2949 auto MayBePermittedAsTailCall = [&](const auto *CI) {
2950 return TLI->mayBeEmittedAsTailCall(CI) &&
2951 attributesPermitTailCall(BB->getParent(), CI, RetI, *TLI);
2952 };
2953
2954 SmallVector<BasicBlock *, 4> TailCallBBs;
2955 // Record the call instructions so we can insert any fake uses
2956 // that need to be preserved before them.
2957 SmallVector<CallInst *, 4> CallInsts;
2958 if (PN) {
2959 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2960 // Look through bitcasts.
2961 Value *IncomingVal = PN->getIncomingValue(i: I)->stripPointerCasts();
2962 CallInst *CI = dyn_cast<CallInst>(Val: IncomingVal);
2963 BasicBlock *PredBB = PN->getIncomingBlock(i: I);
2964 // Make sure the phi value is indeed produced by the tail call.
2965 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
2966 MayBePermittedAsTailCall(CI)) {
2967 TailCallBBs.push_back(Elt: PredBB);
2968 CallInsts.push_back(Elt: CI);
2969 } else {
2970 // Consider the cases in which the phi value is indirectly produced by
2971 // the tail call, for example when encountering memset(), memmove(),
2972 // strcpy(), whose return value may have been optimized out. In such
2973 // cases, the value needs to be the first function argument.
2974 //
2975 // bb0:
2976 // tail call void @llvm.memset.p0.i64(ptr %0, i8 0, i64 %1)
2977 // br label %return
2978 // return:
2979 // %phi = phi ptr [ %0, %bb0 ], [ %2, %entry ]
2980 if (PredBB && PredBB->getSingleSuccessor() == BB)
2981 CI = dyn_cast_or_null<CallInst>(
2982 Val: PredBB->getTerminator()->getPrevNode());
2983
2984 if (CI && CI->use_empty() &&
2985 isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
2986 IncomingVal == CI->getArgOperand(i: 0) &&
2987 MayBePermittedAsTailCall(CI)) {
2988 TailCallBBs.push_back(Elt: PredBB);
2989 CallInsts.push_back(Elt: CI);
2990 }
2991 }
2992 }
2993 } else {
2994 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
2995 for (BasicBlock *Pred : predecessors(BB)) {
2996 if (!VisitedBBs.insert(Ptr: Pred).second)
2997 continue;
2998 if (Instruction *I = Pred->rbegin()->getPrevNode()) {
2999 CallInst *CI = dyn_cast<CallInst>(Val: I);
3000 if (CI && CI->use_empty() && MayBePermittedAsTailCall(CI)) {
3001 // Either we return void or the return value must be the first
3002 // argument of a known intrinsic or library function.
3003 if (!V || isa<UndefValue>(Val: V) ||
3004 (isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3005 V == CI->getArgOperand(i: 0))) {
3006 TailCallBBs.push_back(Elt: Pred);
3007 CallInsts.push_back(Elt: CI);
3008 }
3009 }
3010 }
3011 }
3012 }
3013
3014 bool Changed = false;
3015 for (auto const &TailCallBB : TailCallBBs) {
3016 // Make sure the call instruction is followed by an unconditional branch to
3017 // the return block.
3018 UncondBrInst *BI = dyn_cast<UncondBrInst>(Val: TailCallBB->getTerminator());
3019 if (!BI || BI->getSuccessor() != BB)
3020 continue;
3021
3022 // Duplicate the return into TailCallBB.
3023 (void)FoldReturnIntoUncondBranch(RI: RetI, BB, Pred: TailCallBB, DTU);
3024 assert(!Opts.cgp_verify_bfi_updates ||
3025 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
3026 BFI->setBlockFreq(BB,
3027 Freq: (BFI->getBlockFreq(BB) - BFI->getBlockFreq(BB: TailCallBB)));
3028 ModifiedDT = ModifyDT::ModifyBBDT;
3029 Changed = true;
3030 ++NumRetsDup;
3031 }
3032
3033 // If we eliminated all predecessors of the block, delete the block now.
3034 if (Changed && !BB->hasAddressTaken() && pred_empty(BB)) {
3035 // Copy the fake uses found in the original return block to all blocks
3036 // that contain tail calls.
3037 for (auto *CI : CallInsts) {
3038 for (auto const *FakeUse : FakeUses) {
3039 auto *ClonedInst = FakeUse->clone();
3040 ClonedInst->insertBefore(InsertPos: CI->getIterator());
3041 }
3042 }
3043 DTU->deleteBB(DelBB: BB);
3044 }
3045
3046 return Changed;
3047}
3048
3049//===----------------------------------------------------------------------===//
3050// Memory Optimization
3051//===----------------------------------------------------------------------===//
3052
3053namespace {
3054
3055/// This is an extended version of TargetLowering::AddrMode
3056/// which holds actual Value*'s for register values.
3057struct ExtAddrMode : public TargetLowering::AddrMode {
3058 Value *BaseReg = nullptr;
3059 Value *ScaledReg = nullptr;
3060 Value *OriginalValue = nullptr;
3061 bool InBounds = true;
3062
3063 enum FieldName {
3064 NoField = 0x00,
3065 BaseRegField = 0x01,
3066 BaseGVField = 0x02,
3067 BaseOffsField = 0x04,
3068 ScaledRegField = 0x08,
3069 ScaleField = 0x10,
3070 MultipleFields = 0xff
3071 };
3072
3073 ExtAddrMode() = default;
3074
3075 void print(raw_ostream &OS) const;
3076 void dump() const;
3077
3078 // Replace From in ExtAddrMode with To.
3079 // E.g., SExt insts may be promoted and deleted. We should replace them with
3080 // the promoted values.
3081 void replaceWith(Value *From, Value *To) {
3082 if (ScaledReg == From)
3083 ScaledReg = To;
3084 }
3085
3086 FieldName compare(const ExtAddrMode &other) {
3087 // First check that the types are the same on each field, as differing types
3088 // is something we can't cope with later on.
3089 if (BaseReg && other.BaseReg &&
3090 BaseReg->getType() != other.BaseReg->getType())
3091 return MultipleFields;
3092 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
3093 return MultipleFields;
3094 if (ScaledReg && other.ScaledReg &&
3095 ScaledReg->getType() != other.ScaledReg->getType())
3096 return MultipleFields;
3097
3098 // Conservatively reject 'inbounds' mismatches.
3099 if (InBounds != other.InBounds)
3100 return MultipleFields;
3101
3102 // Check each field to see if it differs.
3103 unsigned Result = NoField;
3104 if (BaseReg != other.BaseReg)
3105 Result |= BaseRegField;
3106 if (BaseGV != other.BaseGV)
3107 Result |= BaseGVField;
3108 if (BaseOffs != other.BaseOffs)
3109 Result |= BaseOffsField;
3110 if (ScaledReg != other.ScaledReg)
3111 Result |= ScaledRegField;
3112 // Don't count 0 as being a different scale, because that actually means
3113 // unscaled (which will already be counted by having no ScaledReg).
3114 if (Scale && other.Scale && Scale != other.Scale)
3115 Result |= ScaleField;
3116
3117 if (llvm::popcount(Value: Result) > 1)
3118 return MultipleFields;
3119 else
3120 return static_cast<FieldName>(Result);
3121 }
3122
3123 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
3124 // with no offset.
3125 bool isTrivial() {
3126 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
3127 // trivial if at most one of these terms is nonzero, except that BaseGV and
3128 // BaseReg both being zero actually means a null pointer value, which we
3129 // consider to be 'non-zero' here.
3130 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
3131 }
3132
3133 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
3134 switch (Field) {
3135 default:
3136 return nullptr;
3137 case BaseRegField:
3138 return BaseReg;
3139 case BaseGVField:
3140 return BaseGV;
3141 case ScaledRegField:
3142 return ScaledReg;
3143 case BaseOffsField:
3144 return ConstantInt::getSigned(Ty: IntPtrTy, V: BaseOffs);
3145 }
3146 }
3147
3148 void SetCombinedField(FieldName Field, Value *V,
3149 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
3150 switch (Field) {
3151 default:
3152 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
3153 break;
3154 case ExtAddrMode::BaseRegField:
3155 BaseReg = V;
3156 break;
3157 case ExtAddrMode::BaseGVField:
3158 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
3159 // in the BaseReg field.
3160 assert(BaseReg == nullptr);
3161 BaseReg = V;
3162 BaseGV = nullptr;
3163 break;
3164 case ExtAddrMode::ScaledRegField:
3165 ScaledReg = V;
3166 // If we have a mix of scaled and unscaled addrmodes then we want scale
3167 // to be the scale and not zero.
3168 if (!Scale)
3169 for (const ExtAddrMode &AM : AddrModes)
3170 if (AM.Scale) {
3171 Scale = AM.Scale;
3172 break;
3173 }
3174 break;
3175 case ExtAddrMode::BaseOffsField:
3176 // The offset is no longer a constant, so it goes in ScaledReg with a
3177 // scale of 1.
3178 assert(ScaledReg == nullptr);
3179 ScaledReg = V;
3180 Scale = 1;
3181 BaseOffs = 0;
3182 break;
3183 }
3184 }
3185};
3186
3187#ifndef NDEBUG
3188static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3189 AM.print(OS);
3190 return OS;
3191}
3192#endif
3193
3194#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3195void ExtAddrMode::print(raw_ostream &OS) const {
3196 bool NeedPlus = false;
3197 OS << "[";
3198 if (InBounds)
3199 OS << "inbounds ";
3200 if (BaseGV) {
3201 OS << "GV:";
3202 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3203 NeedPlus = true;
3204 }
3205
3206 if (BaseOffs) {
3207 OS << (NeedPlus ? " + " : "") << BaseOffs;
3208 NeedPlus = true;
3209 }
3210
3211 if (BaseReg) {
3212 OS << (NeedPlus ? " + " : "") << "Base:";
3213 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3214 NeedPlus = true;
3215 }
3216 if (Scale) {
3217 OS << (NeedPlus ? " + " : "") << Scale << "*";
3218 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3219 }
3220
3221 OS << ']';
3222}
3223
3224LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
3225 print(dbgs());
3226 dbgs() << '\n';
3227}
3228#endif
3229
3230} // end anonymous namespace
3231
3232namespace {
3233
3234/// This class provides transaction based operation on the IR.
3235/// Every change made through this class is recorded in the internal state and
3236/// can be undone (rollback) until commit is called.
3237/// CGP does not check if instructions could be speculatively executed when
3238/// moved. Preserving the original location would pessimize the debugging
3239/// experience, as well as negatively impact the quality of sample PGO.
3240class TypePromotionTransaction {
3241 /// This represents the common interface of the individual transaction.
3242 /// Each class implements the logic for doing one specific modification on
3243 /// the IR via the TypePromotionTransaction.
3244 class TypePromotionAction {
3245 protected:
3246 /// The Instruction modified.
3247 Instruction *Inst;
3248
3249 public:
3250 /// Constructor of the action.
3251 /// The constructor performs the related action on the IR.
3252 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3253
3254 virtual ~TypePromotionAction() = default;
3255
3256 /// Undo the modification done by this action.
3257 /// When this method is called, the IR must be in the same state as it was
3258 /// before this action was applied.
3259 /// \pre Undoing the action works if and only if the IR is in the exact same
3260 /// state as it was directly after this action was applied.
3261 virtual void undo() = 0;
3262
3263 /// Advocate every change made by this action.
3264 /// When the results on the IR of the action are to be kept, it is important
3265 /// to call this function, otherwise hidden information may be kept forever.
3266 virtual void commit() {
3267 // Nothing to be done, this action is not doing anything.
3268 }
3269 };
3270
3271 /// Utility to remember the position of an instruction.
3272 class InsertionHandler {
3273 /// Position of an instruction.
3274 /// Either an instruction:
3275 /// - Is the first in a basic block: BB is used.
3276 /// - Has a previous instruction: PrevInst is used.
3277 struct {
3278 BasicBlock::iterator PrevInst;
3279 BasicBlock *BB;
3280 } Point;
3281 std::optional<DbgRecord::self_iterator> BeforeDbgRecord = std::nullopt;
3282
3283 /// Remember whether or not the instruction had a previous instruction.
3284 bool HasPrevInstruction;
3285
3286 public:
3287 /// Record the position of \p Inst.
3288 InsertionHandler(Instruction *Inst) {
3289 HasPrevInstruction = (Inst != &*(Inst->getParent()->begin()));
3290 BasicBlock *BB = Inst->getParent();
3291
3292 // Record where we would have to re-insert the instruction in the sequence
3293 // of DbgRecords, if we ended up reinserting.
3294 BeforeDbgRecord = Inst->getDbgReinsertionPosition();
3295
3296 if (HasPrevInstruction) {
3297 Point.PrevInst = std::prev(x: Inst->getIterator());
3298 } else {
3299 Point.BB = BB;
3300 }
3301 }
3302
3303 /// Insert \p Inst at the recorded position.
3304 void insert(Instruction *Inst) {
3305 if (HasPrevInstruction) {
3306 if (Inst->getParent())
3307 Inst->removeFromParent();
3308 Inst->insertAfter(InsertPos: Point.PrevInst);
3309 } else {
3310 BasicBlock::iterator Position = Point.BB->getFirstInsertionPt();
3311 if (Inst->getParent())
3312 Inst->moveBefore(BB&: *Point.BB, I: Position);
3313 else
3314 Inst->insertBefore(BB&: *Point.BB, InsertPos: Position);
3315 }
3316
3317 Inst->getParent()->reinsertInstInDbgRecords(I: Inst, Pos: BeforeDbgRecord);
3318 }
3319 };
3320
3321 /// Set the operand of an instruction with a new value.
3322 class OperandSetter : public TypePromotionAction {
3323 /// Original operand of the instruction.
3324 Value *Origin;
3325
3326 /// Index of the modified instruction.
3327 unsigned Idx;
3328
3329 public:
3330 /// Set \p Idx operand of \p Inst with \p NewVal.
3331 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3332 : TypePromotionAction(Inst), Idx(Idx) {
3333 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3334 << "for:" << *Inst << "\n"
3335 << "with:" << *NewVal << "\n");
3336 Origin = Inst->getOperand(i: Idx);
3337 Inst->setOperand(i: Idx, Val: NewVal);
3338 }
3339
3340 /// Restore the original value of the instruction.
3341 void undo() override {
3342 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3343 << "for: " << *Inst << "\n"
3344 << "with: " << *Origin << "\n");
3345 Inst->setOperand(i: Idx, Val: Origin);
3346 }
3347 };
3348
3349 /// Hide the operands of an instruction.
3350 /// Do as if this instruction was not using any of its operands.
3351 class OperandsHider : public TypePromotionAction {
3352 /// The list of original operands.
3353 SmallVector<Value *, 4> OriginalValues;
3354
3355 public:
3356 /// Remove \p Inst from the uses of the operands of \p Inst.
3357 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3358 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3359 unsigned NumOpnds = Inst->getNumOperands();
3360 OriginalValues.reserve(N: NumOpnds);
3361 for (unsigned It = 0; It < NumOpnds; ++It) {
3362 // Save the current operand.
3363 Value *Val = Inst->getOperand(i: It);
3364 OriginalValues.push_back(Elt: Val);
3365 // Set a dummy one.
3366 // We could use OperandSetter here, but that would imply an overhead
3367 // that we are not willing to pay.
3368 Inst->setOperand(i: It, Val: PoisonValue::get(T: Val->getType()));
3369 }
3370 }
3371
3372 /// Restore the original list of uses.
3373 void undo() override {
3374 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3375 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3376 Inst->setOperand(i: It, Val: OriginalValues[It]);
3377 }
3378 };
3379
3380 /// Build a truncate instruction.
3381 class TruncBuilder : public TypePromotionAction {
3382 Value *Val;
3383
3384 public:
3385 /// Build a truncate instruction of \p Opnd producing a \p Ty
3386 /// result.
3387 /// trunc Opnd to Ty.
3388 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3389 IRBuilder<> Builder(Opnd);
3390 Builder.SetCurrentDebugLocation(DebugLoc());
3391 Val = Builder.CreateTrunc(V: Opnd, DestTy: Ty, Name: "promoted");
3392 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3393 }
3394
3395 /// Get the built value.
3396 Value *getBuiltValue() { return Val; }
3397
3398 /// Remove the built instruction.
3399 void undo() override {
3400 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3401 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3402 IVal->eraseFromParent();
3403 }
3404 };
3405
3406 /// Build a sign extension instruction.
3407 class SExtBuilder : public TypePromotionAction {
3408 Value *Val;
3409
3410 public:
3411 /// Build a sign extension instruction of \p Opnd producing a \p Ty
3412 /// result.
3413 /// sext Opnd to Ty.
3414 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3415 : TypePromotionAction(InsertPt) {
3416 IRBuilder<> Builder(InsertPt);
3417 Val = Builder.CreateSExt(V: Opnd, DestTy: Ty, Name: "promoted");
3418 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3419 }
3420
3421 /// Get the built value.
3422 Value *getBuiltValue() { return Val; }
3423
3424 /// Remove the built instruction.
3425 void undo() override {
3426 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3427 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3428 IVal->eraseFromParent();
3429 }
3430 };
3431
3432 /// Build a zero extension instruction.
3433 class ZExtBuilder : public TypePromotionAction {
3434 Value *Val;
3435
3436 public:
3437 /// Build a zero extension instruction of \p Opnd producing a \p Ty
3438 /// result.
3439 /// zext Opnd to Ty.
3440 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3441 : TypePromotionAction(InsertPt) {
3442 IRBuilder<> Builder(InsertPt);
3443 Builder.SetCurrentDebugLocation(DebugLoc());
3444 Val = Builder.CreateZExt(V: Opnd, DestTy: Ty, Name: "promoted");
3445 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3446 }
3447
3448 /// Get the built value.
3449 Value *getBuiltValue() { return Val; }
3450
3451 /// Remove the built instruction.
3452 void undo() override {
3453 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3454 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3455 IVal->eraseFromParent();
3456 }
3457 };
3458
3459 /// Mutate an instruction to another type.
3460 class TypeMutator : public TypePromotionAction {
3461 /// Record the original type.
3462 Type *OrigTy;
3463
3464 public:
3465 /// Mutate the type of \p Inst into \p NewTy.
3466 TypeMutator(Instruction *Inst, Type *NewTy)
3467 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3468 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3469 << "\n");
3470 Inst->mutateType(Ty: NewTy);
3471 }
3472
3473 /// Mutate the instruction back to its original type.
3474 void undo() override {
3475 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3476 << "\n");
3477 Inst->mutateType(Ty: OrigTy);
3478 }
3479 };
3480
3481 /// Replace the uses of an instruction by another instruction.
3482 class UsesReplacer : public TypePromotionAction {
3483 /// Helper structure to keep track of the replaced uses.
3484 struct InstructionAndIdx {
3485 /// The instruction using the instruction.
3486 Instruction *Inst;
3487
3488 /// The index where this instruction is used for Inst.
3489 unsigned Idx;
3490
3491 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3492 : Inst(Inst), Idx(Idx) {}
3493 };
3494
3495 /// Keep track of the original uses (pair Instruction, Index).
3496 SmallVector<InstructionAndIdx, 4> OriginalUses;
3497 /// Keep track of the debug users.
3498 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
3499
3500 /// Keep track of the new value so that we can undo it by replacing
3501 /// instances of the new value with the original value.
3502 Value *New;
3503
3504 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
3505
3506 public:
3507 /// Replace all the use of \p Inst by \p New.
3508 UsesReplacer(Instruction *Inst, Value *New)
3509 : TypePromotionAction(Inst), New(New) {
3510 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3511 << "\n");
3512 // Record the original uses.
3513 for (Use &U : Inst->uses()) {
3514 Instruction *UserI = cast<Instruction>(Val: U.getUser());
3515 OriginalUses.push_back(Elt: InstructionAndIdx(UserI, U.getOperandNo()));
3516 }
3517 // Record the debug uses separately. They are not in the instruction's
3518 // use list, but they are replaced by RAUW.
3519 findDbgValues(V: Inst, DbgVariableRecords);
3520
3521 // Now, we can replace the uses.
3522 Inst->replaceAllUsesWith(V: New);
3523 }
3524
3525 /// Reassign the original uses of Inst to Inst.
3526 void undo() override {
3527 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3528 for (InstructionAndIdx &Use : OriginalUses)
3529 Use.Inst->setOperand(i: Use.Idx, Val: Inst);
3530 // RAUW has replaced all original uses with references to the new value,
3531 // including the debug uses. Since we are undoing the replacements,
3532 // the original debug uses must also be reinstated to maintain the
3533 // correctness and utility of debug value records.
3534 for (DbgVariableRecord *DVR : DbgVariableRecords)
3535 DVR->replaceVariableLocationOp(OldValue: New, NewValue: Inst);
3536 }
3537 };
3538
3539 /// Remove an instruction from the IR.
3540 class InstructionRemover : public TypePromotionAction {
3541 /// Original position of the instruction.
3542 InsertionHandler Inserter;
3543
3544 /// Helper structure to hide all the link to the instruction. In other
3545 /// words, this helps to do as if the instruction was removed.
3546 OperandsHider Hider;
3547
3548 /// Keep track of the uses replaced, if any.
3549 UsesReplacer *Replacer = nullptr;
3550
3551 /// Keep track of instructions removed.
3552 SetOfInstrs &RemovedInsts;
3553
3554 public:
3555 /// Remove all reference of \p Inst and optionally replace all its
3556 /// uses with New.
3557 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3558 /// \pre If !Inst->use_empty(), then New != nullptr
3559 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3560 Value *New = nullptr)
3561 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3562 RemovedInsts(RemovedInsts) {
3563 if (New)
3564 Replacer = new UsesReplacer(Inst, New);
3565 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3566 RemovedInsts.insert(Ptr: Inst);
3567 /// The instructions removed here will be freed after completing
3568 /// optimizeBlock() for all blocks as we need to keep track of the
3569 /// removed instructions during promotion.
3570 Inst->removeFromParent();
3571 }
3572
3573 ~InstructionRemover() override { delete Replacer; }
3574
3575 InstructionRemover &operator=(const InstructionRemover &other) = delete;
3576 InstructionRemover(const InstructionRemover &other) = delete;
3577
3578 /// Resurrect the instruction and reassign it to the proper uses if
3579 /// new value was provided when build this action.
3580 void undo() override {
3581 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3582 Inserter.insert(Inst);
3583 if (Replacer)
3584 Replacer->undo();
3585 Hider.undo();
3586 RemovedInsts.erase(Ptr: Inst);
3587 }
3588 };
3589
3590public:
3591 /// Restoration point.
3592 /// The restoration point is a pointer to an action instead of an iterator
3593 /// because the iterator may be invalidated but not the pointer.
3594 using ConstRestorationPt = const TypePromotionAction *;
3595
3596 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3597 : RemovedInsts(RemovedInsts) {}
3598
3599 /// Advocate every changes made in that transaction. Return true if any change
3600 /// happen.
3601 bool commit();
3602
3603 /// Undo all the changes made after the given point.
3604 void rollback(ConstRestorationPt Point);
3605
3606 /// Get the current restoration point.
3607 ConstRestorationPt getRestorationPoint() const;
3608
3609 /// \name API for IR modification with state keeping to support rollback.
3610 /// @{
3611 /// Same as Instruction::setOperand.
3612 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3613
3614 /// Same as Instruction::eraseFromParent.
3615 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3616
3617 /// Same as Value::replaceAllUsesWith.
3618 void replaceAllUsesWith(Instruction *Inst, Value *New);
3619
3620 /// Same as Value::mutateType.
3621 void mutateType(Instruction *Inst, Type *NewTy);
3622
3623 /// Same as IRBuilder::createTrunc.
3624 Value *createTrunc(Instruction *Opnd, Type *Ty);
3625
3626 /// Same as IRBuilder::createSExt.
3627 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3628
3629 /// Same as IRBuilder::createZExt.
3630 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3631
3632private:
3633 /// The ordered list of actions made so far.
3634 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3635
3636 using CommitPt =
3637 SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
3638
3639 SetOfInstrs &RemovedInsts;
3640};
3641
3642} // end anonymous namespace
3643
3644void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3645 Value *NewVal) {
3646 Actions.push_back(Elt: std::make_unique<TypePromotionTransaction::OperandSetter>(
3647 args&: Inst, args&: Idx, args&: NewVal));
3648}
3649
3650void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3651 Value *NewVal) {
3652 Actions.push_back(
3653 Elt: std::make_unique<TypePromotionTransaction::InstructionRemover>(
3654 args&: Inst, args&: RemovedInsts, args&: NewVal));
3655}
3656
3657void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3658 Value *New) {
3659 Actions.push_back(
3660 Elt: std::make_unique<TypePromotionTransaction::UsesReplacer>(args&: Inst, args&: New));
3661}
3662
3663void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3664 Actions.push_back(
3665 Elt: std::make_unique<TypePromotionTransaction::TypeMutator>(args&: Inst, args&: NewTy));
3666}
3667
3668Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3669 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3670 Value *Val = Ptr->getBuiltValue();
3671 Actions.push_back(Elt: std::move(Ptr));
3672 return Val;
3673}
3674
3675Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3676 Type *Ty) {
3677 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3678 Value *Val = Ptr->getBuiltValue();
3679 Actions.push_back(Elt: std::move(Ptr));
3680 return Val;
3681}
3682
3683Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3684 Type *Ty) {
3685 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3686 Value *Val = Ptr->getBuiltValue();
3687 Actions.push_back(Elt: std::move(Ptr));
3688 return Val;
3689}
3690
3691TypePromotionTransaction::ConstRestorationPt
3692TypePromotionTransaction::getRestorationPoint() const {
3693 return !Actions.empty() ? Actions.back().get() : nullptr;
3694}
3695
3696bool TypePromotionTransaction::commit() {
3697 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3698 Action->commit();
3699 bool Modified = !Actions.empty();
3700 Actions.clear();
3701 return Modified;
3702}
3703
3704void TypePromotionTransaction::rollback(
3705 TypePromotionTransaction::ConstRestorationPt Point) {
3706 while (!Actions.empty() && Point != Actions.back().get()) {
3707 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3708 Curr->undo();
3709 }
3710}
3711
3712namespace {
3713
3714/// A helper class for matching addressing modes.
3715///
3716/// This encapsulates the logic for matching the target-legal addressing modes.
3717class AddressingModeMatcher {
3718 SmallVectorImpl<Instruction *> &AddrModeInsts;
3719 const TargetLowering &TLI;
3720 const TargetRegisterInfo &TRI;
3721 const DataLayout &DL;
3722 const LoopInfo &LI;
3723 const std::function<const DominatorTree &()> getDTFn;
3724
3725 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3726 /// the memory instruction that we're computing this address for.
3727 Type *AccessTy;
3728 unsigned AddrSpace;
3729 Instruction *MemoryInst;
3730
3731 /// This is the addressing mode that we're building up. This is
3732 /// part of the return value of this addressing mode matching stuff.
3733 ExtAddrMode &AddrMode;
3734
3735 /// The instructions inserted by other CodeGenPrepare optimizations.
3736 const SetOfInstrs &InsertedInsts;
3737
3738 /// A map from the instructions to their type before promotion.
3739 InstrToOrigTy &PromotedInsts;
3740
3741 /// The ongoing transaction where every action should be registered.
3742 TypePromotionTransaction &TPT;
3743
3744 // A GEP which has too large offset to be folded into the addressing mode.
3745 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3746
3747 /// This is set to true when we should not do profitability checks.
3748 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3749 bool IgnoreProfitability;
3750
3751 /// True if we are optimizing for size.
3752 bool OptSize = false;
3753
3754 ProfileSummaryInfo *PSI;
3755 BlockFrequencyInfo *BFI;
3756 const CodeGenOptions &Opts;
3757
3758 AddressingModeMatcher(
3759 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3760 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3761 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3762 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3763 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3764 TypePromotionTransaction &TPT,
3765 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3766 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3767 const CodeGenOptions &Opts)
3768 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), DL(MI->getDataLayout()), LI(LI),
3769 getDTFn(getDTFn), AccessTy(AT), AddrSpace(AS), MemoryInst(MI),
3770 AddrMode(AM), InsertedInsts(InsertedInsts),
3771 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP),
3772 OptSize(OptSize), PSI(PSI), BFI(BFI), Opts(Opts) {
3773 IgnoreProfitability = false;
3774 }
3775
3776public:
3777 /// Find the maximal addressing mode that a load/store of V can fold,
3778 /// give an access type of AccessTy. This returns a list of involved
3779 /// instructions in AddrModeInsts.
3780 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3781 /// optimizations.
3782 /// \p PromotedInsts maps the instructions to their type before promotion.
3783 /// \p The ongoing transaction where every action should be registered.
3784 static ExtAddrMode
3785 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3786 SmallVectorImpl<Instruction *> &AddrModeInsts,
3787 const TargetLowering &TLI, const LoopInfo &LI,
3788 const std::function<const DominatorTree &()> getDTFn,
3789 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3790 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3791 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3792 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3793 const CodeGenOptions &Opts) {
3794 ExtAddrMode Result;
3795
3796 bool Success = AddressingModeMatcher(
3797 AddrModeInsts, TLI, TRI, LI, getDTFn, AccessTy, AS,
3798 MemoryInst, Result, InsertedInsts, PromotedInsts, TPT,
3799 LargeOffsetGEP, OptSize, PSI, BFI, Opts)
3800 .matchAddr(Addr: V, Depth: 0);
3801 (void)Success;
3802 assert(Success && "Couldn't select *anything*?");
3803 return Result;
3804 }
3805
3806private:
3807 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3808 bool matchAddr(Value *Addr, unsigned Depth);
3809 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3810 bool *MovedAway = nullptr);
3811 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3812 ExtAddrMode &AMBefore,
3813 ExtAddrMode &AMAfter);
3814 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3815 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3816 Value *PromotedOperand) const;
3817};
3818
3819class PhiNodeSet;
3820
3821/// An iterator for PhiNodeSet.
3822class PhiNodeSetIterator {
3823 PhiNodeSet *const Set;
3824 size_t CurrentIndex = 0;
3825
3826public:
3827 /// The constructor. Start should point to either a valid element, or be equal
3828 /// to the size of the underlying SmallVector of the PhiNodeSet.
3829 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3830 PHINode *operator*() const;
3831 PhiNodeSetIterator &operator++();
3832 bool operator==(const PhiNodeSetIterator &RHS) const;
3833 bool operator!=(const PhiNodeSetIterator &RHS) const;
3834};
3835
3836/// Keeps a set of PHINodes.
3837///
3838/// This is a minimal set implementation for a specific use case:
3839/// It is very fast when there are very few elements, but also provides good
3840/// performance when there are many. It is similar to SmallPtrSet, but also
3841/// provides iteration by insertion order, which is deterministic and stable
3842/// across runs. It is also similar to SmallSetVector, but provides removing
3843/// elements in O(1) time. This is achieved by not actually removing the element
3844/// from the underlying vector, so comes at the cost of using more memory, but
3845/// that is fine, since PhiNodeSets are used as short lived objects.
3846class PhiNodeSet {
3847 friend class PhiNodeSetIterator;
3848
3849 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3850 using iterator = PhiNodeSetIterator;
3851
3852 /// Keeps the elements in the order of their insertion in the underlying
3853 /// vector. To achieve constant time removal, it never deletes any element.
3854 SmallVector<PHINode *, 32> NodeList;
3855
3856 /// Keeps the elements in the underlying set implementation. This (and not the
3857 /// NodeList defined above) is the source of truth on whether an element
3858 /// is actually in the collection.
3859 MapType NodeMap;
3860
3861 /// Points to the first valid (not deleted) element when the set is not empty
3862 /// and the value is not zero. Equals to the size of the underlying vector
3863 /// when the set is empty. When the value is 0, as in the beginning, the
3864 /// first element may or may not be valid.
3865 size_t FirstValidElement = 0;
3866
3867public:
3868 /// Inserts a new element to the collection.
3869 /// \returns true if the element is actually added, i.e. was not in the
3870 /// collection before the operation.
3871 bool insert(PHINode *Ptr) {
3872 if (NodeMap.insert(KV: std::make_pair(x&: Ptr, y: NodeList.size())).second) {
3873 NodeList.push_back(Elt: Ptr);
3874 return true;
3875 }
3876 return false;
3877 }
3878
3879 /// Removes the element from the collection.
3880 /// \returns whether the element is actually removed, i.e. was in the
3881 /// collection before the operation.
3882 bool erase(PHINode *Ptr) {
3883 if (NodeMap.erase(Val: Ptr)) {
3884 SkipRemovedElements(CurrentIndex&: FirstValidElement);
3885 return true;
3886 }
3887 return false;
3888 }
3889
3890 /// Removes all elements and clears the collection.
3891 void clear() {
3892 NodeMap.clear();
3893 NodeList.clear();
3894 FirstValidElement = 0;
3895 }
3896
3897 /// \returns an iterator that will iterate the elements in the order of
3898 /// insertion.
3899 iterator begin() {
3900 if (FirstValidElement == 0)
3901 SkipRemovedElements(CurrentIndex&: FirstValidElement);
3902 return PhiNodeSetIterator(this, FirstValidElement);
3903 }
3904
3905 /// \returns an iterator that points to the end of the collection.
3906 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
3907
3908 /// Returns the number of elements in the collection.
3909 size_t size() const { return NodeMap.size(); }
3910
3911 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
3912 size_t count(PHINode *Ptr) const { return NodeMap.count(Val: Ptr); }
3913
3914private:
3915 /// Updates the CurrentIndex so that it will point to a valid element.
3916 ///
3917 /// If the element of NodeList at CurrentIndex is valid, it does not
3918 /// change it. If there are no more valid elements, it updates CurrentIndex
3919 /// to point to the end of the NodeList.
3920 void SkipRemovedElements(size_t &CurrentIndex) {
3921 while (CurrentIndex < NodeList.size()) {
3922 auto it = NodeMap.find(Val: NodeList[CurrentIndex]);
3923 // If the element has been deleted and added again later, NodeMap will
3924 // point to a different index, so CurrentIndex will still be invalid.
3925 if (it != NodeMap.end() && it->second == CurrentIndex)
3926 break;
3927 ++CurrentIndex;
3928 }
3929 }
3930};
3931
3932PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3933 : Set(Set), CurrentIndex(Start) {}
3934
3935PHINode *PhiNodeSetIterator::operator*() const {
3936 assert(CurrentIndex < Set->NodeList.size() &&
3937 "PhiNodeSet access out of range");
3938 return Set->NodeList[CurrentIndex];
3939}
3940
3941PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
3942 assert(CurrentIndex < Set->NodeList.size() &&
3943 "PhiNodeSet access out of range");
3944 ++CurrentIndex;
3945 Set->SkipRemovedElements(CurrentIndex);
3946 return *this;
3947}
3948
3949bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3950 return CurrentIndex == RHS.CurrentIndex;
3951}
3952
3953bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
3954 return !((*this) == RHS);
3955}
3956
3957/// Keep track of simplification of Phi nodes.
3958/// Accept the set of all phi nodes and erase phi node from this set
3959/// if it is simplified.
3960class SimplificationTracker {
3961 DenseMap<Value *, Value *> Storage;
3962 // Tracks newly created Phi nodes. The elements are iterated by insertion
3963 // order.
3964 PhiNodeSet AllPhiNodes;
3965 // Tracks newly created Select nodes.
3966 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3967
3968public:
3969 Value *Get(Value *V) {
3970 do {
3971 auto SV = Storage.find(Val: V);
3972 if (SV == Storage.end())
3973 return V;
3974 V = SV->second;
3975 } while (true);
3976 }
3977
3978 void Put(Value *From, Value *To) { Storage.insert(KV: {From, To}); }
3979
3980 void ReplacePhi(PHINode *From, PHINode *To) {
3981 Value *OldReplacement = Get(V: From);
3982 while (OldReplacement != From) {
3983 From = To;
3984 To = dyn_cast<PHINode>(Val: OldReplacement);
3985 OldReplacement = Get(V: From);
3986 }
3987 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
3988 Put(From, To);
3989 From->replaceAllUsesWith(V: To);
3990 AllPhiNodes.erase(Ptr: From);
3991 From->eraseFromParent();
3992 }
3993
3994 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
3995
3996 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(Ptr: PN); }
3997
3998 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(Ptr: SI); }
3999
4000 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
4001
4002 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
4003
4004 void destroyNewNodes(Type *CommonType) {
4005 // For safe erasing, replace the uses with dummy value first.
4006 auto *Dummy = PoisonValue::get(T: CommonType);
4007 for (auto *I : AllPhiNodes) {
4008 I->replaceAllUsesWith(V: Dummy);
4009 I->eraseFromParent();
4010 }
4011 AllPhiNodes.clear();
4012 for (auto *I : AllSelectNodes) {
4013 I->replaceAllUsesWith(V: Dummy);
4014 I->eraseFromParent();
4015 }
4016 AllSelectNodes.clear();
4017 }
4018};
4019
4020/// A helper class for combining addressing modes.
4021class AddressingModeCombiner {
4022 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
4023 typedef std::pair<PHINode *, PHINode *> PHIPair;
4024
4025private:
4026 /// The addressing modes we've collected.
4027 SmallVector<ExtAddrMode, 16> AddrModes;
4028
4029 /// The field in which the AddrModes differ, when we have more than one.
4030 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
4031
4032 /// Are the AddrModes that we have all just equal to their original values?
4033 bool AllAddrModesTrivial = true;
4034
4035 /// Common Type for all different fields in addressing modes.
4036 Type *CommonType = nullptr;
4037
4038 const DataLayout &DL;
4039 const CodeGenOptions &Opts;
4040
4041 /// Original Address.
4042 Value *Original;
4043
4044 /// Common value among addresses
4045 Value *CommonValue = nullptr;
4046
4047public:
4048 AddressingModeCombiner(const DataLayout &DL, const CodeGenOptions &Opts,
4049 Value *OriginalValue)
4050 : DL(DL), Opts(Opts), Original(OriginalValue) {}
4051
4052 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
4053
4054 /// Get the combined AddrMode
4055 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
4056
4057 /// Add a new AddrMode if it's compatible with the AddrModes we already
4058 /// have.
4059 /// \return True iff we succeeded in doing so.
4060 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
4061 // Take note of if we have any non-trivial AddrModes, as we need to detect
4062 // when all AddrModes are trivial as then we would introduce a phi or select
4063 // which just duplicates what's already there.
4064 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
4065
4066 // If this is the first addrmode then everything is fine.
4067 if (AddrModes.empty()) {
4068 AddrModes.emplace_back(Args&: NewAddrMode);
4069 return true;
4070 }
4071
4072 // Figure out how different this is from the other address modes, which we
4073 // can do just by comparing against the first one given that we only care
4074 // about the cumulative difference.
4075 ExtAddrMode::FieldName ThisDifferentField =
4076 AddrModes[0].compare(other: NewAddrMode);
4077 if (DifferentField == ExtAddrMode::NoField)
4078 DifferentField = ThisDifferentField;
4079 else if (DifferentField != ThisDifferentField)
4080 DifferentField = ExtAddrMode::MultipleFields;
4081
4082 // If NewAddrMode differs in more than one dimension we cannot handle it.
4083 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
4084
4085 // If Scale Field is different then we reject.
4086 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
4087
4088 // We also must reject the case when base offset is different and
4089 // scale reg is not null, we cannot handle this case due to merge of
4090 // different offsets will be used as ScaleReg.
4091 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
4092 !NewAddrMode.ScaledReg);
4093
4094 // We also must reject the case when GV is different and BaseReg installed
4095 // due to we want to use base reg as a merge of GV values.
4096 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
4097 !NewAddrMode.HasBaseReg);
4098
4099 // Even if NewAddMode is the same we still need to collect it due to
4100 // original value is different. And later we will need all original values
4101 // as anchors during finding the common Phi node.
4102 if (CanHandle)
4103 AddrModes.emplace_back(Args&: NewAddrMode);
4104 else
4105 AddrModes.clear();
4106
4107 return CanHandle;
4108 }
4109
4110 /// Combine the addressing modes we've collected into a single
4111 /// addressing mode.
4112 /// \return True iff we successfully combined them or we only had one so
4113 /// didn't need to combine them anyway.
4114 bool combineAddrModes() {
4115 // If we have no AddrModes then they can't be combined.
4116 if (AddrModes.size() == 0)
4117 return false;
4118
4119 // A single AddrMode can trivially be combined.
4120 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
4121 return true;
4122
4123 // If the AddrModes we collected are all just equal to the value they are
4124 // derived from then combining them wouldn't do anything useful.
4125 if (AllAddrModesTrivial)
4126 return false;
4127
4128 if (!addrModeCombiningAllowed())
4129 return false;
4130
4131 // Build a map between <original value, basic block where we saw it> to
4132 // value of base register.
4133 // Bail out if there is no common type.
4134 FoldAddrToValueMapping Map;
4135 if (!initializeMap(Map))
4136 return false;
4137
4138 CommonValue = findCommon(Map);
4139 if (CommonValue)
4140 AddrModes[0].SetCombinedField(Field: DifferentField, V: CommonValue, AddrModes);
4141 return CommonValue != nullptr;
4142 }
4143
4144private:
4145 /// `CommonValue` may be a placeholder inserted by us.
4146 /// If the placeholder is not used, we should remove this dead instruction.
4147 void eraseCommonValueIfDead() {
4148 if (CommonValue && CommonValue->use_empty())
4149 if (Instruction *CommonInst = dyn_cast<Instruction>(Val: CommonValue))
4150 CommonInst->eraseFromParent();
4151 }
4152
4153 /// Initialize Map with anchor values. For address seen
4154 /// we set the value of different field saw in this address.
4155 /// At the same time we find a common type for different field we will
4156 /// use to create new Phi/Select nodes. Keep it in CommonType field.
4157 /// Return false if there is no common type found.
4158 bool initializeMap(FoldAddrToValueMapping &Map) {
4159 // Keep track of keys where the value is null. We will need to replace it
4160 // with constant null when we know the common type.
4161 SmallVector<Value *, 2> NullValue;
4162 Type *IntPtrTy = DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
4163 for (auto &AM : AddrModes) {
4164 Value *DV = AM.GetFieldAsValue(Field: DifferentField, IntPtrTy);
4165 if (DV) {
4166 auto *Type = DV->getType();
4167 if (CommonType && CommonType != Type)
4168 return false;
4169 CommonType = Type;
4170 Map[AM.OriginalValue] = DV;
4171 } else {
4172 NullValue.push_back(Elt: AM.OriginalValue);
4173 }
4174 }
4175 assert(CommonType && "At least one non-null value must be!");
4176 for (auto *V : NullValue)
4177 Map[V] = Constant::getNullValue(Ty: CommonType);
4178 return true;
4179 }
4180
4181 /// We have mapping between value A and other value B where B was a field in
4182 /// addressing mode represented by A. Also we have an original value C
4183 /// representing an address we start with. Traversing from C through phi and
4184 /// selects we ended up with A's in a map. This utility function tries to find
4185 /// a value V which is a field in addressing mode C and traversing through phi
4186 /// nodes and selects we will end up in corresponded values B in a map.
4187 /// The utility will create a new Phi/Selects if needed.
4188 // The simple example looks as follows:
4189 // BB1:
4190 // p1 = b1 + 40
4191 // br cond BB2, BB3
4192 // BB2:
4193 // p2 = b2 + 40
4194 // br BB3
4195 // BB3:
4196 // p = phi [p1, BB1], [p2, BB2]
4197 // v = load p
4198 // Map is
4199 // p1 -> b1
4200 // p2 -> b2
4201 // Request is
4202 // p -> ?
4203 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
4204 Value *findCommon(FoldAddrToValueMapping &Map) {
4205 // Tracks the simplification of newly created phi nodes. The reason we use
4206 // this mapping is because we will add new created Phi nodes in AddrToBase.
4207 // Simplification of Phi nodes is recursive, so some Phi node may
4208 // be simplified after we added it to AddrToBase. In reality this
4209 // simplification is possible only if original phi/selects were not
4210 // simplified yet.
4211 // Using this mapping we can find the current value in AddrToBase.
4212 SimplificationTracker ST;
4213
4214 // First step, DFS to create PHI nodes for all intermediate blocks.
4215 // Also fill traverse order for the second step.
4216 SmallVector<Value *, 32> TraverseOrder;
4217 InsertPlaceholders(Map, TraverseOrder, ST);
4218
4219 // Second Step, fill new nodes by merged values and simplify if possible.
4220 FillPlaceholders(Map, TraverseOrder, ST);
4221
4222 if (!Opts.cgp_addr_sink_new_select && ST.countNewSelectNodes() > 0) {
4223 ST.destroyNewNodes(CommonType);
4224 return nullptr;
4225 }
4226
4227 // Now we'd like to match New Phi nodes to existed ones.
4228 unsigned PhiNotMatchedCount = 0;
4229 if (!MatchPhiSet(ST, AllowNewPhiNodes: Opts.cgp_addr_sink_new_phis, PhiNotMatchedCount)) {
4230 ST.destroyNewNodes(CommonType);
4231 return nullptr;
4232 }
4233
4234 auto *Result = ST.Get(V: Map.find(Val: Original)->second);
4235 if (Result) {
4236 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
4237 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
4238 }
4239 return Result;
4240 }
4241
4242 /// Try to match PHI node to Candidate.
4243 /// Matcher tracks the matched Phi nodes.
4244 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
4245 SmallSetVector<PHIPair, 8> &Matcher,
4246 PhiNodeSet &PhiNodesToMatch) {
4247 SmallVector<PHIPair, 8> WorkList;
4248 Matcher.insert(X: {PHI, Candidate});
4249 SmallPtrSet<PHINode *, 8> MatchedPHIs;
4250 MatchedPHIs.insert(Ptr: PHI);
4251 WorkList.push_back(Elt: {PHI, Candidate});
4252 SmallSet<PHIPair, 8> Visited;
4253 while (!WorkList.empty()) {
4254 auto Item = WorkList.pop_back_val();
4255 if (!Visited.insert(V: Item).second)
4256 continue;
4257 // We iterate over all incoming values to Phi to compare them.
4258 // If values are different and both of them Phi and the first one is a
4259 // Phi we added (subject to match) and both of them is in the same basic
4260 // block then we can match our pair if values match. So we state that
4261 // these values match and add it to work list to verify that.
4262 for (auto *B : Item.first->blocks()) {
4263 Value *FirstValue = Item.first->getIncomingValueForBlock(BB: B);
4264 Value *SecondValue = Item.second->getIncomingValueForBlock(BB: B);
4265 if (FirstValue == SecondValue)
4266 continue;
4267
4268 PHINode *FirstPhi = dyn_cast<PHINode>(Val: FirstValue);
4269 PHINode *SecondPhi = dyn_cast<PHINode>(Val: SecondValue);
4270
4271 // One of them is not Phi or
4272 // The first one is not Phi node from the set we'd like to match or
4273 // Phi nodes from different basic blocks then
4274 // we will not be able to match.
4275 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(Ptr: FirstPhi) ||
4276 FirstPhi->getParent() != SecondPhi->getParent())
4277 return false;
4278
4279 // If we already matched them then continue.
4280 if (Matcher.count(key: {FirstPhi, SecondPhi}))
4281 continue;
4282 // So the values are different and does not match. So we need them to
4283 // match. (But we register no more than one match per PHI node, so that
4284 // we won't later try to replace them twice.)
4285 if (MatchedPHIs.insert(Ptr: FirstPhi).second)
4286 Matcher.insert(X: {FirstPhi, SecondPhi});
4287 // But me must check it.
4288 WorkList.push_back(Elt: {FirstPhi, SecondPhi});
4289 }
4290 }
4291 return true;
4292 }
4293
4294 /// For the given set of PHI nodes (in the SimplificationTracker) try
4295 /// to find their equivalents.
4296 /// Returns false if this matching fails and creation of new Phi is disabled.
4297 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
4298 unsigned &PhiNotMatchedCount) {
4299 // Matched and PhiNodesToMatch iterate their elements in a deterministic
4300 // order, so the replacements (ReplacePhi) are also done in a deterministic
4301 // order.
4302 SmallSetVector<PHIPair, 8> Matched;
4303 SmallPtrSet<PHINode *, 8> WillNotMatch;
4304 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
4305 while (PhiNodesToMatch.size()) {
4306 PHINode *PHI = *PhiNodesToMatch.begin();
4307
4308 // Add us, if no Phi nodes in the basic block we do not match.
4309 WillNotMatch.clear();
4310 WillNotMatch.insert(Ptr: PHI);
4311
4312 // Traverse all Phis until we found equivalent or fail to do that.
4313 bool IsMatched = false;
4314 for (auto &P : PHI->getParent()->phis()) {
4315 // Skip new Phi nodes.
4316 if (PhiNodesToMatch.count(Ptr: &P))
4317 continue;
4318 if ((IsMatched = MatchPhiNode(PHI, Candidate: &P, Matcher&: Matched, PhiNodesToMatch)))
4319 break;
4320 // If it does not match, collect all Phi nodes from matcher.
4321 // if we end up with no match, them all these Phi nodes will not match
4322 // later.
4323 WillNotMatch.insert_range(R: llvm::make_first_range(c&: Matched));
4324 Matched.clear();
4325 }
4326 if (IsMatched) {
4327 // Replace all matched values and erase them.
4328 for (auto MV : Matched)
4329 ST.ReplacePhi(From: MV.first, To: MV.second);
4330 Matched.clear();
4331 continue;
4332 }
4333 // If we are not allowed to create new nodes then bail out.
4334 if (!AllowNewPhiNodes)
4335 return false;
4336 // Just remove all seen values in matcher. They will not match anything.
4337 PhiNotMatchedCount += WillNotMatch.size();
4338 for (auto *P : WillNotMatch)
4339 PhiNodesToMatch.erase(Ptr: P);
4340 }
4341 return true;
4342 }
4343 /// Fill the placeholders with values from predecessors and simplify them.
4344 void FillPlaceholders(FoldAddrToValueMapping &Map,
4345 SmallVectorImpl<Value *> &TraverseOrder,
4346 SimplificationTracker &ST) {
4347 while (!TraverseOrder.empty()) {
4348 Value *Current = TraverseOrder.pop_back_val();
4349 assert(Map.contains(Current) && "No node to fill!!!");
4350 Value *V = Map[Current];
4351
4352 if (SelectInst *Select = dyn_cast<SelectInst>(Val: V)) {
4353 // CurrentValue also must be Select.
4354 auto *CurrentSelect = cast<SelectInst>(Val: Current);
4355 auto *TrueValue = CurrentSelect->getTrueValue();
4356 assert(Map.contains(TrueValue) && "No True Value!");
4357 Select->setTrueValue(ST.Get(V: Map[TrueValue]));
4358 auto *FalseValue = CurrentSelect->getFalseValue();
4359 assert(Map.contains(FalseValue) && "No False Value!");
4360 Select->setFalseValue(ST.Get(V: Map[FalseValue]));
4361 } else {
4362 // Must be a Phi node then.
4363 auto *PHI = cast<PHINode>(Val: V);
4364 // Fill the Phi node with values from predecessors.
4365 for (auto *B : predecessors(BB: PHI->getParent())) {
4366 Value *PV = cast<PHINode>(Val: Current)->getIncomingValueForBlock(BB: B);
4367 assert(Map.contains(PV) && "No predecessor Value!");
4368 PHI->addIncoming(V: ST.Get(V: Map[PV]), BB: B);
4369 }
4370 }
4371 }
4372 }
4373
4374 /// Starting from original value recursively iterates over def-use chain up to
4375 /// known ending values represented in a map. For each traversed phi/select
4376 /// inserts a placeholder Phi or Select.
4377 /// Reports all new created Phi/Select nodes by adding them to set.
4378 /// Also reports and order in what values have been traversed.
4379 void InsertPlaceholders(FoldAddrToValueMapping &Map,
4380 SmallVectorImpl<Value *> &TraverseOrder,
4381 SimplificationTracker &ST) {
4382 SmallVector<Value *, 32> Worklist;
4383 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
4384 "Address must be a Phi or Select node");
4385 auto *Dummy = PoisonValue::get(T: CommonType);
4386 Worklist.push_back(Elt: Original);
4387 while (!Worklist.empty()) {
4388 Value *Current = Worklist.pop_back_val();
4389 // if it is already visited or it is an ending value then skip it.
4390 if (Map.contains(Val: Current))
4391 continue;
4392 TraverseOrder.push_back(Elt: Current);
4393
4394 // CurrentValue must be a Phi node or select. All others must be covered
4395 // by anchors.
4396 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Val: Current)) {
4397 // Is it OK to get metadata from OrigSelect?!
4398 // Create a Select placeholder with dummy value.
4399 SelectInst *Select =
4400 SelectInst::Create(C: CurrentSelect->getCondition(), S1: Dummy, S2: Dummy,
4401 NameStr: CurrentSelect->getName(),
4402 InsertBefore: CurrentSelect->getIterator(), MDFrom: CurrentSelect);
4403 Map[Current] = Select;
4404 ST.insertNewSelect(SI: Select);
4405 // We are interested in True and False values.
4406 Worklist.push_back(Elt: CurrentSelect->getTrueValue());
4407 Worklist.push_back(Elt: CurrentSelect->getFalseValue());
4408 } else {
4409 // It must be a Phi node then.
4410 PHINode *CurrentPhi = cast<PHINode>(Val: Current);
4411 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4412 PHINode *PHI =
4413 PHINode::Create(Ty: CommonType, NumReservedValues: PredCount, NameStr: "sunk_phi", InsertBefore: CurrentPhi->getIterator());
4414 Map[Current] = PHI;
4415 ST.insertNewPhi(PN: PHI);
4416 append_range(C&: Worklist, R: CurrentPhi->incoming_values());
4417 }
4418 }
4419 }
4420
4421 bool addrModeCombiningAllowed() {
4422 if (!Opts.cgp_complex_addr_modes)
4423 return false;
4424 switch (DifferentField) {
4425 default:
4426 return false;
4427 case ExtAddrMode::BaseRegField:
4428 return Opts.cgp_addr_sink_combine_base_reg;
4429 case ExtAddrMode::BaseGVField:
4430 return Opts.cgp_addr_sink_combine_base_gv;
4431 case ExtAddrMode::BaseOffsField:
4432 return Opts.cgp_addr_sink_combine_base_offs;
4433 case ExtAddrMode::ScaledRegField:
4434 return Opts.cgp_addr_sink_combine_scaled_reg;
4435 }
4436 }
4437};
4438} // end anonymous namespace
4439
4440/// Try adding ScaleReg*Scale to the current addressing mode.
4441/// Return true and update AddrMode if this addr mode is legal for the target,
4442/// false if not.
4443bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
4444 unsigned Depth) {
4445 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
4446 // mode. Just process that directly.
4447 if (Scale == 1)
4448 return matchAddr(Addr: ScaleReg, Depth);
4449
4450 // If the scale is 0, it takes nothing to add this.
4451 if (Scale == 0)
4452 return true;
4453
4454 // If we already have a scale of this value, we can add to it, otherwise, we
4455 // need an available scale field.
4456 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
4457 return false;
4458
4459 ExtAddrMode TestAddrMode = AddrMode;
4460
4461 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
4462 // [A+B + A*7] -> [B+A*8].
4463 TestAddrMode.Scale += Scale;
4464 TestAddrMode.ScaledReg = ScaleReg;
4465
4466 // If the new address isn't legal, bail out.
4467 if (!TLI.isLegalAddressingMode(DL, AM: TestAddrMode, Ty: AccessTy, AddrSpace))
4468 return false;
4469
4470 // It was legal, so commit it.
4471 AddrMode = TestAddrMode;
4472
4473 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
4474 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
4475 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
4476 // go any further: we can reuse it and cannot eliminate it.
4477 ConstantInt *CI = nullptr;
4478 Value *AddLHS = nullptr;
4479 if (isa<Instruction>(Val: ScaleReg) && // not a constant expr.
4480 match(V: ScaleReg, P: m_Add(L: m_Value(V&: AddLHS), R: m_ConstantInt(CI))) &&
4481 !isIVIncrement(V: ScaleReg, LI: &LI) && CI->getValue().isSignedIntN(N: 64)) {
4482 TestAddrMode.InBounds = false;
4483 TestAddrMode.ScaledReg = AddLHS;
4484 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4485
4486 // If this addressing mode is legal, commit it and remember that we folded
4487 // this instruction.
4488 if (TLI.isLegalAddressingMode(DL, AM: TestAddrMode, Ty: AccessTy, AddrSpace)) {
4489 AddrModeInsts.push_back(Elt: cast<Instruction>(Val: ScaleReg));
4490 AddrMode = TestAddrMode;
4491 return true;
4492 }
4493 // Restore status quo.
4494 TestAddrMode = AddrMode;
4495 }
4496
4497 // If this is an add recurrence with a constant step, return the increment
4498 // instruction and the canonicalized step.
4499 auto GetConstantStep =
4500 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4501 auto *PN = dyn_cast<PHINode>(Val: V);
4502 if (!PN)
4503 return std::nullopt;
4504 auto IVInc = getIVIncrement(PN, LI: &LI);
4505 if (!IVInc)
4506 return std::nullopt;
4507 // TODO: The result of the intrinsics above is two-complement. However when
4508 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4509 // If it has nuw or nsw flags, we need to make sure that these flags are
4510 // inferrable at the point of memory instruction. Otherwise we are replacing
4511 // well-defined two-complement computation with poison. Currently, to avoid
4512 // potentially complex analysis needed to prove this, we reject such cases.
4513 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(Val: IVInc->first))
4514 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4515 return std::nullopt;
4516 if (auto *ConstantStep = dyn_cast<ConstantInt>(Val: IVInc->second))
4517 return std::make_pair(x&: IVInc->first, y: ConstantStep->getValue());
4518 return std::nullopt;
4519 };
4520
4521 // Try to account for the following special case:
4522 // 1. ScaleReg is an inductive variable;
4523 // 2. We use it with non-zero offset;
4524 // 3. IV's increment is available at the point of memory instruction.
4525 //
4526 // In this case, we may reuse the IV increment instead of the IV Phi to
4527 // achieve the following advantages:
4528 // 1. If IV step matches the offset, we will have no need in the offset;
4529 // 2. Even if they don't match, we will reduce the overlap of living IV
4530 // and IV increment, that will potentially lead to better register
4531 // assignment.
4532 if (AddrMode.BaseOffs) {
4533 if (auto IVStep = GetConstantStep(ScaleReg)) {
4534 Instruction *IVInc = IVStep->first;
4535 // The following assert is important to ensure a lack of infinite loops.
4536 // This transforms is (intentionally) the inverse of the one just above.
4537 // If they don't agree on the definition of an increment, we'd alternate
4538 // back and forth indefinitely.
4539 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4540 APInt Step = IVStep->second;
4541 APInt Offset = Step * AddrMode.Scale;
4542 if (Offset.isSignedIntN(N: 64)) {
4543 TestAddrMode.InBounds = false;
4544 TestAddrMode.ScaledReg = IVInc;
4545 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4546 // If this addressing mode is legal, commit it..
4547 // (Note that we defer the (expensive) domtree base legality check
4548 // to the very last possible point.)
4549 if (TLI.isLegalAddressingMode(DL, AM: TestAddrMode, Ty: AccessTy, AddrSpace) &&
4550 getDTFn().dominates(Def: IVInc, User: MemoryInst)) {
4551 AddrModeInsts.push_back(Elt: cast<Instruction>(Val: IVInc));
4552 AddrMode = TestAddrMode;
4553 return true;
4554 }
4555 // Restore status quo.
4556 TestAddrMode = AddrMode;
4557 }
4558 }
4559 }
4560
4561 // Otherwise, just return what we have.
4562 return true;
4563}
4564
4565/// This is a little filter, which returns true if an addressing computation
4566/// involving I might be folded into a load/store accessing it.
4567/// This doesn't need to be perfect, but needs to accept at least
4568/// the set of instructions that MatchOperationAddr can.
4569static bool MightBeFoldableInst(Instruction *I) {
4570 switch (I->getOpcode()) {
4571 case Instruction::BitCast:
4572 case Instruction::AddrSpaceCast:
4573 // Don't touch identity bitcasts.
4574 if (I->getType() == I->getOperand(i: 0)->getType())
4575 return false;
4576 return I->getType()->isIntOrPtrTy();
4577 case Instruction::PtrToInt:
4578 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4579 return true;
4580 case Instruction::IntToPtr:
4581 // We know the input is intptr_t, so this is foldable.
4582 return true;
4583 case Instruction::Add:
4584 return true;
4585 case Instruction::Mul:
4586 case Instruction::Shl:
4587 // Can only handle X*C and X << C.
4588 return isa<ConstantInt>(Val: I->getOperand(i: 1));
4589 case Instruction::GetElementPtr:
4590 return true;
4591 default:
4592 return false;
4593 }
4594}
4595
4596/// Check whether or not \p Val is a legal instruction for \p TLI.
4597/// \note \p Val is assumed to be the product of some type promotion.
4598/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4599/// to be legal, as the non-promoted value would have had the same state.
4600static bool isPromotedInstructionLegal(const TargetLowering &TLI,
4601 const DataLayout &DL, Value *Val) {
4602 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4603 if (!PromotedInst)
4604 return false;
4605 int ISDOpcode = TLI.InstructionOpcodeToISD(Opcode: PromotedInst->getOpcode());
4606 // If the ISDOpcode is undefined, it was undefined before the promotion.
4607 if (!ISDOpcode)
4608 return true;
4609 // Otherwise, check if the promoted instruction is legal or not.
4610 return TLI.isOperationLegalOrCustom(
4611 Op: ISDOpcode, VT: TLI.getValueType(DL, Ty: PromotedInst->getType()));
4612}
4613
4614namespace {
4615
4616/// Hepler class to perform type promotion.
4617class TypePromotionHelper {
4618 /// Utility function to add a promoted instruction \p ExtOpnd to
4619 /// \p PromotedInsts and record the type of extension we have seen.
4620 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4621 Instruction *ExtOpnd, bool IsSExt) {
4622 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4623 auto [It, Inserted] = PromotedInsts.try_emplace(Key: ExtOpnd);
4624 if (!Inserted) {
4625 // If the new extension is same as original, the information in
4626 // PromotedInsts[ExtOpnd] is still correct.
4627 if (It->second.getInt() == ExtTy)
4628 return;
4629
4630 // Now the new extension is different from old extension, we make
4631 // the type information invalid by setting extension type to
4632 // BothExtension.
4633 ExtTy = BothExtension;
4634 }
4635 It->second = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4636 }
4637
4638 /// Utility function to query the original type of instruction \p Opnd
4639 /// with a matched extension type. If the extension doesn't match, we
4640 /// cannot use the information we had on the original type.
4641 /// BothExtension doesn't match any extension type.
4642 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4643 Instruction *Opnd, bool IsSExt) {
4644 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4645 InstrToOrigTy::const_iterator It = PromotedInsts.find(Val: Opnd);
4646 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4647 return It->second.getPointer();
4648 return nullptr;
4649 }
4650
4651 /// Utility function to check whether or not a sign or zero extension
4652 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4653 /// either using the operands of \p Inst or promoting \p Inst.
4654 /// The type of the extension is defined by \p IsSExt.
4655 /// In other words, check if:
4656 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4657 /// #1 Promotion applies:
4658 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4659 /// #2 Operand reuses:
4660 /// ext opnd1 to ConsideredExtType.
4661 /// \p PromotedInsts maps the instructions to their type before promotion.
4662 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4663 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4664
4665 /// Utility function to determine if \p OpIdx should be promoted when
4666 /// promoting \p Inst.
4667 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4668 return !(isa<SelectInst>(Val: Inst) && OpIdx == 0);
4669 }
4670
4671 /// Utility function to promote the operand of \p Ext when this
4672 /// operand is a promotable trunc or sext or zext.
4673 /// \p PromotedInsts maps the instructions to their type before promotion.
4674 /// \p CreatedInstsCost[out] contains the cost of all instructions
4675 /// created to promote the operand of Ext.
4676 /// Newly added extensions are inserted in \p Exts.
4677 /// Newly added truncates are inserted in \p Truncs.
4678 /// Should never be called directly.
4679 /// \return The promoted value which is used instead of Ext.
4680 static Value *promoteOperandForTruncAndAnyExt(
4681 Instruction *Ext, TypePromotionTransaction &TPT,
4682 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4683 SmallVectorImpl<Instruction *> *Exts,
4684 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4685
4686 /// Utility function to promote the operand of \p Ext when this
4687 /// operand is promotable and is not a supported trunc or sext.
4688 /// \p PromotedInsts maps the instructions to their type before promotion.
4689 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4690 /// created to promote the operand of Ext.
4691 /// Newly added extensions are inserted in \p Exts.
4692 /// Newly added truncates are inserted in \p Truncs.
4693 /// Should never be called directly.
4694 /// \return The promoted value which is used instead of Ext.
4695 static Value *promoteOperandForOther(Instruction *Ext,
4696 TypePromotionTransaction &TPT,
4697 InstrToOrigTy &PromotedInsts,
4698 unsigned &CreatedInstsCost,
4699 SmallVectorImpl<Instruction *> *Exts,
4700 SmallVectorImpl<Instruction *> *Truncs,
4701 const TargetLowering &TLI, bool IsSExt);
4702
4703 /// \see promoteOperandForOther.
4704 static Value *signExtendOperandForOther(
4705 Instruction *Ext, TypePromotionTransaction &TPT,
4706 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4707 SmallVectorImpl<Instruction *> *Exts,
4708 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4709 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4710 Exts, Truncs, TLI, IsSExt: true);
4711 }
4712
4713 /// \see promoteOperandForOther.
4714 static Value *zeroExtendOperandForOther(
4715 Instruction *Ext, TypePromotionTransaction &TPT,
4716 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4717 SmallVectorImpl<Instruction *> *Exts,
4718 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4719 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4720 Exts, Truncs, TLI, IsSExt: false);
4721 }
4722
4723public:
4724 /// Type for the utility function that promotes the operand of Ext.
4725 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4726 InstrToOrigTy &PromotedInsts,
4727 unsigned &CreatedInstsCost,
4728 SmallVectorImpl<Instruction *> *Exts,
4729 SmallVectorImpl<Instruction *> *Truncs,
4730 const TargetLowering &TLI);
4731
4732 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4733 /// action to promote the operand of \p Ext instead of using Ext.
4734 /// \return NULL if no promotable action is possible with the current
4735 /// sign extension.
4736 /// \p InsertedInsts keeps track of all the instructions inserted by the
4737 /// other CodeGenPrepare optimizations. This information is important
4738 /// because we do not want to promote these instructions as CodeGenPrepare
4739 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4740 /// \p PromotedInsts maps the instructions to their type before promotion.
4741 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4742 const TargetLowering &TLI,
4743 const InstrToOrigTy &PromotedInsts);
4744};
4745
4746} // end anonymous namespace
4747
4748bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4749 Type *ConsideredExtType,
4750 const InstrToOrigTy &PromotedInsts,
4751 bool IsSExt) {
4752 // The promotion helper does not know how to deal with vector types yet.
4753 // To be able to fix that, we would need to fix the places where we
4754 // statically extend, e.g., constants and such.
4755 if (Inst->getType()->isVectorTy())
4756 return false;
4757
4758 // We can always get through zext.
4759 if (isa<ZExtInst>(Val: Inst))
4760 return true;
4761
4762 // sext(sext) is ok too.
4763 if (IsSExt && isa<SExtInst>(Val: Inst))
4764 return true;
4765
4766 // We can get through binary operator, if it is legal. In other words, the
4767 // binary operator must have a nuw or nsw flag.
4768 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: Inst))
4769 if (isa<OverflowingBinaryOperator>(Val: BinOp) &&
4770 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4771 (IsSExt && BinOp->hasNoSignedWrap())))
4772 return true;
4773
4774 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4775 if ((Inst->getOpcode() == Instruction::And ||
4776 Inst->getOpcode() == Instruction::Or))
4777 return true;
4778
4779 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4780 if (Inst->getOpcode() == Instruction::Xor) {
4781 // Make sure it is not a NOT.
4782 if (const auto *Cst = dyn_cast<ConstantInt>(Val: Inst->getOperand(i: 1)))
4783 if (!Cst->getValue().isAllOnes())
4784 return true;
4785 }
4786
4787 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4788 // It may change a poisoned value into a regular value, like
4789 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4790 // poisoned value regular value
4791 // It should be OK since undef covers valid value.
4792 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4793 return true;
4794
4795 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4796 // It may change a poisoned value into a regular value, like
4797 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4798 // poisoned value regular value
4799 // It should be OK since undef covers valid value.
4800 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4801 const auto *ExtInst = cast<const Instruction>(Val: *Inst->user_begin());
4802 if (ExtInst->hasOneUse()) {
4803 const auto *AndInst = dyn_cast<const Instruction>(Val: *ExtInst->user_begin());
4804 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4805 const auto *Cst = dyn_cast<ConstantInt>(Val: AndInst->getOperand(i: 1));
4806 if (Cst &&
4807 Cst->getValue().isIntN(N: Inst->getType()->getIntegerBitWidth()))
4808 return true;
4809 }
4810 }
4811 }
4812
4813 // Check if we can do the following simplification.
4814 // ext(trunc(opnd)) --> ext(opnd)
4815 if (!isa<TruncInst>(Val: Inst))
4816 return false;
4817
4818 Value *OpndVal = Inst->getOperand(i: 0);
4819 // Check if we can use this operand in the extension.
4820 // If the type is larger than the result type of the extension, we cannot.
4821 if (!OpndVal->getType()->isIntegerTy() ||
4822 OpndVal->getType()->getIntegerBitWidth() >
4823 ConsideredExtType->getIntegerBitWidth())
4824 return false;
4825
4826 // If the operand of the truncate is not an instruction, we will not have
4827 // any information on the dropped bits.
4828 // (Actually we could for constant but it is not worth the extra logic).
4829 Instruction *Opnd = dyn_cast<Instruction>(Val: OpndVal);
4830 if (!Opnd)
4831 return false;
4832
4833 // Check if the source of the type is narrow enough.
4834 // I.e., check that trunc just drops extended bits of the same kind of
4835 // the extension.
4836 // #1 get the type of the operand and check the kind of the extended bits.
4837 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4838 if (OpndType)
4839 ;
4840 else if ((IsSExt && isa<SExtInst>(Val: Opnd)) || (!IsSExt && isa<ZExtInst>(Val: Opnd)))
4841 OpndType = Opnd->getOperand(i: 0)->getType();
4842 else
4843 return false;
4844
4845 // #2 check that the truncate just drops extended bits.
4846 return Inst->getType()->getIntegerBitWidth() >=
4847 OpndType->getIntegerBitWidth();
4848}
4849
4850TypePromotionHelper::Action TypePromotionHelper::getAction(
4851 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4852 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4853 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4854 "Unexpected instruction type");
4855 Instruction *ExtOpnd = dyn_cast<Instruction>(Val: Ext->getOperand(i: 0));
4856 Type *ExtTy = Ext->getType();
4857 bool IsSExt = isa<SExtInst>(Val: Ext);
4858 // If the operand of the extension is not an instruction, we cannot
4859 // get through.
4860 // If it, check we can get through.
4861 if (!ExtOpnd || !canGetThrough(Inst: ExtOpnd, ConsideredExtType: ExtTy, PromotedInsts, IsSExt))
4862 return nullptr;
4863
4864 // Do not promote if the operand has been added by codegenprepare.
4865 // Otherwise, it means we are undoing an optimization that is likely to be
4866 // redone, thus causing potential infinite loop.
4867 if (isa<TruncInst>(Val: ExtOpnd) && InsertedInsts.count(Ptr: ExtOpnd))
4868 return nullptr;
4869
4870 // SExt or Trunc instructions.
4871 // Return the related handler.
4872 if (isa<SExtInst>(Val: ExtOpnd) || isa<TruncInst>(Val: ExtOpnd) ||
4873 isa<ZExtInst>(Val: ExtOpnd))
4874 return promoteOperandForTruncAndAnyExt;
4875
4876 // Regular instruction.
4877 // Abort early if we will have to insert non-free instructions.
4878 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(FromTy: ExtTy, ToTy: ExtOpnd->getType()))
4879 return nullptr;
4880 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4881}
4882
4883Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4884 Instruction *SExt, TypePromotionTransaction &TPT,
4885 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4886 SmallVectorImpl<Instruction *> *Exts,
4887 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4888 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4889 // get through it and this method should not be called.
4890 Instruction *SExtOpnd = cast<Instruction>(Val: SExt->getOperand(i: 0));
4891 Value *ExtVal = SExt;
4892 bool HasMergedNonFreeExt = false;
4893 if (isa<ZExtInst>(Val: SExtOpnd)) {
4894 // Replace s|zext(zext(opnd))
4895 // => zext(opnd).
4896 HasMergedNonFreeExt = !TLI.isExtFree(I: SExtOpnd);
4897 Value *ZExt =
4898 TPT.createZExt(Inst: SExt, Opnd: SExtOpnd->getOperand(i: 0), Ty: SExt->getType());
4899 TPT.replaceAllUsesWith(Inst: SExt, New: ZExt);
4900 TPT.eraseInstruction(Inst: SExt);
4901 ExtVal = ZExt;
4902 } else {
4903 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4904 // => z|sext(opnd).
4905 TPT.setOperand(Inst: SExt, Idx: 0, NewVal: SExtOpnd->getOperand(i: 0));
4906 }
4907 CreatedInstsCost = 0;
4908
4909 // Remove dead code.
4910 if (SExtOpnd->use_empty())
4911 TPT.eraseInstruction(Inst: SExtOpnd);
4912
4913 // Check if the extension is still needed.
4914 Instruction *ExtInst = dyn_cast<Instruction>(Val: ExtVal);
4915 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(i: 0)->getType()) {
4916 if (ExtInst) {
4917 if (Exts)
4918 Exts->push_back(Elt: ExtInst);
4919 CreatedInstsCost = !TLI.isExtFree(I: ExtInst) && !HasMergedNonFreeExt;
4920 }
4921 return ExtVal;
4922 }
4923
4924 // At this point we have: ext ty opnd to ty.
4925 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4926 Value *NextVal = ExtInst->getOperand(i: 0);
4927 TPT.eraseInstruction(Inst: ExtInst, NewVal: NextVal);
4928 return NextVal;
4929}
4930
4931Value *TypePromotionHelper::promoteOperandForOther(
4932 Instruction *Ext, TypePromotionTransaction &TPT,
4933 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4934 SmallVectorImpl<Instruction *> *Exts,
4935 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
4936 bool IsSExt) {
4937 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4938 // get through it and this method should not be called.
4939 Instruction *ExtOpnd = cast<Instruction>(Val: Ext->getOperand(i: 0));
4940 CreatedInstsCost = 0;
4941 if (!ExtOpnd->hasOneUse()) {
4942 // ExtOpnd will be promoted.
4943 // All its uses, but Ext, will need to use a truncated value of the
4944 // promoted version.
4945 // Create the truncate now.
4946 Value *Trunc = TPT.createTrunc(Opnd: Ext, Ty: ExtOpnd->getType());
4947 if (Instruction *ITrunc = dyn_cast<Instruction>(Val: Trunc)) {
4948 // Insert it just after the definition.
4949 ITrunc->moveAfter(MovePos: ExtOpnd);
4950 if (Truncs)
4951 Truncs->push_back(Elt: ITrunc);
4952 }
4953
4954 TPT.replaceAllUsesWith(Inst: ExtOpnd, New: Trunc);
4955 // Restore the operand of Ext (which has been replaced by the previous call
4956 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4957 TPT.setOperand(Inst: Ext, Idx: 0, NewVal: ExtOpnd);
4958 }
4959
4960 // Get through the Instruction:
4961 // 1. Update its type.
4962 // 2. Replace the uses of Ext by Inst.
4963 // 3. Extend each operand that needs to be extended.
4964
4965 // Remember the original type of the instruction before promotion.
4966 // This is useful to know that the high bits are sign extended bits.
4967 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4968 // Step #1.
4969 TPT.mutateType(Inst: ExtOpnd, NewTy: Ext->getType());
4970 // Step #2.
4971 TPT.replaceAllUsesWith(Inst: Ext, New: ExtOpnd);
4972 // Step #3.
4973 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
4974 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4975 ++OpIdx) {
4976 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4977 if (ExtOpnd->getOperand(i: OpIdx)->getType() == Ext->getType() ||
4978 !shouldExtOperand(Inst: ExtOpnd, OpIdx)) {
4979 LLVM_DEBUG(dbgs() << "No need to propagate\n");
4980 continue;
4981 }
4982 // Check if we can statically extend the operand.
4983 Value *Opnd = ExtOpnd->getOperand(i: OpIdx);
4984 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Val: Opnd)) {
4985 LLVM_DEBUG(dbgs() << "Statically extend\n");
4986 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4987 APInt CstVal = IsSExt ? Cst->getValue().sext(width: BitWidth)
4988 : Cst->getValue().zext(width: BitWidth);
4989 TPT.setOperand(Inst: ExtOpnd, Idx: OpIdx, NewVal: ConstantInt::get(Ty: Ext->getType(), V: CstVal));
4990 continue;
4991 }
4992 // UndefValue are typed, so we have to statically sign extend them.
4993 if (isa<UndefValue>(Val: Opnd)) {
4994 LLVM_DEBUG(dbgs() << "Statically extend\n");
4995 TPT.setOperand(Inst: ExtOpnd, Idx: OpIdx, NewVal: UndefValue::get(T: Ext->getType()));
4996 continue;
4997 }
4998
4999 // Otherwise we have to explicitly sign extend the operand.
5000 Value *ValForExtOpnd = IsSExt
5001 ? TPT.createSExt(Inst: ExtOpnd, Opnd, Ty: Ext->getType())
5002 : TPT.createZExt(Inst: ExtOpnd, Opnd, Ty: Ext->getType());
5003 TPT.setOperand(Inst: ExtOpnd, Idx: OpIdx, NewVal: ValForExtOpnd);
5004 Instruction *InstForExtOpnd = dyn_cast<Instruction>(Val: ValForExtOpnd);
5005 if (!InstForExtOpnd)
5006 continue;
5007
5008 if (Exts)
5009 Exts->push_back(Elt: InstForExtOpnd);
5010
5011 CreatedInstsCost += !TLI.isExtFree(I: InstForExtOpnd);
5012 }
5013 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
5014 TPT.eraseInstruction(Inst: Ext);
5015 return ExtOpnd;
5016}
5017
5018/// Check whether or not promoting an instruction to a wider type is profitable.
5019/// \p NewCost gives the cost of extension instructions created by the
5020/// promotion.
5021/// \p OldCost gives the cost of extension instructions before the promotion
5022/// plus the number of instructions that have been
5023/// matched in the addressing mode the promotion.
5024/// \p PromotedOperand is the value that has been promoted.
5025/// \return True if the promotion is profitable, false otherwise.
5026bool AddressingModeMatcher::isPromotionProfitable(
5027 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
5028 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
5029 << '\n');
5030 // The cost of the new extensions is greater than the cost of the
5031 // old extension plus what we folded.
5032 // This is not profitable.
5033 if (NewCost > OldCost)
5034 return false;
5035 if (NewCost < OldCost)
5036 return true;
5037 // The promotion is neutral but it may help folding the sign extension in
5038 // loads for instance.
5039 // Check that we did not create an illegal instruction.
5040 return isPromotedInstructionLegal(TLI, DL, Val: PromotedOperand);
5041}
5042
5043/// Given an instruction or constant expr, see if we can fold the operation
5044/// into the addressing mode. If so, update the addressing mode and return
5045/// true, otherwise return false without modifying AddrMode.
5046/// If \p MovedAway is not NULL, it contains the information of whether or
5047/// not AddrInst has to be folded into the addressing mode on success.
5048/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
5049/// because it has been moved away.
5050/// Thus AddrInst must not be added in the matched instructions.
5051/// This state can happen when AddrInst is a sext, since it may be moved away.
5052/// Therefore, AddrInst may not be valid when MovedAway is true and it must
5053/// not be referenced anymore.
5054bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
5055 unsigned Depth,
5056 bool *MovedAway) {
5057 // Avoid exponential behavior on extremely deep expression trees.
5058 if (Depth >= 5)
5059 return false;
5060
5061 // By default, all matched instructions stay in place.
5062 if (MovedAway)
5063 *MovedAway = false;
5064
5065 switch (Opcode) {
5066 case Instruction::PtrToInt:
5067 // PtrToInt is always a noop, as we know that the int type is pointer sized.
5068 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5069 case Instruction::IntToPtr: {
5070 auto AS = AddrInst->getType()->getPointerAddressSpace();
5071 auto PtrTy = MVT::getIntegerVT(BitWidth: DL.getPointerSizeInBits(AS));
5072 // This inttoptr is a no-op if the integer type is pointer sized.
5073 if (TLI.getValueType(DL, Ty: AddrInst->getOperand(i: 0)->getType()) == PtrTy)
5074 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5075 return false;
5076 }
5077 case Instruction::BitCast:
5078 // BitCast is always a noop, and we can handle it as long as it is
5079 // int->int or pointer->pointer (we don't want int<->fp or something).
5080 if (AddrInst->getOperand(i: 0)->getType()->isIntOrPtrTy() &&
5081 // Don't touch identity bitcasts. These were probably put here by LSR,
5082 // and we don't want to mess around with them. Assume it knows what it
5083 // is doing.
5084 AddrInst->getOperand(i: 0)->getType() != AddrInst->getType())
5085 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5086 return false;
5087 case Instruction::AddrSpaceCast: {
5088 unsigned SrcAS =
5089 AddrInst->getOperand(i: 0)->getType()->getPointerAddressSpace();
5090 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
5091 if (TLI.getTargetMachine().isNoopAddrSpaceCast(DL, SrcAS, DestAS))
5092 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5093 return false;
5094 }
5095 case Instruction::Add: {
5096 // Check to see if we can merge in one operand, then the other. If so, we
5097 // win.
5098 ExtAddrMode BackupAddrMode = AddrMode;
5099 unsigned OldSize = AddrModeInsts.size();
5100 // Start a transaction at this point.
5101 // The LHS may match but not the RHS.
5102 // Therefore, we need a higher level restoration point to undo partially
5103 // matched operation.
5104 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5105 TPT.getRestorationPoint();
5106
5107 // Try to match an integer constant second to increase its chance of ending
5108 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
5109 int First = 0, Second = 1;
5110 if (isa<ConstantInt>(Val: AddrInst->getOperand(i: First))
5111 && !isa<ConstantInt>(Val: AddrInst->getOperand(i: Second)))
5112 std::swap(a&: First, b&: Second);
5113 AddrMode.InBounds = false;
5114 if (matchAddr(Addr: AddrInst->getOperand(i: First), Depth: Depth + 1) &&
5115 matchAddr(Addr: AddrInst->getOperand(i: Second), Depth: Depth + 1))
5116 return true;
5117
5118 // Restore the old addr mode info.
5119 AddrMode = BackupAddrMode;
5120 AddrModeInsts.resize(N: OldSize);
5121 TPT.rollback(Point: LastKnownGood);
5122
5123 // Otherwise this was over-aggressive. Try merging operands in the opposite
5124 // order.
5125 if (matchAddr(Addr: AddrInst->getOperand(i: Second), Depth: Depth + 1) &&
5126 matchAddr(Addr: AddrInst->getOperand(i: First), Depth: Depth + 1))
5127 return true;
5128
5129 // Otherwise we definitely can't merge the ADD in.
5130 AddrMode = BackupAddrMode;
5131 AddrModeInsts.resize(N: OldSize);
5132 TPT.rollback(Point: LastKnownGood);
5133 break;
5134 }
5135 // case Instruction::Or:
5136 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
5137 // break;
5138 case Instruction::Mul:
5139 case Instruction::Shl: {
5140 // Can only handle X*C and X << C.
5141 AddrMode.InBounds = false;
5142 ConstantInt *RHS = dyn_cast<ConstantInt>(Val: AddrInst->getOperand(i: 1));
5143 if (!RHS || RHS->getBitWidth() > 64)
5144 return false;
5145 int64_t Scale = Opcode == Instruction::Shl
5146 ? 1LL << RHS->getLimitedValue(Limit: RHS->getBitWidth() - 1)
5147 : RHS->getSExtValue();
5148
5149 return matchScaledValue(ScaleReg: AddrInst->getOperand(i: 0), Scale, Depth);
5150 }
5151 case Instruction::GetElementPtr: {
5152 // Scan the GEP. We check it if it contains constant offsets and at most
5153 // one variable offset.
5154 int VariableOperand = -1;
5155 unsigned VariableScale = 0;
5156
5157 int64_t ConstantOffset = 0;
5158 gep_type_iterator GTI = gep_type_begin(GEP: AddrInst);
5159 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
5160 if (StructType *STy = GTI.getStructTypeOrNull()) {
5161 const StructLayout *SL = DL.getStructLayout(Ty: STy);
5162 unsigned Idx =
5163 cast<ConstantInt>(Val: AddrInst->getOperand(i))->getZExtValue();
5164 ConstantOffset += SL->getElementOffset(Idx);
5165 } else {
5166 TypeSize TS = GTI.getSequentialElementStride(DL);
5167 if (TS.isNonZero()) {
5168 // The optimisations below currently only work for fixed offsets.
5169 if (TS.isScalable())
5170 return false;
5171 int64_t TypeSize = TS.getFixedValue();
5172 if (ConstantInt *CI =
5173 dyn_cast<ConstantInt>(Val: AddrInst->getOperand(i))) {
5174 const APInt &CVal = CI->getValue();
5175 if (CVal.getSignificantBits() <= 64) {
5176 ConstantOffset += CVal.getSExtValue() * TypeSize;
5177 continue;
5178 }
5179 }
5180 // We only allow one variable index at the moment.
5181 if (VariableOperand != -1)
5182 return false;
5183
5184 // Remember the variable index.
5185 VariableOperand = i;
5186 VariableScale = TypeSize;
5187 }
5188 }
5189 }
5190
5191 // A common case is for the GEP to only do a constant offset. In this case,
5192 // just add it to the disp field and check validity.
5193 if (VariableOperand == -1) {
5194 AddrMode.BaseOffs += ConstantOffset;
5195 if (matchAddr(Addr: AddrInst->getOperand(i: 0), Depth: Depth + 1)) {
5196 if (!cast<GEPOperator>(Val: AddrInst)->isInBounds())
5197 AddrMode.InBounds = false;
5198 return true;
5199 }
5200 AddrMode.BaseOffs -= ConstantOffset;
5201
5202 if (Opts.cgp_split_large_offset_gep && isa<GetElementPtrInst>(Val: AddrInst) &&
5203 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
5204 ConstantOffset > 0) {
5205 // Record GEPs with non-zero offsets as candidates for splitting in
5206 // the event that the offset cannot fit into the r+i addressing mode.
5207 // Simple and common case that only one GEP is used in calculating the
5208 // address for the memory access.
5209 Value *Base = AddrInst->getOperand(i: 0);
5210 auto *BaseI = dyn_cast<Instruction>(Val: Base);
5211 auto *GEP = cast<GetElementPtrInst>(Val: AddrInst);
5212 if (isa<Argument>(Val: Base) || isa<GlobalValue>(Val: Base) ||
5213 (BaseI && !isa<CastInst>(Val: BaseI) &&
5214 !isa<GetElementPtrInst>(Val: BaseI))) {
5215 // Make sure the parent block allows inserting non-PHI instructions
5216 // before the terminator.
5217 BasicBlock *Parent =
5218 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
5219 if (!Parent->getTerminator()->isEHPad())
5220 LargeOffsetGEP = std::make_pair(x&: GEP, y&: ConstantOffset);
5221 }
5222 }
5223
5224 return false;
5225 }
5226
5227 // Save the valid addressing mode in case we can't match.
5228 ExtAddrMode BackupAddrMode = AddrMode;
5229 unsigned OldSize = AddrModeInsts.size();
5230
5231 // See if the scale and offset amount is valid for this target.
5232 AddrMode.BaseOffs += ConstantOffset;
5233 if (!cast<GEPOperator>(Val: AddrInst)->isInBounds())
5234 AddrMode.InBounds = false;
5235
5236 // Match the base operand of the GEP.
5237 if (!matchAddr(Addr: AddrInst->getOperand(i: 0), Depth: Depth + 1)) {
5238 // If it couldn't be matched, just stuff the value in a register.
5239 if (AddrMode.HasBaseReg) {
5240 AddrMode = BackupAddrMode;
5241 AddrModeInsts.resize(N: OldSize);
5242 return false;
5243 }
5244 AddrMode.HasBaseReg = true;
5245 AddrMode.BaseReg = AddrInst->getOperand(i: 0);
5246 }
5247
5248 // Match the remaining variable portion of the GEP.
5249 if (!matchScaledValue(ScaleReg: AddrInst->getOperand(i: VariableOperand), Scale: VariableScale,
5250 Depth)) {
5251 // If it couldn't be matched, try stuffing the base into a register
5252 // instead of matching it, and retrying the match of the scale.
5253 AddrMode = BackupAddrMode;
5254 AddrModeInsts.resize(N: OldSize);
5255 if (AddrMode.HasBaseReg)
5256 return false;
5257 AddrMode.HasBaseReg = true;
5258 AddrMode.BaseReg = AddrInst->getOperand(i: 0);
5259 AddrMode.BaseOffs += ConstantOffset;
5260 if (!matchScaledValue(ScaleReg: AddrInst->getOperand(i: VariableOperand),
5261 Scale: VariableScale, Depth)) {
5262 // If even that didn't work, bail.
5263 AddrMode = BackupAddrMode;
5264 AddrModeInsts.resize(N: OldSize);
5265 return false;
5266 }
5267 }
5268
5269 return true;
5270 }
5271 case Instruction::SExt:
5272 case Instruction::ZExt: {
5273 Instruction *Ext = dyn_cast<Instruction>(Val: AddrInst);
5274 if (!Ext)
5275 return false;
5276
5277 // Try to move this ext out of the way of the addressing mode.
5278 // Ask for a method for doing so.
5279 TypePromotionHelper::Action TPH =
5280 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
5281 if (!TPH)
5282 return false;
5283
5284 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5285 TPT.getRestorationPoint();
5286 unsigned CreatedInstsCost = 0;
5287 unsigned ExtCost = !TLI.isExtFree(I: Ext);
5288 Value *PromotedOperand =
5289 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
5290 // SExt has been moved away.
5291 // Thus either it will be rematched later in the recursive calls or it is
5292 // gone. Anyway, we must not fold it into the addressing mode at this point.
5293 // E.g.,
5294 // op = add opnd, 1
5295 // idx = ext op
5296 // addr = gep base, idx
5297 // is now:
5298 // promotedOpnd = ext opnd <- no match here
5299 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
5300 // addr = gep base, op <- match
5301 if (MovedAway)
5302 *MovedAway = true;
5303
5304 assert(PromotedOperand &&
5305 "TypePromotionHelper should have filtered out those cases");
5306
5307 ExtAddrMode BackupAddrMode = AddrMode;
5308 unsigned OldSize = AddrModeInsts.size();
5309
5310 if (!matchAddr(Addr: PromotedOperand, Depth) ||
5311 // The total of the new cost is equal to the cost of the created
5312 // instructions.
5313 // The total of the old cost is equal to the cost of the extension plus
5314 // what we have saved in the addressing mode.
5315 !isPromotionProfitable(NewCost: CreatedInstsCost,
5316 OldCost: ExtCost + (AddrModeInsts.size() - OldSize),
5317 PromotedOperand)) {
5318 AddrMode = BackupAddrMode;
5319 AddrModeInsts.resize(N: OldSize);
5320 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
5321 TPT.rollback(Point: LastKnownGood);
5322 return false;
5323 }
5324
5325 // SExt has been deleted. Make sure it is not referenced by the AddrMode.
5326 AddrMode.replaceWith(From: Ext, To: PromotedOperand);
5327 return true;
5328 }
5329 case Instruction::Call:
5330 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: AddrInst)) {
5331 if (II->getIntrinsicID() == Intrinsic::threadlocal_address) {
5332 GlobalValue &GV = cast<GlobalValue>(Val&: *II->getArgOperand(i: 0));
5333 if (TLI.addressingModeSupportsTLS(GV))
5334 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5335 }
5336 }
5337 break;
5338 }
5339 return false;
5340}
5341
5342/// If we can, try to add the value of 'Addr' into the current addressing mode.
5343/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
5344/// unmodified. This assumes that Addr is either a pointer type or intptr_t
5345/// for the target.
5346///
5347bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
5348 // Start a transaction at this point that we will rollback if the matching
5349 // fails.
5350 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5351 TPT.getRestorationPoint();
5352 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: Addr)) {
5353 if (CI->getValue().isSignedIntN(N: 64)) {
5354 // Check if the addition would result in a signed overflow.
5355 int64_t Result;
5356 bool Overflow =
5357 AddOverflow(X: AddrMode.BaseOffs, Y: CI->getSExtValue(), Result);
5358 if (!Overflow) {
5359 // Fold in immediates if legal for the target.
5360 AddrMode.BaseOffs = Result;
5361 if (TLI.isLegalAddressingMode(DL, AM: AddrMode, Ty: AccessTy, AddrSpace))
5362 return true;
5363 AddrMode.BaseOffs -= CI->getSExtValue();
5364 }
5365 }
5366 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val: Addr)) {
5367 // If this is a global variable, try to fold it into the addressing mode.
5368 if (!AddrMode.BaseGV) {
5369 AddrMode.BaseGV = GV;
5370 if (TLI.isLegalAddressingMode(DL, AM: AddrMode, Ty: AccessTy, AddrSpace))
5371 return true;
5372 AddrMode.BaseGV = nullptr;
5373 }
5374 } else if (Instruction *I = dyn_cast<Instruction>(Val: Addr)) {
5375 ExtAddrMode BackupAddrMode = AddrMode;
5376 unsigned OldSize = AddrModeInsts.size();
5377
5378 // Check to see if it is possible to fold this operation.
5379 bool MovedAway = false;
5380 if (matchOperationAddr(AddrInst: I, Opcode: I->getOpcode(), Depth, MovedAway: &MovedAway)) {
5381 // This instruction may have been moved away. If so, there is nothing
5382 // to check here.
5383 if (MovedAway)
5384 return true;
5385 // Okay, it's possible to fold this. Check to see if it is actually
5386 // *profitable* to do so. We use a simple cost model to avoid increasing
5387 // register pressure too much.
5388 if (I->hasOneUse() ||
5389 isProfitableToFoldIntoAddressingMode(I, AMBefore&: BackupAddrMode, AMAfter&: AddrMode)) {
5390 AddrModeInsts.push_back(Elt: I);
5391 return true;
5392 }
5393
5394 // It isn't profitable to do this, roll back.
5395 AddrMode = BackupAddrMode;
5396 AddrModeInsts.resize(N: OldSize);
5397 TPT.rollback(Point: LastKnownGood);
5398 }
5399 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: Addr)) {
5400 if (matchOperationAddr(AddrInst: CE, Opcode: CE->getOpcode(), Depth))
5401 return true;
5402 TPT.rollback(Point: LastKnownGood);
5403 } else if (isa<ConstantPointerNull>(Val: Addr)) {
5404 // Null pointer gets folded without affecting the addressing mode.
5405 return true;
5406 }
5407
5408 // Worse case, the target should support [reg] addressing modes. :)
5409 if (!AddrMode.HasBaseReg) {
5410 AddrMode.HasBaseReg = true;
5411 AddrMode.BaseReg = Addr;
5412 // Still check for legality in case the target supports [imm] but not [i+r].
5413 if (TLI.isLegalAddressingMode(DL, AM: AddrMode, Ty: AccessTy, AddrSpace))
5414 return true;
5415 AddrMode.HasBaseReg = false;
5416 AddrMode.BaseReg = nullptr;
5417 }
5418
5419 // If the base register is already taken, see if we can do [r+r].
5420 if (AddrMode.Scale == 0) {
5421 AddrMode.Scale = 1;
5422 AddrMode.ScaledReg = Addr;
5423 if (TLI.isLegalAddressingMode(DL, AM: AddrMode, Ty: AccessTy, AddrSpace))
5424 return true;
5425 AddrMode.Scale = 0;
5426 AddrMode.ScaledReg = nullptr;
5427 }
5428 // Couldn't match.
5429 TPT.rollback(Point: LastKnownGood);
5430 return false;
5431}
5432
5433/// Check to see if all uses of OpVal by the specified inline asm call are due
5434/// to memory operands. If so, return true, otherwise return false.
5435static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
5436 const TargetLowering &TLI,
5437 const TargetRegisterInfo &TRI) {
5438 const Function *F = CI->getFunction();
5439 TargetLowering::AsmOperandInfoVector TargetConstraints =
5440 TLI.ParseConstraints(DL: F->getDataLayout(), TRI: &TRI, Call: *CI);
5441
5442 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5443 // Compute the constraint code and ConstraintType to use.
5444 TLI.ComputeConstraintToUse(OpInfo, Op: SDValue());
5445
5446 // If this asm operand is our Value*, and if it isn't an indirect memory
5447 // operand, we can't fold it! TODO: Also handle C_Address?
5448 if (OpInfo.CallOperandVal == OpVal &&
5449 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
5450 !OpInfo.isIndirect))
5451 return false;
5452 }
5453
5454 return true;
5455}
5456
5457/// Recursively walk all the uses of I until we find a memory use.
5458/// If we find an obviously non-foldable instruction, return true.
5459/// Add accessed addresses and types to MemoryUses.
5460static bool FindAllMemoryUses(
5461 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5462 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
5463 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
5464 BlockFrequencyInfo *BFI, unsigned &SeenInsts, unsigned MaxUsersToScan) {
5465 // If we already considered this instruction, we're done.
5466 if (!ConsideredInsts.insert(Ptr: I).second)
5467 return false;
5468
5469 // If this is an obviously unfoldable instruction, bail out.
5470 if (!MightBeFoldableInst(I))
5471 return true;
5472
5473 // Loop over all the uses, recursively processing them.
5474 for (Use &U : I->uses()) {
5475 // Conservatively return true if we're seeing a large number or a deep chain
5476 // of users. This avoids excessive compilation times in pathological cases.
5477 if (SeenInsts++ >= MaxUsersToScan)
5478 return true;
5479
5480 Instruction *UserI = cast<Instruction>(Val: U.getUser());
5481 if (LoadInst *LI = dyn_cast<LoadInst>(Val: UserI)) {
5482 MemoryUses.push_back(Elt: {&U, LI->getType()});
5483 continue;
5484 }
5485
5486 if (StoreInst *SI = dyn_cast<StoreInst>(Val: UserI)) {
5487 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
5488 return true; // Storing addr, not into addr.
5489 MemoryUses.push_back(Elt: {&U, SI->getValueOperand()->getType()});
5490 continue;
5491 }
5492
5493 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Val: UserI)) {
5494 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5495 return true; // Storing addr, not into addr.
5496 MemoryUses.push_back(Elt: {&U, RMW->getValOperand()->getType()});
5497 continue;
5498 }
5499
5500 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Val: UserI)) {
5501 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5502 return true; // Storing addr, not into addr.
5503 MemoryUses.push_back(Elt: {&U, CmpX->getCompareOperand()->getType()});
5504 continue;
5505 }
5506
5507 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: UserI)) {
5508 SmallVector<Value *, 2> PtrOps;
5509 Type *AccessTy;
5510 if (!TLI.getAddrModeArguments(II, PtrOps, AccessTy))
5511 return true;
5512
5513 if (!find(Range&: PtrOps, Val: U.get()))
5514 return true;
5515
5516 MemoryUses.push_back(Elt: {&U, AccessTy});
5517 continue;
5518 }
5519
5520 if (CallInst *CI = dyn_cast<CallInst>(Val: UserI)) {
5521 if (CI->hasFnAttr(Kind: Attribute::Cold)) {
5522 // If this is a cold call, we can sink the addressing calculation into
5523 // the cold path. See optimizeCallInst
5524 if (!llvm::shouldOptimizeForSize(BB: CI->getParent(), PSI, BFI))
5525 continue;
5526 }
5527
5528 InlineAsm *IA = dyn_cast<InlineAsm>(Val: CI->getCalledOperand());
5529 if (!IA)
5530 return true;
5531
5532 // If this is a memory operand, we're cool, otherwise bail out.
5533 if (!IsOperandAMemoryOperand(CI, IA, OpVal: I, TLI, TRI))
5534 return true;
5535 continue;
5536 }
5537
5538 if (FindAllMemoryUses(I: UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5539 PSI, BFI, SeenInsts, MaxUsersToScan))
5540 return true;
5541 }
5542
5543 return false;
5544}
5545
5546static bool FindAllMemoryUses(
5547 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5548 const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize,
5549 ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, unsigned MaxUsersToScan) {
5550 unsigned SeenInsts = 0;
5551 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5552 return FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5553 PSI, BFI, SeenInsts, MaxUsersToScan);
5554}
5555
5556/// Return true if Val is already known to be live at the use site that we're
5557/// folding it into. If so, there is no cost to include it in the addressing
5558/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5559/// instruction already.
5560bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5561 Value *KnownLive1,
5562 Value *KnownLive2) {
5563 // If Val is either of the known-live values, we know it is live!
5564 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5565 return true;
5566
5567 // All values other than instructions and arguments (e.g. constants) are live.
5568 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5569 return true;
5570
5571 // If Val is a constant sized alloca in the entry block, it is live, this is
5572 // true because it is just a reference to the stack/frame pointer, which is
5573 // live for the whole function.
5574 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5575 if (AI->isStaticAlloca())
5576 return true;
5577
5578 // Check to see if this value is already used in the memory instruction's
5579 // block. If so, it's already live into the block at the very least, so we
5580 // can reasonably fold it.
5581 return Val->isUsedInBasicBlock(BB: MemoryInst->getParent());
5582}
5583
5584/// It is possible for the addressing mode of the machine to fold the specified
5585/// instruction into a load or store that ultimately uses it.
5586/// However, the specified instruction has multiple uses.
5587/// Given this, it may actually increase register pressure to fold it
5588/// into the load. For example, consider this code:
5589///
5590/// X = ...
5591/// Y = X+1
5592/// use(Y) -> nonload/store
5593/// Z = Y+1
5594/// load Z
5595///
5596/// In this case, Y has multiple uses, and can be folded into the load of Z
5597/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5598/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5599/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5600/// number of computations either.
5601///
5602/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5603/// X was live across 'load Z' for other reasons, we actually *would* want to
5604/// fold the addressing mode in the Z case. This would make Y die earlier.
5605bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5606 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5607 if (IgnoreProfitability)
5608 return true;
5609
5610 // AMBefore is the addressing mode before this instruction was folded into it,
5611 // and AMAfter is the addressing mode after the instruction was folded. Get
5612 // the set of registers referenced by AMAfter and subtract out those
5613 // referenced by AMBefore: this is the set of values which folding in this
5614 // address extends the lifetime of.
5615 //
5616 // Note that there are only two potential values being referenced here,
5617 // BaseReg and ScaleReg (global addresses are always available, as are any
5618 // folded immediates).
5619 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5620
5621 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5622 // lifetime wasn't extended by adding this instruction.
5623 if (valueAlreadyLiveAtInst(Val: BaseReg, KnownLive1: AMBefore.BaseReg, KnownLive2: AMBefore.ScaledReg))
5624 BaseReg = nullptr;
5625 if (valueAlreadyLiveAtInst(Val: ScaledReg, KnownLive1: AMBefore.BaseReg, KnownLive2: AMBefore.ScaledReg))
5626 ScaledReg = nullptr;
5627
5628 // If folding this instruction (and it's subexprs) didn't extend any live
5629 // ranges, we're ok with it.
5630 if (!BaseReg && !ScaledReg)
5631 return true;
5632
5633 // If all uses of this instruction can have the address mode sunk into them,
5634 // we can remove the addressing mode and effectively trade one live register
5635 // for another (at worst.) In this context, folding an addressing mode into
5636 // the use is just a particularly nice way of sinking it.
5637 SmallVector<std::pair<Use *, Type *>, 16> MemoryUses;
5638 if (FindAllMemoryUses(I, MemoryUses, TLI, TRI, OptSize, PSI, BFI,
5639 MaxUsersToScan: Opts.cgp_max_address_users_to_scan))
5640 return false; // Has a non-memory, non-foldable use!
5641
5642 // Now that we know that all uses of this instruction are part of a chain of
5643 // computation involving only operations that could theoretically be folded
5644 // into a memory use, loop over each of these memory operation uses and see
5645 // if they could *actually* fold the instruction. The assumption is that
5646 // addressing modes are cheap and that duplicating the computation involved
5647 // many times is worthwhile, even on a fastpath. For sinking candidates
5648 // (i.e. cold call sites), this serves as a way to prevent excessive code
5649 // growth since most architectures have some reasonable small and fast way to
5650 // compute an effective address. (i.e LEA on x86)
5651 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5652 for (const std::pair<Use *, Type *> &Pair : MemoryUses) {
5653 Value *Address = Pair.first->get();
5654 Instruction *UserI = cast<Instruction>(Val: Pair.first->getUser());
5655 Type *AddressAccessTy = Pair.second;
5656 unsigned AS = Address->getType()->getPointerAddressSpace();
5657
5658 // Do a match against the root of this address, ignoring profitability. This
5659 // will tell us if the addressing mode for the memory operation will
5660 // *actually* cover the shared instruction.
5661 ExtAddrMode Result;
5662 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5663 0);
5664 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5665 TPT.getRestorationPoint();
5666 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5667 AddressAccessTy, AS, UserI, Result,
5668 InsertedInsts, PromotedInsts, TPT,
5669 LargeOffsetGEP, OptSize, PSI, BFI, Opts);
5670 Matcher.IgnoreProfitability = true;
5671 bool Success = Matcher.matchAddr(Addr: Address, Depth: 0);
5672 (void)Success;
5673 assert(Success && "Couldn't select *anything*?");
5674
5675 // The match was to check the profitability, the changes made are not
5676 // part of the original matcher. Therefore, they should be dropped
5677 // otherwise the original matcher will not present the right state.
5678 TPT.rollback(Point: LastKnownGood);
5679
5680 // If the match didn't cover I, then it won't be shared by it.
5681 if (!is_contained(Range&: MatchedAddrModeInsts, Element: I))
5682 return false;
5683
5684 MatchedAddrModeInsts.clear();
5685 }
5686
5687 return true;
5688}
5689
5690/// Return true if the specified values are defined in a
5691/// different basic block than BB.
5692static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5693 if (Instruction *I = dyn_cast<Instruction>(Val: V))
5694 return I->getParent() != BB;
5695 return false;
5696}
5697
5698// Find an insert position of Addr for MemoryInst. We can't guarantee MemoryInst
5699// is the first instruction that will use Addr. So we need to find the first
5700// user of Addr in current BB.
5701static BasicBlock::iterator findInsertPos(Value *Addr, Instruction *MemoryInst,
5702 Value *SunkAddr) {
5703 if (Addr->hasOneUse())
5704 return MemoryInst->getIterator();
5705
5706 // We already have a SunkAddr in current BB, but we may need to insert cast
5707 // instruction after it.
5708 if (SunkAddr) {
5709 if (Instruction *AddrInst = dyn_cast<Instruction>(Val: SunkAddr))
5710 return std::next(x: AddrInst->getIterator());
5711 }
5712
5713 // Find the first user of Addr in current BB.
5714 Instruction *Earliest = MemoryInst;
5715 for (User *U : Addr->users()) {
5716 Instruction *UserInst = dyn_cast<Instruction>(Val: U);
5717 if (UserInst && UserInst->getParent() == MemoryInst->getParent()) {
5718 if (isa<PHINode>(Val: UserInst) || UserInst->isDebugOrPseudoInst())
5719 continue;
5720 if (UserInst->comesBefore(Other: Earliest))
5721 Earliest = UserInst;
5722 }
5723 }
5724 return Earliest->getIterator();
5725}
5726
5727/// Sink addressing mode computation immediate before MemoryInst if doing so
5728/// can be done without increasing register pressure. The need for the
5729/// register pressure constraint means this can end up being an all or nothing
5730/// decision for all uses of the same addressing computation.
5731///
5732/// Load and Store Instructions often have addressing modes that can do
5733/// significant amounts of computation. As such, instruction selection will try
5734/// to get the load or store to do as much computation as possible for the
5735/// program. The problem is that isel can only see within a single block. As
5736/// such, we sink as much legal addressing mode work into the block as possible.
5737///
5738/// This method is used to optimize both load/store and inline asms with memory
5739/// operands. It's also used to sink addressing computations feeding into cold
5740/// call sites into their (cold) basic block.
5741///
5742/// The motivation for handling sinking into cold blocks is that doing so can
5743/// both enable other address mode sinking (by satisfying the register pressure
5744/// constraint above), and reduce register pressure globally (by removing the
5745/// addressing mode computation from the fast path entirely.).
5746bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5747 Type *AccessTy, unsigned AddrSpace) {
5748 Value *Repl = Addr;
5749
5750 // Try to collapse single-value PHI nodes. This is necessary to undo
5751 // unprofitable PRE transformations.
5752 SmallVector<Value *, 8> worklist;
5753 SmallPtrSet<Value *, 16> Visited;
5754 worklist.push_back(Elt: Addr);
5755
5756 // Use a worklist to iteratively look through PHI and select nodes, and
5757 // ensure that the addressing mode obtained from the non-PHI/select roots of
5758 // the graph are compatible.
5759 bool PhiOrSelectSeen = false;
5760 SmallVector<Instruction *, 16> AddrModeInsts;
5761 AddressingModeCombiner AddrModes(*DL, Opts, Addr);
5762 TypePromotionTransaction TPT(RemovedInsts);
5763 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5764 TPT.getRestorationPoint();
5765 while (!worklist.empty()) {
5766 Value *V = worklist.pop_back_val();
5767
5768 // We allow traversing cyclic Phi nodes.
5769 // In case of success after this loop we ensure that traversing through
5770 // Phi nodes ends up with all cases to compute address of the form
5771 // BaseGV + Base + Scale * Index + Offset
5772 // where Scale and Offset are constans and BaseGV, Base and Index
5773 // are exactly the same Values in all cases.
5774 // It means that BaseGV, Scale and Offset dominate our memory instruction
5775 // and have the same value as they had in address computation represented
5776 // as Phi. So we can safely sink address computation to memory instruction.
5777 if (!Visited.insert(Ptr: V).second)
5778 continue;
5779
5780 // For a PHI node, push all of its incoming values.
5781 if (PHINode *P = dyn_cast<PHINode>(Val: V)) {
5782 append_range(C&: worklist, R: P->incoming_values());
5783 PhiOrSelectSeen = true;
5784 continue;
5785 }
5786 // Similar for select.
5787 if (SelectInst *SI = dyn_cast<SelectInst>(Val: V)) {
5788 worklist.push_back(Elt: SI->getFalseValue());
5789 worklist.push_back(Elt: SI->getTrueValue());
5790 PhiOrSelectSeen = true;
5791 continue;
5792 }
5793
5794 // For non-PHIs, determine the addressing mode being computed. Note that
5795 // the result may differ depending on what other uses our candidate
5796 // addressing instructions might have.
5797 AddrModeInsts.clear();
5798 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5799 0);
5800 // Defer the query (and possible computation of) the dom tree to point of
5801 // actual use. It's expected that most address matches don't actually need
5802 // the domtree.
5803 auto getDTFn = [this]() -> const DominatorTree & { return getDT(); };
5804 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5805 V, AccessTy, AS: AddrSpace, MemoryInst, AddrModeInsts, TLI: *TLI, LI: *LI, getDTFn,
5806 TRI: *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5807 BFI, Opts);
5808
5809 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5810 if (GEP && !NewGEPBases.count(V: GEP)) {
5811 // If splitting the underlying data structure can reduce the offset of a
5812 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5813 // previously split data structures.
5814 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(Elt: LargeOffsetGEP);
5815 LargeOffsetGEPID.insert(KV: std::make_pair(x&: GEP, y: LargeOffsetGEPID.size()));
5816 }
5817
5818 NewAddrMode.OriginalValue = V;
5819 if (!AddrModes.addNewAddrMode(NewAddrMode))
5820 break;
5821 }
5822
5823 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5824 // or we have multiple but either couldn't combine them or combining them
5825 // wouldn't do anything useful, bail out now.
5826 if (!AddrModes.combineAddrModes()) {
5827 TPT.rollback(Point: LastKnownGood);
5828 return false;
5829 }
5830 bool Modified = TPT.commit();
5831
5832 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5833 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5834
5835 // If all the instructions matched are already in this BB, don't do anything.
5836 // If we saw a Phi node then it is not local definitely, and if we saw a
5837 // select then we want to push the address calculation past it even if it's
5838 // already in this BB.
5839 if (!PhiOrSelectSeen && none_of(Range&: AddrModeInsts, P: [&](Value *V) {
5840 return IsNonLocalValue(V, BB: MemoryInst->getParent());
5841 })) {
5842 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
5843 << "\n");
5844 return Modified;
5845 }
5846
5847 // Now that we determined the addressing expression we want to use and know
5848 // that we have to sink it into this block. Check to see if we have already
5849 // done this for some other load/store instr in this block. If so, reuse
5850 // the computation. Before attempting reuse, check if the address is valid
5851 // as it may have been erased.
5852
5853 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5854
5855 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5856 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5857
5858 // The current BB may be optimized multiple times, we can't guarantee the
5859 // reuse of Addr happens later, call findInsertPos to find an appropriate
5860 // insert position.
5861 auto InsertPos = findInsertPos(Addr, MemoryInst, SunkAddr);
5862
5863 // TODO: Adjust insert point considering (Base|Scaled)Reg if possible.
5864 if (!SunkAddr) {
5865 auto &DT = getDT();
5866 if ((AddrMode.BaseReg && !DT.dominates(Def: AddrMode.BaseReg, User: &*InsertPos)) ||
5867 (AddrMode.ScaledReg && !DT.dominates(Def: AddrMode.ScaledReg, User: &*InsertPos)))
5868 return Modified;
5869 }
5870
5871 IRBuilder<> Builder(InsertPos);
5872
5873 if (SunkAddr) {
5874 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
5875 << " for " << *MemoryInst << "\n");
5876 if (SunkAddr->getType() != Addr->getType()) {
5877 if (SunkAddr->getType()->getPointerAddressSpace() !=
5878 Addr->getType()->getPointerAddressSpace() &&
5879 !DL->isNonIntegralPointerType(Ty: Addr->getType())) {
5880 // There are two reasons the address spaces might not match: a no-op
5881 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5882 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5883 // TODO: allow bitcast between different address space pointers with the
5884 // same size.
5885 SunkAddr = Builder.CreatePtrToInt(V: SunkAddr, DestTy: IntPtrTy, Name: "sunkaddr");
5886 SunkAddr =
5887 Builder.CreateIntToPtr(V: SunkAddr, DestTy: Addr->getType(), Name: "sunkaddr");
5888 } else
5889 SunkAddr = Builder.CreatePointerCast(V: SunkAddr, DestTy: Addr->getType());
5890 }
5891 } else if (valueOr(X: Opts.cgp_addr_sink_using_gep, Default: true) ||
5892 (Opts.cgp_addr_sink_using_gep == BoolOrDefault::Default &&
5893 SubtargetInfo->addrSinkUsingGEPs())) {
5894 // By default, we use the GEP-based method when AA is used later. This
5895 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
5896 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
5897 << " for " << *MemoryInst << "\n");
5898 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
5899
5900 // First, find the pointer.
5901 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
5902 ResultPtr = AddrMode.BaseReg;
5903 AddrMode.BaseReg = nullptr;
5904 }
5905
5906 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
5907 // We can't add more than one pointer together, nor can we scale a
5908 // pointer (both of which seem meaningless).
5909 if (ResultPtr || AddrMode.Scale != 1)
5910 return Modified;
5911
5912 ResultPtr = AddrMode.ScaledReg;
5913 AddrMode.Scale = 0;
5914 }
5915
5916 // It is only safe to sign extend the BaseReg if we know that the math
5917 // required to create it did not overflow before we extend it. Since
5918 // the original IR value was tossed in favor of a constant back when
5919 // the AddrMode was created we need to bail out gracefully if widths
5920 // do not match instead of extending it.
5921 //
5922 // (See below for code to add the scale.)
5923 if (AddrMode.Scale) {
5924 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
5925 if (cast<IntegerType>(Val: IntPtrTy)->getBitWidth() >
5926 cast<IntegerType>(Val: ScaledRegTy)->getBitWidth())
5927 return Modified;
5928 }
5929
5930 GlobalValue *BaseGV = AddrMode.BaseGV;
5931 if (BaseGV != nullptr) {
5932 if (ResultPtr)
5933 return Modified;
5934
5935 if (BaseGV->isThreadLocal()) {
5936 ResultPtr = Builder.CreateThreadLocalAddress(Ptr: BaseGV);
5937 } else {
5938 ResultPtr = BaseGV;
5939 }
5940 }
5941
5942 // If the real base value actually came from an inttoptr, then the matcher
5943 // will look through it and provide only the integer value. In that case,
5944 // use it here.
5945 if (!DL->isNonIntegralPointerType(Ty: Addr->getType())) {
5946 if (!ResultPtr && AddrMode.BaseReg) {
5947 ResultPtr = Builder.CreateIntToPtr(V: AddrMode.BaseReg, DestTy: Addr->getType(),
5948 Name: "sunkaddr");
5949 AddrMode.BaseReg = nullptr;
5950 } else if (!ResultPtr && AddrMode.Scale == 1) {
5951 ResultPtr = Builder.CreateIntToPtr(V: AddrMode.ScaledReg, DestTy: Addr->getType(),
5952 Name: "sunkaddr");
5953 AddrMode.Scale = 0;
5954 }
5955 }
5956
5957 if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
5958 !AddrMode.BaseOffs) {
5959 SunkAddr = Constant::getNullValue(Ty: Addr->getType());
5960 } else if (!ResultPtr) {
5961 return Modified;
5962 } else {
5963 Type *I8PtrTy =
5964 Builder.getPtrTy(AddrSpace: Addr->getType()->getPointerAddressSpace());
5965
5966 // Start with the base register. Do this first so that subsequent address
5967 // matching finds it last, which will prevent it from trying to match it
5968 // as the scaled value in case it happens to be a mul. That would be
5969 // problematic if we've sunk a different mul for the scale, because then
5970 // we'd end up sinking both muls.
5971 if (AddrMode.BaseReg) {
5972 Value *V = AddrMode.BaseReg;
5973 if (V->getType() != IntPtrTy)
5974 V = Builder.CreateIntCast(V, DestTy: IntPtrTy, /*isSigned=*/true, Name: "sunkaddr");
5975
5976 ResultIndex = V;
5977 }
5978
5979 // Add the scale value.
5980 if (AddrMode.Scale) {
5981 Value *V = AddrMode.ScaledReg;
5982 if (V->getType() == IntPtrTy) {
5983 // done.
5984 } else {
5985 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
5986 cast<IntegerType>(V->getType())->getBitWidth() &&
5987 "We can't transform if ScaledReg is too narrow");
5988 V = Builder.CreateTrunc(V, DestTy: IntPtrTy, Name: "sunkaddr");
5989 }
5990
5991 if (AddrMode.Scale != 1)
5992 V = Builder.CreateMul(
5993 LHS: V, RHS: ConstantInt::getSigned(Ty: IntPtrTy, V: AddrMode.Scale), Name: "sunkaddr");
5994 if (ResultIndex)
5995 ResultIndex = Builder.CreateAdd(LHS: ResultIndex, RHS: V, Name: "sunkaddr");
5996 else
5997 ResultIndex = V;
5998 }
5999
6000 // Add in the Base Offset if present.
6001 if (AddrMode.BaseOffs) {
6002 Value *V = ConstantInt::getSigned(Ty: IntPtrTy, V: AddrMode.BaseOffs);
6003 if (ResultIndex) {
6004 // We need to add this separately from the scale above to help with
6005 // SDAG consecutive load/store merging.
6006 if (ResultPtr->getType() != I8PtrTy)
6007 ResultPtr = Builder.CreatePointerCast(V: ResultPtr, DestTy: I8PtrTy);
6008 ResultPtr = Builder.CreatePtrAdd(Ptr: ResultPtr, Offset: ResultIndex, Name: "sunkaddr",
6009 NW: AddrMode.InBounds);
6010 }
6011
6012 ResultIndex = V;
6013 }
6014
6015 if (!ResultIndex) {
6016 auto PtrInst = dyn_cast<Instruction>(Val: ResultPtr);
6017 // We know that we have a pointer without any offsets. If this pointer
6018 // originates from a different basic block than the current one, we
6019 // must be able to recreate it in the current basic block.
6020 // We do not support the recreation of any instructions yet.
6021 if (PtrInst && PtrInst->getParent() != MemoryInst->getParent())
6022 return Modified;
6023 SunkAddr = ResultPtr;
6024 } else {
6025 if (ResultPtr->getType() != I8PtrTy)
6026 ResultPtr = Builder.CreatePointerCast(V: ResultPtr, DestTy: I8PtrTy);
6027 SunkAddr = Builder.CreatePtrAdd(Ptr: ResultPtr, Offset: ResultIndex, Name: "sunkaddr",
6028 NW: AddrMode.InBounds);
6029 }
6030
6031 if (SunkAddr->getType() != Addr->getType()) {
6032 if (SunkAddr->getType()->getPointerAddressSpace() !=
6033 Addr->getType()->getPointerAddressSpace() &&
6034 !DL->isNonIntegralPointerType(Ty: Addr->getType())) {
6035 // There are two reasons the address spaces might not match: a no-op
6036 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
6037 // ptrtoint/inttoptr pair to ensure we match the original semantics.
6038 // TODO: allow bitcast between different address space pointers with
6039 // the same size.
6040 SunkAddr = Builder.CreatePtrToInt(V: SunkAddr, DestTy: IntPtrTy, Name: "sunkaddr");
6041 SunkAddr =
6042 Builder.CreateIntToPtr(V: SunkAddr, DestTy: Addr->getType(), Name: "sunkaddr");
6043 } else
6044 SunkAddr = Builder.CreatePointerCast(V: SunkAddr, DestTy: Addr->getType());
6045 }
6046 }
6047 } else {
6048 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
6049 // non-integral pointers, so in that case bail out now.
6050 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
6051 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
6052 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(Val: BaseTy);
6053 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(Val: ScaleTy);
6054 if (DL->isNonIntegralPointerType(Ty: Addr->getType()) ||
6055 (BasePtrTy && DL->isNonIntegralPointerType(PT: BasePtrTy)) ||
6056 (ScalePtrTy && DL->isNonIntegralPointerType(PT: ScalePtrTy)) ||
6057 (AddrMode.BaseGV &&
6058 DL->isNonIntegralPointerType(PT: AddrMode.BaseGV->getType())))
6059 return Modified;
6060
6061 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6062 << " for " << *MemoryInst << "\n");
6063 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
6064 Value *Result = nullptr;
6065
6066 // Start with the base register. Do this first so that subsequent address
6067 // matching finds it last, which will prevent it from trying to match it
6068 // as the scaled value in case it happens to be a mul. That would be
6069 // problematic if we've sunk a different mul for the scale, because then
6070 // we'd end up sinking both muls.
6071 if (AddrMode.BaseReg) {
6072 Value *V = AddrMode.BaseReg;
6073 if (V->getType()->isPointerTy())
6074 V = Builder.CreatePtrToInt(V, DestTy: IntPtrTy, Name: "sunkaddr");
6075 if (V->getType() != IntPtrTy)
6076 V = Builder.CreateIntCast(V, DestTy: IntPtrTy, /*isSigned=*/true, Name: "sunkaddr");
6077 Result = V;
6078 }
6079
6080 // Add the scale value.
6081 if (AddrMode.Scale) {
6082 Value *V = AddrMode.ScaledReg;
6083 if (V->getType() == IntPtrTy) {
6084 // done.
6085 } else if (V->getType()->isPointerTy()) {
6086 V = Builder.CreatePtrToInt(V, DestTy: IntPtrTy, Name: "sunkaddr");
6087 } else if (cast<IntegerType>(Val: IntPtrTy)->getBitWidth() <
6088 cast<IntegerType>(Val: V->getType())->getBitWidth()) {
6089 V = Builder.CreateTrunc(V, DestTy: IntPtrTy, Name: "sunkaddr");
6090 } else {
6091 // It is only safe to sign extend the BaseReg if we know that the math
6092 // required to create it did not overflow before we extend it. Since
6093 // the original IR value was tossed in favor of a constant back when
6094 // the AddrMode was created we need to bail out gracefully if widths
6095 // do not match instead of extending it.
6096 Instruction *I = dyn_cast_or_null<Instruction>(Val: Result);
6097 if (I && (Result != AddrMode.BaseReg))
6098 I->eraseFromParent();
6099 return Modified;
6100 }
6101 if (AddrMode.Scale != 1)
6102 V = Builder.CreateMul(
6103 LHS: V, RHS: ConstantInt::getSigned(Ty: IntPtrTy, V: AddrMode.Scale), Name: "sunkaddr");
6104 if (Result)
6105 Result = Builder.CreateAdd(LHS: Result, RHS: V, Name: "sunkaddr");
6106 else
6107 Result = V;
6108 }
6109
6110 // Add in the BaseGV if present.
6111 GlobalValue *BaseGV = AddrMode.BaseGV;
6112 if (BaseGV != nullptr) {
6113 Value *BaseGVPtr;
6114 if (BaseGV->isThreadLocal()) {
6115 BaseGVPtr = Builder.CreateThreadLocalAddress(Ptr: BaseGV);
6116 } else {
6117 BaseGVPtr = BaseGV;
6118 }
6119 Value *V = Builder.CreatePtrToInt(V: BaseGVPtr, DestTy: IntPtrTy, Name: "sunkaddr");
6120 if (Result)
6121 Result = Builder.CreateAdd(LHS: Result, RHS: V, Name: "sunkaddr");
6122 else
6123 Result = V;
6124 }
6125
6126 // Add in the Base Offset if present.
6127 if (AddrMode.BaseOffs) {
6128 Value *V = ConstantInt::getSigned(Ty: IntPtrTy, V: AddrMode.BaseOffs);
6129 if (Result)
6130 Result = Builder.CreateAdd(LHS: Result, RHS: V, Name: "sunkaddr");
6131 else
6132 Result = V;
6133 }
6134
6135 if (!Result)
6136 SunkAddr = Constant::getNullValue(Ty: Addr->getType());
6137 else
6138 SunkAddr = Builder.CreateIntToPtr(V: Result, DestTy: Addr->getType(), Name: "sunkaddr");
6139 }
6140
6141 MemoryInst->replaceUsesOfWith(From: Repl, To: SunkAddr);
6142 // Store the newly computed address into the cache. In the case we reused a
6143 // value, this should be idempotent.
6144 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
6145
6146 // If we have no uses, recursively delete the value and all dead instructions
6147 // using it.
6148 if (Repl->use_empty()) {
6149 resetIteratorIfInvalidatedWhileCalling(BB: CurInstIterator->getParent(), f: [&]() {
6150 RecursivelyDeleteTriviallyDeadInstructions(
6151 V: Repl, TLI: TLInfo, MSSAU: nullptr,
6152 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
6153 });
6154 }
6155 ++NumMemoryInsts;
6156 return true;
6157}
6158
6159/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
6160/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
6161/// only handle a 2 operand GEP in the same basic block or a splat constant
6162/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
6163/// index.
6164///
6165/// If the existing GEP has a vector base pointer that is splat, we can look
6166/// through the splat to find the scalar pointer. If we can't find a scalar
6167/// pointer there's nothing we can do.
6168///
6169/// If we have a GEP with more than 2 indices where the middle indices are all
6170/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
6171///
6172/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
6173/// followed by a GEP with an all zeroes vector index. This will enable
6174/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
6175/// zero index.
6176bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
6177 Value *Ptr) {
6178 Value *NewAddr;
6179
6180 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Val: Ptr)) {
6181 // Don't optimize GEPs that don't have indices.
6182 if (!GEP->hasIndices())
6183 return false;
6184
6185 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
6186 // FIXME: We should support this by sinking the GEP.
6187 if (MemoryInst->getParent() != GEP->getParent())
6188 return false;
6189
6190 SmallVector<Value *, 2> Ops(GEP->operands());
6191
6192 bool RewriteGEP = false;
6193
6194 if (Ops[0]->getType()->isVectorTy()) {
6195 Ops[0] = getSplatValue(V: Ops[0]);
6196 if (!Ops[0])
6197 return false;
6198 RewriteGEP = true;
6199 }
6200
6201 unsigned FinalIndex = Ops.size() - 1;
6202
6203 // Ensure all but the last index is 0.
6204 // FIXME: This isn't strictly required. All that's required is that they are
6205 // all scalars or splats.
6206 for (unsigned i = 1; i < FinalIndex; ++i) {
6207 auto *C = dyn_cast<Constant>(Val: Ops[i]);
6208 if (!C)
6209 return false;
6210 if (isa<VectorType>(Val: C->getType()))
6211 C = C->getSplatValue();
6212 auto *CI = dyn_cast_or_null<ConstantInt>(Val: C);
6213 if (!CI || !CI->isZero())
6214 return false;
6215 // Scalarize the index if needed.
6216 Ops[i] = CI;
6217 }
6218
6219 // Try to scalarize the final index.
6220 if (Ops[FinalIndex]->getType()->isVectorTy()) {
6221 if (Value *V = getSplatValue(V: Ops[FinalIndex])) {
6222 auto *C = dyn_cast<ConstantInt>(Val: V);
6223 // Don't scalarize all zeros vector.
6224 if (!C || !C->isZero()) {
6225 Ops[FinalIndex] = V;
6226 RewriteGEP = true;
6227 }
6228 }
6229 }
6230
6231 // If we made any changes or the we have extra operands, we need to generate
6232 // new instructions.
6233 if (!RewriteGEP && Ops.size() == 2)
6234 return false;
6235
6236 auto NumElts = cast<VectorType>(Val: Ptr->getType())->getElementCount();
6237
6238 IRBuilder<> Builder(MemoryInst);
6239
6240 Type *SourceTy = GEP->getSourceElementType();
6241 Type *ScalarIndexTy = DL->getIndexType(PtrTy: Ops[0]->getType()->getScalarType());
6242
6243 // If the final index isn't a vector, emit a scalar GEP containing all ops
6244 // and a vector GEP with all zeroes final index.
6245 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
6246 NewAddr = Builder.CreateGEP(Ty: SourceTy, Ptr: Ops[0], IdxList: ArrayRef(Ops).drop_front());
6247 auto *IndexTy = VectorType::get(ElementType: ScalarIndexTy, EC: NumElts);
6248 auto *SecondTy = GetElementPtrInst::getIndexedType(
6249 Ty: SourceTy, IdxList: ArrayRef(Ops).drop_front());
6250 NewAddr =
6251 Builder.CreateGEP(Ty: SecondTy, Ptr: NewAddr, IdxList: Constant::getNullValue(Ty: IndexTy));
6252 } else {
6253 Value *Base = Ops[0];
6254 Value *Index = Ops[FinalIndex];
6255
6256 // Create a scalar GEP if there are more than 2 operands.
6257 if (Ops.size() != 2) {
6258 // Replace the last index with 0.
6259 Ops[FinalIndex] =
6260 Constant::getNullValue(Ty: Ops[FinalIndex]->getType()->getScalarType());
6261 Base = Builder.CreateGEP(Ty: SourceTy, Ptr: Base, IdxList: ArrayRef(Ops).drop_front());
6262 SourceTy = GetElementPtrInst::getIndexedType(
6263 Ty: SourceTy, IdxList: ArrayRef(Ops).drop_front());
6264 }
6265
6266 // Now create the GEP with scalar pointer and vector index.
6267 NewAddr = Builder.CreateGEP(Ty: SourceTy, Ptr: Base, IdxList: Index);
6268 }
6269 } else if (!isa<Constant>(Val: Ptr)) {
6270 // Not a GEP, maybe its a splat and we can create a GEP to enable
6271 // SelectionDAGBuilder to use it as a uniform base.
6272 Value *V = getSplatValue(V: Ptr);
6273 if (!V)
6274 return false;
6275
6276 auto NumElts = cast<VectorType>(Val: Ptr->getType())->getElementCount();
6277
6278 IRBuilder<> Builder(MemoryInst);
6279
6280 // Emit a vector GEP with a scalar pointer and all 0s vector index.
6281 Type *ScalarIndexTy = DL->getIndexType(PtrTy: V->getType()->getScalarType());
6282 auto *IndexTy = VectorType::get(ElementType: ScalarIndexTy, EC: NumElts);
6283 Type *ScalarTy;
6284 if (cast<IntrinsicInst>(Val: MemoryInst)->getIntrinsicID() ==
6285 Intrinsic::masked_gather) {
6286 ScalarTy = MemoryInst->getType()->getScalarType();
6287 } else {
6288 assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6289 Intrinsic::masked_scatter);
6290 ScalarTy = MemoryInst->getOperand(i: 0)->getType()->getScalarType();
6291 }
6292 NewAddr = Builder.CreateGEP(Ty: ScalarTy, Ptr: V, IdxList: Constant::getNullValue(Ty: IndexTy));
6293 } else {
6294 // Constant, SelectionDAGBuilder knows to check if its a splat.
6295 return false;
6296 }
6297
6298 MemoryInst->replaceUsesOfWith(From: Ptr, To: NewAddr);
6299
6300 // If we have no uses, recursively delete the value and all dead instructions
6301 // using it.
6302 if (Ptr->use_empty())
6303 RecursivelyDeleteTriviallyDeadInstructions(
6304 V: Ptr, TLI: TLInfo, MSSAU: nullptr,
6305 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
6306
6307 return true;
6308}
6309
6310// This is a helper for CodeGenPrepare::optimizeMulWithOverflow.
6311// Check the pattern we are interested in where there are maximum 2 uses
6312// of the intrinsic which are the extract instructions.
6313static bool matchOverflowPattern(Instruction *&I, ExtractValueInst *&MulExtract,
6314 ExtractValueInst *&OverflowExtract) {
6315 // Bail out if it's more than 2 users:
6316 if (I->hasNUsesOrMore(N: 3))
6317 return false;
6318
6319 for (User *U : I->users()) {
6320 auto *Extract = dyn_cast<ExtractValueInst>(Val: U);
6321 if (!Extract || Extract->getNumIndices() != 1)
6322 return false;
6323
6324 unsigned Index = Extract->getIndices()[0];
6325 if (Index == 0)
6326 MulExtract = Extract;
6327 else if (Index == 1)
6328 OverflowExtract = Extract;
6329 else
6330 return false;
6331 }
6332 return true;
6333}
6334
6335// Rewrite the mul_with_overflow intrinsic by checking if both of the
6336// operands' value ranges are within the legal type. If so, we can optimize the
6337// multiplication algorithm. This code is supposed to be written during the step
6338// of type legalization, but given that we need to reconstruct the IR which is
6339// not doable there, we do it here.
6340// The IR after the optimization will look like:
6341// entry:
6342// if signed:
6343// ( (lhs_lo>>BW-1) ^ lhs_hi) || ( (rhs_lo>>BW-1) ^ rhs_hi) ? overflow,
6344// overflow_no
6345// else:
6346// (lhs_hi != 0) || (rhs_hi != 0) ? overflow, overflow_no
6347// overflow_no:
6348// overflow:
6349// overflow.res:
6350// \returns true if optimization was applied
6351// TODO: This optimization can be further improved to optimize branching on
6352// overflow where the 'overflow_no' BB can branch directly to the false
6353// successor of overflow, but that would add additional complexity so we leave
6354// it for future work.
6355bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
6356 ModifyDT &ModifiedDT) {
6357 // Check if target supports this optimization.
6358 if (!TLI->shouldOptimizeMulOverflowWithZeroHighBits(
6359 Context&: I->getContext(),
6360 VT: TLI->getValueType(DL: *DL, Ty: I->getType()->getContainedType(i: 0))))
6361 return false;
6362
6363 ExtractValueInst *MulExtract = nullptr, *OverflowExtract = nullptr;
6364 if (!matchOverflowPattern(I, MulExtract, OverflowExtract))
6365 return false;
6366
6367 // Keep track of the instruction to stop reoptimizing it again.
6368 InsertedInsts.insert(Ptr: I);
6369
6370 Value *LHS = I->getOperand(i: 0);
6371 Value *RHS = I->getOperand(i: 1);
6372 Type *Ty = LHS->getType();
6373 unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
6374 Type *LegalTy = Ty->getWithNewBitWidth(NewBitWidth: VTHalfBitWidth);
6375
6376 // New BBs:
6377 BasicBlock *OverflowEntryBB =
6378 splitBlockBefore(Old: I->getParent(), SplitPt: I, DTU, LI, MSSAU: nullptr, BBName: "");
6379 OverflowEntryBB->takeName(V: I->getParent());
6380 // Keep the 'br' instruction that is generated as a result of the split to be
6381 // erased/replaced later.
6382 Instruction *OldTerminator = OverflowEntryBB->getTerminator();
6383 BasicBlock *NoOverflowBB =
6384 BasicBlock::Create(Context&: I->getContext(), Name: "overflow.no", Parent: I->getFunction());
6385 NoOverflowBB->moveAfter(MovePos: OverflowEntryBB);
6386 BasicBlock *OverflowBB =
6387 BasicBlock::Create(Context&: I->getContext(), Name: "overflow", Parent: I->getFunction());
6388 OverflowBB->moveAfter(MovePos: NoOverflowBB);
6389
6390 // BB overflow.entry:
6391 IRBuilder<> Builder(OverflowEntryBB);
6392 // Extract low and high halves of LHS:
6393 Value *LoLHS = Builder.CreateTrunc(V: LHS, DestTy: LegalTy, Name: "lo.lhs");
6394 Value *HiLHS = Builder.CreateLShr(LHS, RHS: VTHalfBitWidth, Name: "lhs.lsr");
6395 HiLHS = Builder.CreateTrunc(V: HiLHS, DestTy: LegalTy, Name: "hi.lhs");
6396
6397 // Extract low and high halves of RHS:
6398 Value *LoRHS = Builder.CreateTrunc(V: RHS, DestTy: LegalTy, Name: "lo.rhs");
6399 Value *HiRHS = Builder.CreateLShr(LHS: RHS, RHS: VTHalfBitWidth, Name: "rhs.lsr");
6400 HiRHS = Builder.CreateTrunc(V: HiRHS, DestTy: LegalTy, Name: "hi.rhs");
6401
6402 Value *IsAnyBitTrue;
6403 if (IsSigned) {
6404 Value *SignLoLHS =
6405 Builder.CreateAShr(LHS: LoLHS, RHS: VTHalfBitWidth - 1, Name: "sign.lo.lhs");
6406 Value *SignLoRHS =
6407 Builder.CreateAShr(LHS: LoRHS, RHS: VTHalfBitWidth - 1, Name: "sign.lo.rhs");
6408 Value *XorLHS = Builder.CreateXor(LHS: HiLHS, RHS: SignLoLHS);
6409 Value *XorRHS = Builder.CreateXor(LHS: HiRHS, RHS: SignLoRHS);
6410 Value *Or = Builder.CreateOr(LHS: XorLHS, RHS: XorRHS, Name: "or.lhs.rhs");
6411 IsAnyBitTrue = Builder.CreateCmp(Pred: ICmpInst::ICMP_NE, LHS: Or,
6412 RHS: ConstantInt::getNullValue(Ty: Or->getType()));
6413 } else {
6414 Value *CmpLHS = Builder.CreateCmp(Pred: ICmpInst::ICMP_NE, LHS: HiLHS,
6415 RHS: ConstantInt::getNullValue(Ty: LegalTy));
6416 Value *CmpRHS = Builder.CreateCmp(Pred: ICmpInst::ICMP_NE, LHS: HiRHS,
6417 RHS: ConstantInt::getNullValue(Ty: LegalTy));
6418 IsAnyBitTrue = Builder.CreateOr(LHS: CmpLHS, RHS: CmpRHS, Name: "or.lhs.rhs");
6419 }
6420 Builder.CreateCondBr(Cond: IsAnyBitTrue, True: OverflowBB, False: NoOverflowBB);
6421
6422 // BB overflow.no:
6423 Builder.SetInsertPoint(NoOverflowBB);
6424 Value *ExtLoLHS, *ExtLoRHS;
6425 if (IsSigned) {
6426 ExtLoLHS = Builder.CreateSExt(V: LoLHS, DestTy: Ty, Name: "lo.lhs.ext");
6427 ExtLoRHS = Builder.CreateSExt(V: LoRHS, DestTy: Ty, Name: "lo.rhs.ext");
6428 } else {
6429 ExtLoLHS = Builder.CreateZExt(V: LoLHS, DestTy: Ty, Name: "lo.lhs.ext");
6430 ExtLoRHS = Builder.CreateZExt(V: LoRHS, DestTy: Ty, Name: "lo.rhs.ext");
6431 }
6432
6433 Value *Mul = Builder.CreateMul(LHS: ExtLoLHS, RHS: ExtLoRHS, Name: "mul.overflow.no");
6434
6435 // Create the 'overflow.res' BB to merge the results of
6436 // the two paths:
6437 BasicBlock *OverflowResBB = I->getParent();
6438 OverflowResBB->setName("overflow.res");
6439
6440 // BB overflow.no: jump to overflow.res BB
6441 Builder.CreateBr(Dest: OverflowResBB);
6442 // No we don't need the old terminator in overflow.entry BB, erase it:
6443 OldTerminator->eraseFromParent();
6444
6445 // BB overflow.res:
6446 Builder.SetInsertPoint(OverflowResBB->getFirstInsertionPt());
6447 // Create PHI nodes to merge results from no.overflow BB and overflow BB to
6448 // replace the extract instructions.
6449 PHINode *OverflowResPHI = Builder.CreatePHI(Ty, NumReservedValues: 2),
6450 *OverflowFlagPHI =
6451 Builder.CreatePHI(Ty: IntegerType::getInt1Ty(C&: I->getContext()), NumReservedValues: 2);
6452
6453 // Add the incoming values from no.overflow BB and later from overflow BB.
6454 OverflowResPHI->addIncoming(V: Mul, BB: NoOverflowBB);
6455 OverflowFlagPHI->addIncoming(V: ConstantInt::getFalse(Context&: I->getContext()),
6456 BB: NoOverflowBB);
6457
6458 // Replace all users of MulExtract and OverflowExtract to use the PHI nodes.
6459 if (MulExtract) {
6460 MulExtract->replaceAllUsesWith(V: OverflowResPHI);
6461 MulExtract->eraseFromParent();
6462 }
6463 if (OverflowExtract) {
6464 OverflowExtract->replaceAllUsesWith(V: OverflowFlagPHI);
6465 OverflowExtract->eraseFromParent();
6466 }
6467
6468 // Remove the intrinsic from parent (overflow.res BB) as it will be part of
6469 // overflow BB
6470 I->removeFromParent();
6471 // BB overflow:
6472 I->insertInto(ParentBB: OverflowBB, It: OverflowBB->end());
6473 Builder.SetInsertPoint(OverflowBB->end());
6474 Value *MulOverflow = Builder.CreateExtractValue(Agg: I, Idxs: {0}, Name: "mul.overflow");
6475 Value *OverflowFlag = Builder.CreateExtractValue(Agg: I, Idxs: {1}, Name: "overflow.flag");
6476 Builder.CreateBr(Dest: OverflowResBB);
6477
6478 // Add The Extracted values to the PHINodes in the overflow.res BB.
6479 OverflowResPHI->addIncoming(V: MulOverflow, BB: OverflowBB);
6480 OverflowFlagPHI->addIncoming(V: OverflowFlag, BB: OverflowBB);
6481
6482 DTU->applyUpdates(Updates: {{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
6483 {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
6484 {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
6485 {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
6486 {DominatorTree::Insert, OverflowBB, OverflowResBB}});
6487
6488 ModifiedDT = ModifyDT::ModifyBBDT;
6489 return true;
6490}
6491
6492/// If there are any memory operands, use OptimizeMemoryInst to sink their
6493/// address computing into the block when possible / profitable.
6494bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
6495 bool MadeChange = false;
6496
6497 const TargetRegisterInfo *TRI =
6498 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
6499 TargetLowering::AsmOperandInfoVector TargetConstraints =
6500 TLI->ParseConstraints(DL: *DL, TRI, Call: *CS);
6501 unsigned ArgNo = 0;
6502 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
6503 // Compute the constraint code and ConstraintType to use.
6504 TLI->ComputeConstraintToUse(OpInfo, Op: SDValue());
6505
6506 // TODO: Also handle C_Address?
6507 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6508 OpInfo.isIndirect) {
6509 Value *OpVal = CS->getArgOperand(i: ArgNo++);
6510 MadeChange |= optimizeMemoryInst(MemoryInst: CS, Addr: OpVal, AccessTy: OpVal->getType(), AddrSpace: ~0u);
6511 } else if (OpInfo.Type == InlineAsm::isInput)
6512 ArgNo++;
6513 }
6514
6515 return MadeChange;
6516}
6517
6518/// Check if all the uses of \p Val are equivalent (or free) zero or
6519/// sign extensions.
6520static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
6521 assert(!Val->use_empty() && "Input must have at least one use");
6522 const Instruction *FirstUser = cast<Instruction>(Val: *Val->user_begin());
6523 bool IsSExt = isa<SExtInst>(Val: FirstUser);
6524 Type *ExtTy = FirstUser->getType();
6525 for (const User *U : Val->users()) {
6526 const Instruction *UI = cast<Instruction>(Val: U);
6527 if ((IsSExt && !isa<SExtInst>(Val: UI)) || (!IsSExt && !isa<ZExtInst>(Val: UI)))
6528 return false;
6529 Type *CurTy = UI->getType();
6530 // Same input and output types: Same instruction after CSE.
6531 if (CurTy == ExtTy)
6532 continue;
6533
6534 // If IsSExt is true, we are in this situation:
6535 // a = Val
6536 // b = sext ty1 a to ty2
6537 // c = sext ty1 a to ty3
6538 // Assuming ty2 is shorter than ty3, this could be turned into:
6539 // a = Val
6540 // b = sext ty1 a to ty2
6541 // c = sext ty2 b to ty3
6542 // However, the last sext is not free.
6543 if (IsSExt)
6544 return false;
6545
6546 // This is a ZExt, maybe this is free to extend from one type to another.
6547 // In that case, we would not account for a different use.
6548 Type *NarrowTy;
6549 Type *LargeTy;
6550 if (ExtTy->getScalarType()->getIntegerBitWidth() >
6551 CurTy->getScalarType()->getIntegerBitWidth()) {
6552 NarrowTy = CurTy;
6553 LargeTy = ExtTy;
6554 } else {
6555 NarrowTy = ExtTy;
6556 LargeTy = CurTy;
6557 }
6558
6559 if (!TLI.isZExtFree(FromTy: NarrowTy, ToTy: LargeTy))
6560 return false;
6561 }
6562 // All uses are the same or can be derived from one another for free.
6563 return true;
6564}
6565
6566/// Try to speculatively promote extensions in \p Exts and continue
6567/// promoting through newly promoted operands recursively as far as doing so is
6568/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
6569/// When some promotion happened, \p TPT contains the proper state to revert
6570/// them.
6571///
6572/// \return true if some promotion happened, false otherwise.
6573bool CodeGenPrepare::tryToPromoteExts(
6574 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
6575 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
6576 unsigned CreatedInstsCost) {
6577 bool Promoted = false;
6578
6579 // Iterate over all the extensions to try to promote them.
6580 for (auto *I : Exts) {
6581 // Early check if we directly have ext(load).
6582 if (isa<LoadInst>(Val: I->getOperand(i: 0))) {
6583 ProfitablyMovedExts.push_back(Elt: I);
6584 continue;
6585 }
6586
6587 // Check whether or not we want to do any promotion. The reason we have
6588 // this check inside the for loop is to catch the case where an extension
6589 // is directly fed by a load because in such case the extension can be moved
6590 // up without any promotion on its operands.
6591 if (!TLI->enableExtLdPromotion() || !Opts.cgp_ext_ld_promotion)
6592 return false;
6593
6594 // Get the action to perform the promotion.
6595 TypePromotionHelper::Action TPH =
6596 TypePromotionHelper::getAction(Ext: I, InsertedInsts, TLI: *TLI, PromotedInsts);
6597 // Check if we can promote.
6598 if (!TPH) {
6599 // Save the current extension as we cannot move up through its operand.
6600 ProfitablyMovedExts.push_back(Elt: I);
6601 continue;
6602 }
6603
6604 // Save the current state.
6605 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6606 TPT.getRestorationPoint();
6607 SmallVector<Instruction *, 4> NewExts;
6608 unsigned NewCreatedInstsCost = 0;
6609 unsigned ExtCost = !TLI->isExtFree(I);
6610 // Promote.
6611 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
6612 &NewExts, nullptr, *TLI);
6613 assert(PromotedVal &&
6614 "TypePromotionHelper should have filtered out those cases");
6615
6616 // We would be able to merge only one extension in a load.
6617 // Therefore, if we have more than 1 new extension we heuristically
6618 // cut this search path, because it means we degrade the code quality.
6619 // With exactly 2, the transformation is neutral, because we will merge
6620 // one extension but leave one. However, we optimistically keep going,
6621 // because the new extension may be removed too. Also avoid replacing a
6622 // single free extension with multiple extensions, as this increases the
6623 // number of IR instructions while not providing any savings.
6624 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
6625 // FIXME: It would be possible to propagate a negative value instead of
6626 // conservatively ceiling it to 0.
6627 TotalCreatedInstsCost =
6628 std::max(a: (long long)0, b: (TotalCreatedInstsCost - ExtCost));
6629 if (!Opts.cgp_stress_ext_ld_promotion &&
6630 (TotalCreatedInstsCost > 1 ||
6631 !isPromotedInstructionLegal(TLI: *TLI, DL: *DL, Val: PromotedVal) ||
6632 (ExtCost == 0 && NewExts.size() > 1))) {
6633 // This promotion is not profitable, rollback to the previous state, and
6634 // save the current extension in ProfitablyMovedExts as the latest
6635 // speculative promotion turned out to be unprofitable.
6636 TPT.rollback(Point: LastKnownGood);
6637 ProfitablyMovedExts.push_back(Elt: I);
6638 continue;
6639 }
6640 // Continue promoting NewExts as far as doing so is profitable.
6641 SmallVector<Instruction *, 2> NewlyMovedExts;
6642 (void)tryToPromoteExts(TPT, Exts: NewExts, ProfitablyMovedExts&: NewlyMovedExts, CreatedInstsCost: TotalCreatedInstsCost);
6643 bool NewPromoted = false;
6644 for (auto *ExtInst : NewlyMovedExts) {
6645 Instruction *MovedExt = cast<Instruction>(Val: ExtInst);
6646 Value *ExtOperand = MovedExt->getOperand(i: 0);
6647 // If we have reached to a load, we need this extra profitability check
6648 // as it could potentially be merged into an ext(load).
6649 if (isa<LoadInst>(Val: ExtOperand) &&
6650 !(Opts.cgp_stress_ext_ld_promotion ||
6651 NewCreatedInstsCost <= ExtCost ||
6652 (ExtOperand->hasOneUse() || hasSameExtUse(Val: ExtOperand, TLI: *TLI))))
6653 continue;
6654
6655 ProfitablyMovedExts.push_back(Elt: MovedExt);
6656 NewPromoted = true;
6657 }
6658
6659 // If none of speculative promotions for NewExts is profitable, rollback
6660 // and save the current extension (I) as the last profitable extension.
6661 if (!NewPromoted) {
6662 TPT.rollback(Point: LastKnownGood);
6663 ProfitablyMovedExts.push_back(Elt: I);
6664 continue;
6665 }
6666 // The promotion is profitable.
6667 Promoted = true;
6668 }
6669 return Promoted;
6670}
6671
6672/// Merging redundant sexts when one is dominating the other.
6673bool CodeGenPrepare::mergeSExts(Function &F) {
6674 bool Changed = false;
6675 for (auto &Entry : ValToSExtendedUses) {
6676 SExts &Insts = Entry.second;
6677 SExts CurPts;
6678 for (Instruction *Inst : Insts) {
6679 if (RemovedInsts.count(Ptr: Inst) || !isa<SExtInst>(Val: Inst) ||
6680 Inst->getOperand(i: 0) != Entry.first)
6681 continue;
6682 bool inserted = false;
6683 for (auto &Pt : CurPts) {
6684 if (getDT().dominates(Def: Inst, User: Pt)) {
6685 replaceAllUsesWith(Old: Pt, New: Inst, FreshBBs, IsHuge: IsHugeFunc);
6686 RemovedInsts.insert(Ptr: Pt);
6687 Pt->removeFromParent();
6688 Pt = Inst;
6689 inserted = true;
6690 Changed = true;
6691 break;
6692 }
6693 if (!getDT().dominates(Def: Pt, User: Inst))
6694 // Give up if we need to merge in a common dominator as the
6695 // experiments show it is not profitable.
6696 continue;
6697 replaceAllUsesWith(Old: Inst, New: Pt, FreshBBs, IsHuge: IsHugeFunc);
6698 RemovedInsts.insert(Ptr: Inst);
6699 Inst->removeFromParent();
6700 inserted = true;
6701 Changed = true;
6702 break;
6703 }
6704 if (!inserted)
6705 CurPts.push_back(Elt: Inst);
6706 }
6707 }
6708 return Changed;
6709}
6710
6711// Splitting large data structures so that the GEPs accessing them can have
6712// smaller offsets so that they can be sunk to the same blocks as their users.
6713// For example, a large struct starting from %base is split into two parts
6714// where the second part starts from %new_base.
6715//
6716// Before:
6717// BB0:
6718// %base =
6719//
6720// BB1:
6721// %gep0 = gep %base, off0
6722// %gep1 = gep %base, off1
6723// %gep2 = gep %base, off2
6724//
6725// BB2:
6726// %load1 = load %gep0
6727// %load2 = load %gep1
6728// %load3 = load %gep2
6729//
6730// After:
6731// BB0:
6732// %base =
6733// %new_base = gep %base, off0
6734//
6735// BB1:
6736// %new_gep0 = %new_base
6737// %new_gep1 = gep %new_base, off1 - off0
6738// %new_gep2 = gep %new_base, off2 - off0
6739//
6740// BB2:
6741// %load1 = load i32, i32* %new_gep0
6742// %load2 = load i32, i32* %new_gep1
6743// %load3 = load i32, i32* %new_gep2
6744//
6745// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
6746// their offsets are smaller enough to fit into the addressing mode.
6747bool CodeGenPrepare::splitLargeGEPOffsets() {
6748 bool Changed = false;
6749 for (auto &Entry : LargeOffsetGEPMap) {
6750 Value *OldBase = Entry.first;
6751 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
6752 &LargeOffsetGEPs = Entry.second;
6753 auto compareGEPOffset =
6754 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
6755 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
6756 if (LHS.first == RHS.first)
6757 return false;
6758 if (LHS.second != RHS.second)
6759 return LHS.second < RHS.second;
6760 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
6761 };
6762 // Sorting all the GEPs of the same data structures based on the offsets.
6763 llvm::sort(C&: LargeOffsetGEPs, Comp: compareGEPOffset);
6764 LargeOffsetGEPs.erase(CS: llvm::unique(R&: LargeOffsetGEPs), CE: LargeOffsetGEPs.end());
6765 // Skip if all the GEPs have the same offsets.
6766 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
6767 continue;
6768 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
6769 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
6770 Value *NewBaseGEP = nullptr;
6771
6772 auto createNewBase = [&](int64_t BaseOffset, Value *OldBase,
6773 GetElementPtrInst *GEP) {
6774 LLVMContext &Ctx = GEP->getContext();
6775 Type *PtrIdxTy = DL->getIndexType(PtrTy: GEP->getType());
6776 Type *I8PtrTy =
6777 PointerType::get(C&: Ctx, AddressSpace: GEP->getType()->getPointerAddressSpace());
6778
6779 BasicBlock::iterator NewBaseInsertPt;
6780 BasicBlock *NewBaseInsertBB;
6781 if (auto *BaseI = dyn_cast<Instruction>(Val: OldBase)) {
6782 // If the base of the struct is an instruction, the new base will be
6783 // inserted close to it.
6784 NewBaseInsertBB = BaseI->getParent();
6785 if (isa<PHINode>(Val: BaseI))
6786 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6787 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Val: BaseI)) {
6788 NewBaseInsertBB =
6789 SplitEdge(From: NewBaseInsertBB, To: Invoke->getNormalDest(), DT: &getDT(), LI);
6790 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6791 } else
6792 NewBaseInsertPt = std::next(x: BaseI->getIterator());
6793 } else {
6794 // If the current base is an argument or global value, the new base
6795 // will be inserted to the entry block.
6796 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
6797 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6798 }
6799 IRBuilder<> NewBaseBuilder(NewBaseInsertPt);
6800 // Create a new base.
6801 // TODO: Avoid implicit trunc?
6802 // See https://github.com/llvm/llvm-project/issues/112510.
6803 Value *BaseIndex =
6804 ConstantInt::getSigned(Ty: PtrIdxTy, V: BaseOffset, /*ImplicitTrunc=*/true);
6805 NewBaseGEP = OldBase;
6806 if (NewBaseGEP->getType() != I8PtrTy)
6807 NewBaseGEP = NewBaseBuilder.CreatePointerCast(V: NewBaseGEP, DestTy: I8PtrTy);
6808 NewBaseGEP =
6809 NewBaseBuilder.CreatePtrAdd(Ptr: NewBaseGEP, Offset: BaseIndex, Name: "splitgep");
6810 NewGEPBases.insert(V: NewBaseGEP);
6811 return;
6812 };
6813
6814 // Check whether all the offsets can be encoded with prefered common base.
6815 if (int64_t PreferBase = TLI->getPreferredLargeGEPBaseOffset(
6816 MinOffset: LargeOffsetGEPs.front().second, MaxOffset: LargeOffsetGEPs.back().second)) {
6817 BaseOffset = PreferBase;
6818 // Create a new base if the offset of the BaseGEP can be decoded with one
6819 // instruction.
6820 createNewBase(BaseOffset, OldBase, BaseGEP);
6821 }
6822
6823 auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
6824 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
6825 GetElementPtrInst *GEP = LargeOffsetGEP->first;
6826 int64_t Offset = LargeOffsetGEP->second;
6827 if (Offset != BaseOffset) {
6828 TargetLowering::AddrMode AddrMode;
6829 AddrMode.HasBaseReg = true;
6830 AddrMode.BaseOffs = Offset - BaseOffset;
6831 // The result type of the GEP might not be the type of the memory
6832 // access.
6833 if (!TLI->isLegalAddressingMode(DL: *DL, AM: AddrMode,
6834 Ty: GEP->getResultElementType(),
6835 AddrSpace: GEP->getAddressSpace())) {
6836 // We need to create a new base if the offset to the current base is
6837 // too large to fit into the addressing mode. So, a very large struct
6838 // may be split into several parts.
6839 BaseGEP = GEP;
6840 BaseOffset = Offset;
6841 NewBaseGEP = nullptr;
6842 }
6843 }
6844
6845 // Generate a new GEP to replace the current one.
6846 Type *PtrIdxTy = DL->getIndexType(PtrTy: GEP->getType());
6847
6848 if (!NewBaseGEP) {
6849 // Create a new base if we don't have one yet. Find the insertion
6850 // pointer for the new base first.
6851 createNewBase(BaseOffset, OldBase, GEP);
6852 }
6853
6854 IRBuilder<> Builder(GEP);
6855 Value *NewGEP = NewBaseGEP;
6856 if (Offset != BaseOffset) {
6857 // Calculate the new offset for the new GEP.
6858 Value *Index = ConstantInt::get(Ty: PtrIdxTy, V: Offset - BaseOffset);
6859 NewGEP = Builder.CreatePtrAdd(Ptr: NewBaseGEP, Offset: Index);
6860 }
6861 replaceAllUsesWith(Old: GEP, New: NewGEP, FreshBBs, IsHuge: IsHugeFunc);
6862 LargeOffsetGEPID.erase(Val: GEP);
6863 LargeOffsetGEP = LargeOffsetGEPs.erase(CI: LargeOffsetGEP);
6864 GEP->eraseFromParent();
6865 Changed = true;
6866 }
6867 }
6868 return Changed;
6869}
6870
6871bool CodeGenPrepare::optimizePhiType(
6872 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
6873 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
6874 // We are looking for a collection on interconnected phi nodes that together
6875 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
6876 // are of the same type. Convert the whole set of nodes to the type of the
6877 // bitcast.
6878 Type *PhiTy = I->getType();
6879 Type *ConvertTy = nullptr;
6880 if (Visited.count(Ptr: I) ||
6881 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
6882 return false;
6883
6884 SmallVector<Instruction *, 4> Worklist;
6885 Worklist.push_back(Elt: cast<Instruction>(Val: I));
6886 SmallPtrSet<PHINode *, 4> PhiNodes;
6887 SmallPtrSet<ConstantData *, 4> Constants;
6888 PhiNodes.insert(Ptr: I);
6889 Visited.insert(Ptr: I);
6890 SmallPtrSet<Instruction *, 4> Defs;
6891 SmallPtrSet<Instruction *, 4> Uses;
6892 // This works by adding extra bitcasts between load/stores and removing
6893 // existing bitcasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
6894 // we can get in the situation where we remove a bitcast in one iteration
6895 // just to add it again in the next. We need to ensure that at least one
6896 // bitcast we remove are anchored to something that will not change back.
6897 bool AnyAnchored = false;
6898
6899 while (!Worklist.empty()) {
6900 Instruction *II = Worklist.pop_back_val();
6901
6902 if (auto *Phi = dyn_cast<PHINode>(Val: II)) {
6903 // Handle Defs, which might also be PHI's
6904 for (Value *V : Phi->incoming_values()) {
6905 if (auto *OpPhi = dyn_cast<PHINode>(Val: V)) {
6906 if (!PhiNodes.count(Ptr: OpPhi)) {
6907 if (!Visited.insert(Ptr: OpPhi).second)
6908 return false;
6909 PhiNodes.insert(Ptr: OpPhi);
6910 Worklist.push_back(Elt: OpPhi);
6911 }
6912 } else if (auto *OpLoad = dyn_cast<LoadInst>(Val: V)) {
6913 if (!OpLoad->isSimple())
6914 return false;
6915 if (Defs.insert(Ptr: OpLoad).second)
6916 Worklist.push_back(Elt: OpLoad);
6917 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(Val: V)) {
6918 if (Defs.insert(Ptr: OpEx).second)
6919 Worklist.push_back(Elt: OpEx);
6920 } else if (auto *OpBC = dyn_cast<BitCastInst>(Val: V)) {
6921 if (!ConvertTy)
6922 ConvertTy = OpBC->getOperand(i_nocapture: 0)->getType();
6923 if (OpBC->getOperand(i_nocapture: 0)->getType() != ConvertTy)
6924 return false;
6925 if (Defs.insert(Ptr: OpBC).second) {
6926 Worklist.push_back(Elt: OpBC);
6927 AnyAnchored |= !isa<LoadInst>(Val: OpBC->getOperand(i_nocapture: 0)) &&
6928 !isa<ExtractElementInst>(Val: OpBC->getOperand(i_nocapture: 0));
6929 }
6930 } else if (auto *OpC = dyn_cast<ConstantData>(Val: V))
6931 Constants.insert(Ptr: OpC);
6932 else
6933 return false;
6934 }
6935 }
6936
6937 // Handle uses which might also be phi's
6938 for (User *V : II->users()) {
6939 if (auto *OpPhi = dyn_cast<PHINode>(Val: V)) {
6940 if (!PhiNodes.count(Ptr: OpPhi)) {
6941 if (Visited.count(Ptr: OpPhi))
6942 return false;
6943 PhiNodes.insert(Ptr: OpPhi);
6944 Visited.insert(Ptr: OpPhi);
6945 Worklist.push_back(Elt: OpPhi);
6946 }
6947 } else if (auto *OpStore = dyn_cast<StoreInst>(Val: V)) {
6948 if (!OpStore->isSimple() || OpStore->getOperand(i_nocapture: 0) != II)
6949 return false;
6950 Uses.insert(Ptr: OpStore);
6951 } else if (auto *OpBC = dyn_cast<BitCastInst>(Val: V)) {
6952 if (!ConvertTy)
6953 ConvertTy = OpBC->getType();
6954 if (OpBC->getType() != ConvertTy)
6955 return false;
6956 Uses.insert(Ptr: OpBC);
6957 AnyAnchored |=
6958 any_of(Range: OpBC->users(), P: [](User *U) { return !isa<StoreInst>(Val: U); });
6959 } else {
6960 return false;
6961 }
6962 }
6963 }
6964
6965 if (!ConvertTy || !AnyAnchored || PhiTy == ConvertTy ||
6966 !TLI->shouldConvertPhiType(From: PhiTy, To: ConvertTy))
6967 return false;
6968
6969 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "
6970 << *ConvertTy << "\n");
6971
6972 // Create all the new phi nodes of the new type, and bitcast any loads to the
6973 // correct type.
6974 ValueToValueMap ValMap;
6975 for (ConstantData *C : Constants)
6976 ValMap[C] = ConstantExpr::getBitCast(C, Ty: ConvertTy);
6977 for (Instruction *D : Defs) {
6978 if (isa<BitCastInst>(Val: D)) {
6979 ValMap[D] = D->getOperand(i: 0);
6980 DeletedInstrs.insert(Ptr: D);
6981 } else {
6982 BasicBlock::iterator insertPt = std::next(x: D->getIterator());
6983 ValMap[D] = new BitCastInst(D, ConvertTy, D->getName() + ".bc", insertPt);
6984 }
6985 }
6986 for (PHINode *Phi : PhiNodes)
6987 ValMap[Phi] = PHINode::Create(Ty: ConvertTy, NumReservedValues: Phi->getNumIncomingValues(),
6988 NameStr: Phi->getName() + ".tc", InsertBefore: Phi->getIterator());
6989 // Pipe together all the PhiNodes.
6990 for (PHINode *Phi : PhiNodes) {
6991 PHINode *NewPhi = cast<PHINode>(Val: ValMap[Phi]);
6992 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
6993 NewPhi->addIncoming(V: ValMap[Phi->getIncomingValue(i)],
6994 BB: Phi->getIncomingBlock(i));
6995 Visited.insert(Ptr: NewPhi);
6996 }
6997 // And finally pipe up the stores and bitcasts
6998 for (Instruction *U : Uses) {
6999 if (isa<BitCastInst>(Val: U)) {
7000 DeletedInstrs.insert(Ptr: U);
7001 replaceAllUsesWith(Old: U, New: ValMap[U->getOperand(i: 0)], FreshBBs, IsHuge: IsHugeFunc);
7002 } else {
7003 U->setOperand(i: 0, Val: new BitCastInst(ValMap[U->getOperand(i: 0)], PhiTy, "bc",
7004 U->getIterator()));
7005 }
7006 }
7007
7008 // Save the removed phis to be deleted later.
7009 DeletedInstrs.insert_range(R&: PhiNodes);
7010 return true;
7011}
7012
7013bool CodeGenPrepare::optimizePhiTypes(Function &F) {
7014 if (!Opts.cgp_optimize_phi_types)
7015 return false;
7016
7017 bool Changed = false;
7018 SmallPtrSet<PHINode *, 4> Visited;
7019 SmallPtrSet<Instruction *, 4> DeletedInstrs;
7020
7021 // Attempt to optimize all the phis in the functions to the correct type.
7022 for (auto &BB : F)
7023 for (auto &Phi : BB.phis())
7024 Changed |= optimizePhiType(I: &Phi, Visited, DeletedInstrs);
7025
7026 // Remove any old phi's that have been converted.
7027 for (auto *I : DeletedInstrs) {
7028 replaceAllUsesWith(Old: I, New: PoisonValue::get(T: I->getType()), FreshBBs, IsHuge: IsHugeFunc);
7029 I->eraseFromParent();
7030 }
7031
7032 return Changed;
7033}
7034
7035/// Return true, if an ext(load) can be formed from an extension in
7036/// \p MovedExts.
7037bool CodeGenPrepare::canFormExtLd(
7038 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
7039 Instruction *&Inst, bool HasPromoted) {
7040 for (auto *MovedExtInst : MovedExts) {
7041 if (isa<LoadInst>(Val: MovedExtInst->getOperand(i: 0))) {
7042 LI = cast<LoadInst>(Val: MovedExtInst->getOperand(i: 0));
7043 Inst = MovedExtInst;
7044 break;
7045 }
7046 }
7047 if (!LI)
7048 return false;
7049
7050 // If they're already in the same block, there's nothing to do.
7051 // Make the cheap checks first if we did not promote.
7052 // If we promoted, we need to check if it is indeed profitable.
7053 if (!HasPromoted && LI->getParent() == Inst->getParent())
7054 return false;
7055
7056 return TLI->isExtLoad(Load: LI, Ext: Inst, DL: *DL);
7057}
7058
7059/// Move a zext or sext fed by a load into the same basic block as the load,
7060/// unless conditions are unfavorable. This allows SelectionDAG to fold the
7061/// extend into the load.
7062///
7063/// E.g.,
7064/// \code
7065/// %ld = load i32* %addr
7066/// %add = add nuw i32 %ld, 4
7067/// %zext = zext i32 %add to i64
7068// \endcode
7069/// =>
7070/// \code
7071/// %ld = load i32* %addr
7072/// %zext = zext i32 %ld to i64
7073/// %add = add nuw i64 %zext, 4
7074/// \encode
7075/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
7076/// allow us to match zext(load i32*) to i64.
7077///
7078/// Also, try to promote the computations used to obtain a sign extended
7079/// value used into memory accesses.
7080/// E.g.,
7081/// \code
7082/// a = add nsw i32 b, 3
7083/// d = sext i32 a to i64
7084/// e = getelementptr ..., i64 d
7085/// \endcode
7086/// =>
7087/// \code
7088/// f = sext i32 b to i64
7089/// a = add nsw i64 f, 3
7090/// e = getelementptr ..., i64 a
7091/// \endcode
7092///
7093/// \p Inst[in/out] the extension may be modified during the process if some
7094/// promotions apply.
7095bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
7096 bool AllowPromotionWithoutCommonHeader = false;
7097 /// See if it is an interesting sext operations for the address type
7098 /// promotion before trying to promote it, e.g., the ones with the right
7099 /// type and used in memory accesses.
7100 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
7101 I: *Inst, AllowPromotionWithoutCommonHeader);
7102 TypePromotionTransaction TPT(RemovedInsts);
7103 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
7104 TPT.getRestorationPoint();
7105 SmallVector<Instruction *, 1> Exts;
7106 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
7107 Exts.push_back(Elt: Inst);
7108
7109 bool HasPromoted = tryToPromoteExts(TPT, Exts, ProfitablyMovedExts&: SpeculativelyMovedExts);
7110
7111 // Look for a load being extended.
7112 LoadInst *LI = nullptr;
7113 Instruction *ExtFedByLoad;
7114
7115 // Try to promote a chain of computation if it allows to form an extended
7116 // load.
7117 if (canFormExtLd(MovedExts: SpeculativelyMovedExts, LI, Inst&: ExtFedByLoad, HasPromoted)) {
7118 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
7119 TPT.commit();
7120 // Move the extend into the same block as the load.
7121 ExtFedByLoad->moveAfter(MovePos: LI);
7122 ++NumExtsMoved;
7123 Inst = ExtFedByLoad;
7124 return true;
7125 }
7126
7127 // Continue promoting SExts if known as considerable depending on targets.
7128 if (ATPConsiderable &&
7129 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
7130 HasPromoted, TPT, SpeculativelyMovedExts))
7131 return true;
7132
7133 TPT.rollback(Point: LastKnownGood);
7134 return false;
7135}
7136
7137// Perform address type promotion if doing so is profitable.
7138// If AllowPromotionWithoutCommonHeader == false, we should find other sext
7139// instructions that sign extended the same initial value. However, if
7140// AllowPromotionWithoutCommonHeader == true, we expect promoting the
7141// extension is just profitable.
7142bool CodeGenPrepare::performAddressTypePromotion(
7143 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
7144 bool HasPromoted, TypePromotionTransaction &TPT,
7145 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
7146 bool Promoted = false;
7147 SmallPtrSet<Instruction *, 1> UnhandledExts;
7148 bool AllSeenFirst = true;
7149 for (auto *I : SpeculativelyMovedExts) {
7150 Value *HeadOfChain = I->getOperand(i: 0);
7151 auto AlreadySeen = SeenChainsForSExt.find(Val: HeadOfChain);
7152 // If there is an unhandled SExt which has the same header, try to promote
7153 // it as well.
7154 if (AlreadySeen != SeenChainsForSExt.end()) {
7155 if (AlreadySeen->second != nullptr)
7156 UnhandledExts.insert(Ptr: AlreadySeen->second);
7157 AllSeenFirst = false;
7158 }
7159 }
7160
7161 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
7162 SpeculativelyMovedExts.size() == 1)) {
7163 TPT.commit();
7164 if (HasPromoted)
7165 Promoted = true;
7166 for (auto *I : SpeculativelyMovedExts) {
7167 Value *HeadOfChain = I->getOperand(i: 0);
7168 SeenChainsForSExt[HeadOfChain] = nullptr;
7169 ValToSExtendedUses[HeadOfChain].push_back(Elt: I);
7170 }
7171 // Update Inst as promotion happen.
7172 Inst = SpeculativelyMovedExts.pop_back_val();
7173 } else {
7174 // This is the first chain visited from the header, keep the current chain
7175 // as unhandled. Defer to promote this until we encounter another SExt
7176 // chain derived from the same header.
7177 for (auto *I : SpeculativelyMovedExts) {
7178 Value *HeadOfChain = I->getOperand(i: 0);
7179 SeenChainsForSExt[HeadOfChain] = Inst;
7180 }
7181 return false;
7182 }
7183
7184 if (!AllSeenFirst && !UnhandledExts.empty())
7185 for (auto *VisitedSExt : UnhandledExts) {
7186 if (RemovedInsts.count(Ptr: VisitedSExt))
7187 continue;
7188 TypePromotionTransaction TPT(RemovedInsts);
7189 SmallVector<Instruction *, 1> Exts;
7190 SmallVector<Instruction *, 2> Chains;
7191 Exts.push_back(Elt: VisitedSExt);
7192 bool HasPromoted = tryToPromoteExts(TPT, Exts, ProfitablyMovedExts&: Chains);
7193 TPT.commit();
7194 if (HasPromoted)
7195 Promoted = true;
7196 for (auto *I : Chains) {
7197 Value *HeadOfChain = I->getOperand(i: 0);
7198 // Mark this as handled.
7199 SeenChainsForSExt[HeadOfChain] = nullptr;
7200 ValToSExtendedUses[HeadOfChain].push_back(Elt: I);
7201 }
7202 }
7203 return Promoted;
7204}
7205
7206bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
7207 BasicBlock *DefBB = I->getParent();
7208
7209 // If the result of a {s|z}ext and its source are both live out, rewrite all
7210 // other uses of the source with result of extension.
7211 Value *Src = I->getOperand(i: 0);
7212 if (Src->hasOneUse())
7213 return false;
7214
7215 // Only do this xform if truncating is free.
7216 if (!TLI->isTruncateFree(FromTy: I->getType(), ToTy: Src->getType()))
7217 return false;
7218
7219 // Only safe to perform the optimization if the source is also defined in
7220 // this block.
7221 if (!isa<Instruction>(Val: Src) || DefBB != cast<Instruction>(Val: Src)->getParent())
7222 return false;
7223
7224 bool DefIsLiveOut = false;
7225 for (User *U : I->users()) {
7226 Instruction *UI = cast<Instruction>(Val: U);
7227
7228 // Figure out which BB this ext is used in.
7229 BasicBlock *UserBB = UI->getParent();
7230 if (UserBB == DefBB)
7231 continue;
7232 DefIsLiveOut = true;
7233 break;
7234 }
7235 if (!DefIsLiveOut)
7236 return false;
7237
7238 // Make sure none of the uses are PHI nodes.
7239 for (User *U : Src->users()) {
7240 Instruction *UI = cast<Instruction>(Val: U);
7241 BasicBlock *UserBB = UI->getParent();
7242 if (UserBB == DefBB)
7243 continue;
7244 // Be conservative. We don't want this xform to end up introducing
7245 // reloads just before load / store instructions.
7246 if (isa<PHINode>(Val: UI) || isa<LoadInst>(Val: UI) || isa<StoreInst>(Val: UI))
7247 return false;
7248 }
7249
7250 // InsertedTruncs - Only insert one trunc in each block once.
7251 DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
7252
7253 bool MadeChange = false;
7254 for (Use &U : make_early_inc_range(Range: Src->uses())) {
7255 Instruction *User = cast<Instruction>(Val: U.getUser());
7256
7257 // Figure out which BB this ext is used in.
7258 BasicBlock *UserBB = User->getParent();
7259 if (UserBB == DefBB)
7260 continue;
7261
7262 // Both src and def are live in this block. Rewrite the use.
7263 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
7264
7265 if (!InsertedTrunc) {
7266 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
7267 assert(InsertPt != UserBB->end());
7268 InsertedTrunc = new TruncInst(I, Src->getType(), "");
7269 InsertedTrunc->insertBefore(BB&: *UserBB, InsertPos: InsertPt);
7270 InsertedInsts.insert(Ptr: InsertedTrunc);
7271 }
7272
7273 // Replace a use of the {s|z}ext source with a use of the result.
7274 U = InsertedTrunc;
7275 ++NumExtUses;
7276 MadeChange = true;
7277 }
7278
7279 return MadeChange;
7280}
7281
7282// Find loads whose uses only use some of the loaded value's bits. Add an "and"
7283// just after the load if the target can fold this into one extload instruction,
7284// with the hope of eliminating some of the other later "and" instructions using
7285// the loaded value. "and"s that are made trivially redundant by the insertion
7286// of the new "and" are removed by this function, while others (e.g. those whose
7287// path from the load goes through a phi) are left for isel to potentially
7288// remove.
7289//
7290// For example:
7291//
7292// b0:
7293// x = load i32
7294// ...
7295// b1:
7296// y = and x, 0xff
7297// z = use y
7298//
7299// becomes:
7300//
7301// b0:
7302// x = load i32
7303// x' = and x, 0xff
7304// ...
7305// b1:
7306// z = use x'
7307//
7308// whereas:
7309//
7310// b0:
7311// x1 = load i32
7312// ...
7313// b1:
7314// x2 = load i32
7315// ...
7316// b2:
7317// x = phi x1, x2
7318// y = and x, 0xff
7319//
7320// becomes (after a call to optimizeLoadExt for each load):
7321//
7322// b0:
7323// x1 = load i32
7324// x1' = and x1, 0xff
7325// ...
7326// b1:
7327// x2 = load i32
7328// x2' = and x2, 0xff
7329// ...
7330// b2:
7331// x = phi x1', x2'
7332// y = and x, 0xff
7333bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
7334 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
7335 return false;
7336
7337 // Skip loads we've already transformed.
7338 if (Load->hasOneUse() &&
7339 InsertedInsts.count(Ptr: cast<Instruction>(Val: *Load->user_begin())))
7340 return false;
7341
7342 // Look at all uses of Load, looking through phis, to determine how many bits
7343 // of the loaded value are needed.
7344 SmallVector<Instruction *, 8> WorkList;
7345 SmallPtrSet<Instruction *, 16> Visited;
7346 SmallVector<Instruction *, 8> AndsToMaybeRemove;
7347 SmallVector<Instruction *, 8> DropFlags;
7348 for (auto *U : Load->users())
7349 WorkList.push_back(Elt: cast<Instruction>(Val: U));
7350
7351 EVT LoadResultVT = TLI->getValueType(DL: *DL, Ty: Load->getType());
7352 unsigned BitWidth = LoadResultVT.getSizeInBits();
7353 // If the BitWidth is 0, do not try to optimize the type
7354 if (BitWidth == 0)
7355 return false;
7356
7357 APInt DemandBits(BitWidth, 0);
7358 APInt WidestAndBits(BitWidth, 0);
7359
7360 while (!WorkList.empty()) {
7361 Instruction *I = WorkList.pop_back_val();
7362
7363 // Break use-def graph loops.
7364 if (!Visited.insert(Ptr: I).second)
7365 continue;
7366
7367 // For a PHI node, push all of its users.
7368 if (auto *Phi = dyn_cast<PHINode>(Val: I)) {
7369 for (auto *U : Phi->users())
7370 WorkList.push_back(Elt: cast<Instruction>(Val: U));
7371 continue;
7372 }
7373
7374 switch (I->getOpcode()) {
7375 case Instruction::And: {
7376 auto *AndC = dyn_cast<ConstantInt>(Val: I->getOperand(i: 1));
7377 if (!AndC)
7378 return false;
7379 APInt AndBits = AndC->getValue();
7380 DemandBits |= AndBits;
7381 // Keep track of the widest and mask we see.
7382 if (AndBits.ugt(RHS: WidestAndBits))
7383 WidestAndBits = AndBits;
7384 if (AndBits == WidestAndBits && I->getOperand(i: 0) == Load)
7385 AndsToMaybeRemove.push_back(Elt: I);
7386 break;
7387 }
7388
7389 case Instruction::Shl: {
7390 auto *ShlC = dyn_cast<ConstantInt>(Val: I->getOperand(i: 1));
7391 if (!ShlC)
7392 return false;
7393 uint64_t ShiftAmt = ShlC->getLimitedValue(Limit: BitWidth - 1);
7394 DemandBits.setLowBits(BitWidth - ShiftAmt);
7395 DropFlags.push_back(Elt: I);
7396 break;
7397 }
7398
7399 case Instruction::Trunc: {
7400 EVT TruncVT = TLI->getValueType(DL: *DL, Ty: I->getType());
7401 unsigned TruncBitWidth = TruncVT.getSizeInBits();
7402 DemandBits.setLowBits(TruncBitWidth);
7403 DropFlags.push_back(Elt: I);
7404 break;
7405 }
7406
7407 default:
7408 return false;
7409 }
7410 }
7411
7412 uint32_t ActiveBits = DemandBits.getActiveBits();
7413 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
7414 // target even if isLoadLegal says an i1 EXTLOAD is valid. For example,
7415 // for the AArch64 target isLoadLegal(i32, i1, ..., ZEXTLOAD, false) returns
7416 // true, but (and (load x) 1) is not matched as a single instruction, rather
7417 // as a LDR followed by an AND.
7418 // TODO: Look into removing this restriction by fixing backends to either
7419 // return false for isLoadLegal for i1 or have them select this pattern to
7420 // a single instruction.
7421 //
7422 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
7423 // mask, since these are the only ands that will be removed by isel.
7424 if (ActiveBits <= 1 || !DemandBits.isMask(numBits: ActiveBits) ||
7425 WidestAndBits != DemandBits)
7426 return false;
7427
7428 LLVMContext &Ctx = Load->getType()->getContext();
7429 Type *TruncTy = Type::getIntNTy(C&: Ctx, N: ActiveBits);
7430 EVT TruncVT = TLI->getValueType(DL: *DL, Ty: TruncTy);
7431
7432 // Reject cases that won't be matched as extloads.
7433 if (!LoadResultVT.bitsGT(VT: TruncVT) || !TruncVT.isRound() ||
7434 !TLI->isLoadLegal(ValVT: LoadResultVT, MemVT: TruncVT, Alignment: Load->getAlign(),
7435 AddrSpace: Load->getPointerAddressSpace(), ExtType: ISD::ZEXTLOAD, Atomic: false))
7436 return false;
7437
7438 IRBuilder<> Builder(Load->getNextNode());
7439 auto *NewAnd = cast<Instruction>(
7440 Val: Builder.CreateAnd(LHS: Load, RHS: ConstantInt::get(Context&: Ctx, V: DemandBits)));
7441 // Mark this instruction as "inserted by CGP", so that other
7442 // optimizations don't touch it.
7443 InsertedInsts.insert(Ptr: NewAnd);
7444
7445 // Replace all uses of load with new and (except for the use of load in the
7446 // new and itself).
7447 replaceAllUsesWith(Old: Load, New: NewAnd, FreshBBs, IsHuge: IsHugeFunc);
7448 NewAnd->setOperand(i: 0, Val: Load);
7449
7450 // Remove any and instructions that are now redundant.
7451 for (auto *And : AndsToMaybeRemove)
7452 // Check that the and mask is the same as the one we decided to put on the
7453 // new and.
7454 if (cast<ConstantInt>(Val: And->getOperand(i: 1))->getValue() == DemandBits) {
7455 replaceAllUsesWith(Old: And, New: NewAnd, FreshBBs, IsHuge: IsHugeFunc);
7456 if (&*CurInstIterator == And)
7457 CurInstIterator = std::next(x: And->getIterator());
7458 And->eraseFromParent();
7459 ++NumAndUses;
7460 }
7461
7462 // NSW flags may not longer hold.
7463 for (auto *Inst : DropFlags)
7464 Inst->setHasNoSignedWrap(false);
7465
7466 ++NumAndsAdded;
7467 return true;
7468}
7469
7470/// Check if V (an operand of a select instruction) is an expensive instruction
7471/// that is only used once.
7472static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
7473 auto *I = dyn_cast<Instruction>(Val: V);
7474 // If it's safe to speculatively execute, then it should not have side
7475 // effects; therefore, it's safe to sink and possibly *not* execute.
7476 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
7477 TTI->isExpensiveToSpeculativelyExecute(I);
7478}
7479
7480/// Returns true if a SelectInst should be turned into an explicit branch.
7481static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
7482 const TargetLowering *TLI,
7483 SelectInst *SI) {
7484 // If even a predictable select is cheap, then a branch can't be cheaper.
7485 if (!TLI->isPredictableSelectExpensive())
7486 return false;
7487
7488 // FIXME: This should use the same heuristics as IfConversion to determine
7489 // whether a select is better represented as a branch.
7490
7491 // If metadata tells us that the select condition is obviously predictable,
7492 // then we want to replace the select with a branch.
7493 uint64_t TrueWeight, FalseWeight;
7494 if (extractBranchWeights(I: *SI, TrueVal&: TrueWeight, FalseVal&: FalseWeight)) {
7495 uint64_t Max = std::max(a: TrueWeight, b: FalseWeight);
7496 uint64_t Sum = TrueWeight + FalseWeight;
7497 if (Sum != 0) {
7498 auto Probability = BranchProbability::getBranchProbability(Numerator: Max, Denominator: Sum);
7499 if (Probability > TTI->getPredictableBranchThreshold())
7500 return true;
7501 }
7502 }
7503
7504 CmpInst *Cmp = dyn_cast<CmpInst>(Val: SI->getCondition());
7505
7506 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
7507 // comparison condition. If the compare has more than one use, there's
7508 // probably another cmov or setcc around, so it's not worth emitting a branch.
7509 if (!Cmp || !Cmp->hasOneUse())
7510 return false;
7511
7512 // If either operand of the select is expensive and only needed on one side
7513 // of the select, we should form a branch.
7514 if (sinkSelectOperand(TTI, V: SI->getTrueValue()) ||
7515 sinkSelectOperand(TTI, V: SI->getFalseValue()))
7516 return true;
7517
7518 return false;
7519}
7520
7521/// If \p isTrue is true, return the true value of \p SI, otherwise return
7522/// false value of \p SI. If the true/false value of \p SI is defined by any
7523/// select instructions in \p Selects, look through the defining select
7524/// instruction until the true/false value is not defined in \p Selects.
7525static Value *
7526getTrueOrFalseValue(SelectInst *SI, bool isTrue,
7527 const SmallPtrSet<const Instruction *, 2> &Selects) {
7528 Value *V = nullptr;
7529
7530 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(Ptr: DefSI);
7531 DefSI = dyn_cast<SelectInst>(Val: V)) {
7532 assert(DefSI->getCondition() == SI->getCondition() &&
7533 "The condition of DefSI does not match with SI");
7534 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
7535 }
7536
7537 assert(V && "Failed to get select true/false value");
7538 return V;
7539}
7540
7541bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
7542 assert(Shift->isShift() && "Expected a shift");
7543
7544 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
7545 // general vector shifts, and (3) the shift amount is a select-of-splatted
7546 // values, hoist the shifts before the select:
7547 // shift Op0, (select Cond, TVal, FVal) -->
7548 // select Cond, (shift Op0, TVal), (shift Op0, FVal)
7549 //
7550 // This is inverting a generic IR transform when we know that the cost of a
7551 // general vector shift is more than the cost of 2 shift-by-scalars.
7552 // We can't do this effectively in SDAG because we may not be able to
7553 // determine if the select operands are splats from within a basic block.
7554 Type *Ty = Shift->getType();
7555 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7556 return false;
7557 Value *Cond, *TVal, *FVal;
7558 if (!match(V: Shift->getOperand(i_nocapture: 1),
7559 P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TVal), R: m_Value(V&: FVal)))))
7560 return false;
7561 if (!isSplatValue(V: TVal) || !isSplatValue(V: FVal))
7562 return false;
7563
7564 IRBuilder<> Builder(Shift);
7565 BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
7566 Value *NewTVal = Builder.CreateBinOp(Opc: Opcode, LHS: Shift->getOperand(i_nocapture: 0), RHS: TVal);
7567 Value *NewFVal = Builder.CreateBinOp(Opc: Opcode, LHS: Shift->getOperand(i_nocapture: 0), RHS: FVal);
7568 Value *NewSel = Builder.CreateSelect(C: Cond, True: NewTVal, False: NewFVal);
7569 replaceAllUsesWith(Old: Shift, New: NewSel, FreshBBs, IsHuge: IsHugeFunc);
7570 Shift->eraseFromParent();
7571 return true;
7572}
7573
7574bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
7575 Intrinsic::ID Opcode = Fsh->getIntrinsicID();
7576 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
7577 "Expected a funnel shift");
7578
7579 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
7580 // than general vector shifts, and (3) the shift amount is select-of-splatted
7581 // values, hoist the funnel shifts before the select:
7582 // fsh Op0, Op1, (select Cond, TVal, FVal) -->
7583 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
7584 //
7585 // This is inverting a generic IR transform when we know that the cost of a
7586 // general vector shift is more than the cost of 2 shift-by-scalars.
7587 // We can't do this effectively in SDAG because we may not be able to
7588 // determine if the select operands are splats from within a basic block.
7589 Type *Ty = Fsh->getType();
7590 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7591 return false;
7592 Value *Cond, *TVal, *FVal;
7593 if (!match(V: Fsh->getOperand(i_nocapture: 2),
7594 P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TVal), R: m_Value(V&: FVal)))))
7595 return false;
7596 if (!isSplatValue(V: TVal) || !isSplatValue(V: FVal))
7597 return false;
7598
7599 IRBuilder<> Builder(Fsh);
7600 Value *X = Fsh->getOperand(i_nocapture: 0), *Y = Fsh->getOperand(i_nocapture: 1);
7601 Value *NewTVal = Builder.CreateIntrinsic(ID: Opcode, OverloadTypes: Ty, Args: {X, Y, TVal});
7602 Value *NewFVal = Builder.CreateIntrinsic(ID: Opcode, OverloadTypes: Ty, Args: {X, Y, FVal});
7603 Value *NewSel = Builder.CreateSelect(C: Cond, True: NewTVal, False: NewFVal);
7604 replaceAllUsesWith(Old: Fsh, New: NewSel, FreshBBs, IsHuge: IsHugeFunc);
7605 Fsh->eraseFromParent();
7606 return true;
7607}
7608
7609/// If we have a SelectInst that will likely profit from branch prediction,
7610/// turn it into a branch.
7611bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
7612 if (!Opts.cgp_select2branch)
7613 return false;
7614
7615 // If the SelectOptimize pass is enabled, selects have already been optimized.
7616 if (!getCGPassBuilderOption().DisableSelectOptimize)
7617 return false;
7618
7619 // Find all consecutive select instructions that share the same condition.
7620 SmallVector<SelectInst *, 2> ASI;
7621 ASI.push_back(Elt: SI);
7622 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
7623 It != SI->getParent()->end(); ++It) {
7624 SelectInst *I = dyn_cast<SelectInst>(Val: &*It);
7625 if (I && SI->getCondition() == I->getCondition()) {
7626 ASI.push_back(Elt: I);
7627 } else {
7628 break;
7629 }
7630 }
7631
7632 SelectInst *LastSI = ASI.back();
7633 // Increment the current iterator to skip all the rest of select instructions
7634 // because they will be either "not lowered" or "all lowered" to branch.
7635 CurInstIterator = std::next(x: LastSI->getIterator());
7636 // Examine debug-info attached to the consecutive select instructions. They
7637 // won't be individually optimised by optimizeInst, so we need to perform
7638 // DbgVariableRecord maintenence here instead.
7639 for (SelectInst *SI : ArrayRef(ASI).drop_front())
7640 fixupDbgVariableRecordsOnInst(I&: *SI);
7641
7642 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(BitWidth: 1);
7643
7644 // Can we convert the 'select' to CF ?
7645 if (VectorCond || SI->getMetadata(KindID: LLVMContext::MD_unpredictable))
7646 return false;
7647
7648 TargetLowering::SelectSupportKind SelectKind;
7649 if (SI->getType()->isVectorTy())
7650 SelectKind = TargetLowering::ScalarCondVectorVal;
7651 else
7652 SelectKind = TargetLowering::ScalarValSelect;
7653
7654 if (TLI->isSelectSupported(SelectKind) &&
7655 (!isFormingBranchFromSelectProfitable(TTI, TLI, SI) ||
7656 llvm::shouldOptimizeForSize(BB: SI->getParent(), PSI, BFI)))
7657 return false;
7658
7659 // Transform a sequence like this:
7660 // start:
7661 // %cmp = cmp uge i32 %a, %b
7662 // %sel = select i1 %cmp, i32 %c, i32 %d
7663 //
7664 // Into:
7665 // start:
7666 // %cmp = cmp uge i32 %a, %b
7667 // %cmp.frozen = freeze %cmp
7668 // br i1 %cmp.frozen, label %select.true, label %select.false
7669 // select.true:
7670 // br label %select.end
7671 // select.false:
7672 // br label %select.end
7673 // select.end:
7674 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
7675 //
7676 // %cmp should be frozen, otherwise it may introduce undefined behavior.
7677 // In addition, we may sink instructions that produce %c or %d from
7678 // the entry block into the destination(s) of the new branch.
7679 // If the true or false blocks do not contain a sunken instruction, that
7680 // block and its branch may be optimized away. In that case, one side of the
7681 // first branch will point directly to select.end, and the corresponding PHI
7682 // predecessor block will be the start block.
7683 // The CFG is altered here and we update the DominatorTree and the LoopInfo,
7684 // but we don't set a ModifiedDT flag to avoid restarting the function walk in
7685 // runOnFunction for each select optimized.
7686
7687 // Collect values that go on the true side and the values that go on the false
7688 // side.
7689 SmallVector<Instruction *> TrueInstrs, FalseInstrs;
7690 for (SelectInst *SI : ASI) {
7691 if (Value *V = SI->getTrueValue(); sinkSelectOperand(TTI, V))
7692 TrueInstrs.push_back(Elt: cast<Instruction>(Val: V));
7693 if (Value *V = SI->getFalseValue(); sinkSelectOperand(TTI, V))
7694 FalseInstrs.push_back(Elt: cast<Instruction>(Val: V));
7695 }
7696
7697 // Split the select block, according to how many (if any) values go on each
7698 // side.
7699 BasicBlock *StartBlock = SI->getParent();
7700 BasicBlock::iterator SplitPt = std::next(x: BasicBlock::iterator(LastSI));
7701 // We should split before any debug-info.
7702 SplitPt.setHeadBit(true);
7703
7704 IRBuilder<> IB(SI);
7705 auto *CondFr = IB.CreateFreeze(V: SI->getCondition(), Name: SI->getName() + ".frozen");
7706
7707 BasicBlock *TrueBlock = nullptr;
7708 BasicBlock *FalseBlock = nullptr;
7709 BasicBlock *EndBlock = nullptr;
7710 UncondBrInst *TrueBranch = nullptr;
7711 UncondBrInst *FalseBranch = nullptr;
7712 if (TrueInstrs.size() == 0) {
7713 FalseBranch = cast<UncondBrInst>(
7714 Val: SplitBlockAndInsertIfElse(Cond: CondFr, SplitBefore: SplitPt, Unreachable: false, BranchWeights: nullptr, DTU, LI));
7715 FalseBlock = FalseBranch->getParent();
7716 EndBlock = cast<BasicBlock>(Val: FalseBranch->getOperand(i_nocapture: 0));
7717 } else if (FalseInstrs.size() == 0) {
7718 TrueBranch = cast<UncondBrInst>(
7719 Val: SplitBlockAndInsertIfThen(Cond: CondFr, SplitBefore: SplitPt, Unreachable: false, BranchWeights: nullptr, DTU, LI));
7720 TrueBlock = TrueBranch->getParent();
7721 EndBlock = TrueBranch->getSuccessor();
7722 } else {
7723 Instruction *ThenTerm = nullptr;
7724 Instruction *ElseTerm = nullptr;
7725 SplitBlockAndInsertIfThenElse(Cond: CondFr, SplitBefore: SplitPt, ThenTerm: &ThenTerm, ElseTerm: &ElseTerm,
7726 BranchWeights: nullptr, DTU, LI);
7727 TrueBranch = cast<UncondBrInst>(Val: ThenTerm);
7728 FalseBranch = cast<UncondBrInst>(Val: ElseTerm);
7729 TrueBlock = TrueBranch->getParent();
7730 FalseBlock = FalseBranch->getParent();
7731 EndBlock = TrueBranch->getSuccessor();
7732 }
7733
7734 EndBlock->setName("select.end");
7735 if (TrueBlock)
7736 TrueBlock->setName("select.true.sink");
7737 if (FalseBlock)
7738 FalseBlock->setName(FalseInstrs.size() == 0 ? "select.false"
7739 : "select.false.sink");
7740
7741 if (IsHugeFunc) {
7742 if (TrueBlock)
7743 FreshBBs.insert(Ptr: TrueBlock);
7744 if (FalseBlock)
7745 FreshBBs.insert(Ptr: FalseBlock);
7746 FreshBBs.insert(Ptr: EndBlock);
7747 }
7748
7749 BFI->setBlockFreq(BB: EndBlock, Freq: BFI->getBlockFreq(BB: StartBlock));
7750
7751 static const unsigned MD[] = {
7752 LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
7753 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
7754 StartBlock->getTerminator()->copyMetadata(SrcInst: *SI, WL: MD);
7755
7756 // Sink expensive instructions into the conditional blocks to avoid executing
7757 // them speculatively.
7758 for (Instruction *I : TrueInstrs)
7759 I->moveBefore(InsertPos: TrueBranch->getIterator());
7760 for (Instruction *I : FalseInstrs)
7761 I->moveBefore(InsertPos: FalseBranch->getIterator());
7762
7763 // If we did not create a new block for one of the 'true' or 'false' paths
7764 // of the condition, it means that side of the branch goes to the end block
7765 // directly and the path originates from the start block from the point of
7766 // view of the new PHI.
7767 if (TrueBlock == nullptr)
7768 TrueBlock = StartBlock;
7769 else if (FalseBlock == nullptr)
7770 FalseBlock = StartBlock;
7771
7772 SmallPtrSet<const Instruction *, 2> INS(llvm::from_range, ASI);
7773 // Use reverse iterator because later select may use the value of the
7774 // earlier select, and we need to propagate value through earlier select
7775 // to get the PHI operand.
7776 for (SelectInst *SI : llvm::reverse(C&: ASI)) {
7777 // The select itself is replaced with a PHI Node.
7778 PHINode *PN = PHINode::Create(Ty: SI->getType(), NumReservedValues: 2, NameStr: "");
7779 PN->insertBefore(InsertPos: EndBlock->begin());
7780 PN->takeName(V: SI);
7781 PN->addIncoming(V: getTrueOrFalseValue(SI, isTrue: true, Selects: INS), BB: TrueBlock);
7782 PN->addIncoming(V: getTrueOrFalseValue(SI, isTrue: false, Selects: INS), BB: FalseBlock);
7783 PN->setDebugLoc(SI->getDebugLoc());
7784
7785 replaceAllUsesWith(Old: SI, New: PN, FreshBBs, IsHuge: IsHugeFunc);
7786 SI->eraseFromParent();
7787 INS.erase(Ptr: SI);
7788 ++NumSelectsExpanded;
7789 }
7790
7791 // Instruct OptimizeBlock to skip to the next block.
7792 CurInstIterator = StartBlock->end();
7793 return true;
7794}
7795
7796/// Some targets only accept certain types for splat inputs. For example a VDUP
7797/// in MVE takes a GPR (integer) register, and the instruction that incorporate
7798/// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
7799bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
7800 // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
7801 if (!match(V: SVI, P: m_Shuffle(v1: m_InsertElt(Val: m_Undef(), Elt: m_Value(), Idx: m_ZeroInt()),
7802 v2: m_Undef(), mask: m_ZeroMask())))
7803 return false;
7804 Type *NewType = TLI->shouldConvertSplatType(SVI);
7805 if (!NewType)
7806 return false;
7807
7808 auto *SVIVecType = cast<FixedVectorType>(Val: SVI->getType());
7809 assert(!NewType->isVectorTy() && "Expected a scalar type!");
7810 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&
7811 "Expected a type of the same size!");
7812 auto *NewVecType =
7813 FixedVectorType::get(ElementType: NewType, NumElts: SVIVecType->getNumElements());
7814
7815 // Create a bitcast (shuffle (insert (bitcast(..))))
7816 IRBuilder<> Builder(SVI);
7817 Value *BC1 = Builder.CreateBitCast(
7818 V: cast<Instruction>(Val: SVI->getOperand(i_nocapture: 0))->getOperand(i: 1), DestTy: NewType);
7819 Value *Shuffle = Builder.CreateVectorSplat(NumElts: NewVecType->getNumElements(), V: BC1);
7820 Value *BC2 = Builder.CreateBitCast(V: Shuffle, DestTy: SVIVecType);
7821
7822 replaceAllUsesWith(Old: SVI, New: BC2, FreshBBs, IsHuge: IsHugeFunc);
7823 RecursivelyDeleteTriviallyDeadInstructions(
7824 V: SVI, TLI: TLInfo, MSSAU: nullptr,
7825 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
7826
7827 // Also hoist the bitcast up to its operand if it they are not in the same
7828 // block.
7829 if (auto *BCI = dyn_cast<Instruction>(Val: BC1))
7830 if (auto *Op = dyn_cast<Instruction>(Val: BCI->getOperand(i: 0)))
7831 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Val: Op) &&
7832 !Op->isTerminator() && !Op->isEHPad())
7833 BCI->moveAfter(MovePos: Op);
7834
7835 return true;
7836}
7837
7838bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
7839 // If the operands of I can be folded into a target instruction together with
7840 // I, duplicate and sink them.
7841 SmallVector<Use *, 4> OpsToSink;
7842 if (!TTI->isProfitableToSinkOperands(I, Ops&: OpsToSink))
7843 return false;
7844
7845 // OpsToSink can contain multiple uses in a use chain (e.g.
7846 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
7847 // uses must come first, so we process the ops in reverse order so as to not
7848 // create invalid IR.
7849 BasicBlock *TargetBB = I->getParent();
7850 bool Changed = false;
7851 SmallVector<Use *, 4> ToReplace;
7852 Instruction *InsertPoint = I;
7853 for (Use *U : reverse(C&: OpsToSink)) {
7854 auto *UI = cast<Instruction>(Val: U->get());
7855 if (isa<PHINode>(Val: UI) || UI->mayHaveSideEffects() || UI->mayReadFromMemory())
7856 continue;
7857 if (UI->getParent() == TargetBB) {
7858 if (UI->comesBefore(Other: InsertPoint))
7859 InsertPoint = UI;
7860 continue;
7861 }
7862 ToReplace.push_back(Elt: U);
7863 }
7864
7865 SetVector<Instruction *> MaybeDead;
7866 DenseMap<Instruction *, Instruction *> NewInstructions;
7867 for (Use *U : ToReplace) {
7868 auto *UI = cast<Instruction>(Val: U->get());
7869 Instruction *NI = UI->clone();
7870
7871 if (IsHugeFunc) {
7872 // Now we clone an instruction, its operands' defs may sink to this BB
7873 // now. So we put the operands defs' BBs into FreshBBs to do optimization.
7874 for (Value *Op : NI->operands())
7875 if (auto *OpDef = dyn_cast<Instruction>(Val: Op))
7876 FreshBBs.insert(Ptr: OpDef->getParent());
7877 }
7878
7879 NewInstructions[UI] = NI;
7880 MaybeDead.insert(X: UI);
7881 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
7882 NI->insertBefore(InsertPos: InsertPoint->getIterator());
7883 InsertPoint = NI;
7884 InsertedInsts.insert(Ptr: NI);
7885
7886 // Update the use for the new instruction, making sure that we update the
7887 // sunk instruction uses, if it is part of a chain that has already been
7888 // sunk.
7889 Instruction *OldI = cast<Instruction>(Val: U->getUser());
7890 if (auto It = NewInstructions.find(Val: OldI); It != NewInstructions.end())
7891 It->second->setOperand(i: U->getOperandNo(), Val: NI);
7892 else
7893 U->set(NI);
7894 Changed = true;
7895 }
7896
7897 // Remove instructions that are dead after sinking.
7898 for (auto *I : MaybeDead) {
7899 if (!I->hasNUsesOrMore(N: 1)) {
7900 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
7901 I->eraseFromParent();
7902 }
7903 }
7904
7905 return Changed;
7906}
7907
7908bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
7909 Value *Cond = SI->getCondition();
7910 Type *OldType = Cond->getType();
7911 LLVMContext &Context = Cond->getContext();
7912 EVT OldVT = TLI->getValueType(DL: *DL, Ty: OldType);
7913 MVT RegType = TLI->getPreferredSwitchConditionType(Context, ConditionVT: OldVT);
7914 unsigned RegWidth = RegType.getSizeInBits();
7915
7916 if (RegWidth <= cast<IntegerType>(Val: OldType)->getBitWidth())
7917 return false;
7918
7919 // If the register width is greater than the type width, expand the condition
7920 // of the switch instruction and each case constant to the width of the
7921 // register. By widening the type of the switch condition, subsequent
7922 // comparisons (for case comparisons) will not need to be extended to the
7923 // preferred register width, so we will potentially eliminate N-1 extends,
7924 // where N is the number of cases in the switch.
7925 auto *NewType = Type::getIntNTy(C&: Context, N: RegWidth);
7926
7927 // Extend the switch condition and case constants using the target preferred
7928 // extend unless the switch condition is a function argument with an extend
7929 // attribute. In that case, we can avoid an unnecessary mask/extension by
7930 // matching the argument extension instead.
7931 Instruction::CastOps ExtType = Instruction::ZExt;
7932 // Some targets prefer SExt over ZExt.
7933 if (TLI->isSExtCheaperThanZExt(FromTy: OldVT, ToTy: RegType))
7934 ExtType = Instruction::SExt;
7935
7936 if (auto *Arg = dyn_cast<Argument>(Val: Cond)) {
7937 if (Arg->hasSExtAttr())
7938 ExtType = Instruction::SExt;
7939 if (Arg->hasZExtAttr())
7940 ExtType = Instruction::ZExt;
7941 }
7942
7943 auto *ExtInst = CastInst::Create(ExtType, S: Cond, Ty: NewType);
7944 ExtInst->insertBefore(InsertPos: SI->getIterator());
7945 ExtInst->setDebugLoc(SI->getDebugLoc());
7946 SI->setCondition(ExtInst);
7947 for (auto Case : SI->cases()) {
7948 const APInt &NarrowConst = Case.getCaseValue()->getValue();
7949 APInt WideConst = (ExtType == Instruction::ZExt)
7950 ? NarrowConst.zext(width: RegWidth)
7951 : NarrowConst.sext(width: RegWidth);
7952 Case.setValue(ConstantInt::get(Context, V: WideConst));
7953 }
7954
7955 return true;
7956}
7957
7958bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
7959 // The SCCP optimization tends to produce code like this:
7960 // switch(x) { case 42: phi(42, ...) }
7961 // Materializing the constant for the phi-argument needs instructions; So we
7962 // change the code to:
7963 // switch(x) { case 42: phi(x, ...) }
7964
7965 Value *Condition = SI->getCondition();
7966 // Avoid endless loop in degenerate case.
7967 if (isa<ConstantInt>(Val: *Condition))
7968 return false;
7969
7970 bool Changed = false;
7971 BasicBlock *SwitchBB = SI->getParent();
7972 Type *ConditionType = Condition->getType();
7973
7974 for (const SwitchInst::CaseHandle &Case : SI->cases()) {
7975 ConstantInt *CaseValue = Case.getCaseValue();
7976 BasicBlock *CaseBB = Case.getCaseSuccessor();
7977 // Set to true if we previously checked that `CaseBB` is only reached by
7978 // a single case from this switch.
7979 bool CheckedForSinglePred = false;
7980 for (PHINode &PHI : CaseBB->phis()) {
7981 Type *PHIType = PHI.getType();
7982 // If ZExt is free then we can also catch patterns like this:
7983 // switch((i32)x) { case 42: phi((i64)42, ...); }
7984 // and replace `(i64)42` with `zext i32 %x to i64`.
7985 bool TryZExt =
7986 PHIType->isIntegerTy() &&
7987 PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
7988 TLI->isZExtFree(FromTy: ConditionType, ToTy: PHIType);
7989 if (PHIType == ConditionType || TryZExt) {
7990 // Set to true to skip this case because of multiple preds.
7991 bool SkipCase = false;
7992 Value *Replacement = nullptr;
7993 for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
7994 Value *PHIValue = PHI.getIncomingValue(i: I);
7995 if (PHIValue != CaseValue) {
7996 if (!TryZExt)
7997 continue;
7998 ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(Val: PHIValue);
7999 if (!PHIValueInt ||
8000 PHIValueInt->getValue() !=
8001 CaseValue->getValue().zext(width: PHIType->getIntegerBitWidth()))
8002 continue;
8003 }
8004 if (PHI.getIncomingBlock(i: I) != SwitchBB)
8005 continue;
8006 // We cannot optimize if there are multiple case labels jumping to
8007 // this block. This check may get expensive when there are many
8008 // case labels so we test for it last.
8009 if (!CheckedForSinglePred) {
8010 CheckedForSinglePred = true;
8011 if (SI->findCaseDest(BB: CaseBB) == nullptr) {
8012 SkipCase = true;
8013 break;
8014 }
8015 }
8016
8017 if (Replacement == nullptr) {
8018 if (PHIValue == CaseValue) {
8019 Replacement = Condition;
8020 } else {
8021 IRBuilder<> Builder(SI);
8022 Replacement = Builder.CreateZExt(V: Condition, DestTy: PHIType);
8023 }
8024 }
8025 PHI.setIncomingValue(i: I, V: Replacement);
8026 Changed = true;
8027 }
8028 if (SkipCase)
8029 break;
8030 }
8031 }
8032 }
8033 return Changed;
8034}
8035
8036bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
8037 bool Changed = optimizeSwitchType(SI);
8038 Changed |= optimizeSwitchPhiConstants(SI);
8039 return Changed;
8040}
8041
8042namespace {
8043
8044/// Helper class to promote a scalar operation to a vector one.
8045/// This class is used to move downward extractelement transition.
8046/// E.g.,
8047/// a = vector_op <2 x i32>
8048/// b = extractelement <2 x i32> a, i32 0
8049/// c = scalar_op b
8050/// store c
8051///
8052/// =>
8053/// a = vector_op <2 x i32>
8054/// c = vector_op a (equivalent to scalar_op on the related lane)
8055/// * d = extractelement <2 x i32> c, i32 0
8056/// * store d
8057/// Assuming both extractelement and store can be combine, we get rid of the
8058/// transition.
8059class VectorPromoteHelper {
8060 /// DataLayout associated with the current module.
8061 const DataLayout &DL;
8062
8063 /// Used to perform some checks on the legality of vector operations.
8064 const TargetLowering &TLI;
8065
8066 /// Used to estimated the cost of the promoted chain.
8067 const TargetTransformInfo &TTI;
8068
8069 /// The transition being moved downwards.
8070 Instruction *Transition;
8071
8072 /// The sequence of instructions to be promoted.
8073 SmallVector<Instruction *, 4> InstsToBePromoted;
8074
8075 /// Cost of combining a store and an extract.
8076 unsigned StoreExtractCombineCost;
8077
8078 bool StressStoreExtract;
8079
8080 /// Instruction that will be combined with the transition.
8081 Instruction *CombineInst = nullptr;
8082
8083 /// The instruction that represents the current end of the transition.
8084 /// Since we are faking the promotion until we reach the end of the chain
8085 /// of computation, we need a way to get the current end of the transition.
8086 Instruction *getEndOfTransition() const {
8087 if (InstsToBePromoted.empty())
8088 return Transition;
8089 return InstsToBePromoted.back();
8090 }
8091
8092 /// Return the index of the original value in the transition.
8093 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
8094 /// c, is at index 0.
8095 unsigned getTransitionOriginalValueIdx() const {
8096 assert(isa<ExtractElementInst>(Transition) &&
8097 "Other kind of transitions are not supported yet");
8098 return 0;
8099 }
8100
8101 /// Return the index of the index in the transition.
8102 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
8103 /// is at index 1.
8104 unsigned getTransitionIdx() const {
8105 assert(isa<ExtractElementInst>(Transition) &&
8106 "Other kind of transitions are not supported yet");
8107 return 1;
8108 }
8109
8110 /// Get the type of the transition.
8111 /// This is the type of the original value.
8112 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
8113 /// transition is <2 x i32>.
8114 Type *getTransitionType() const {
8115 return Transition->getOperand(i: getTransitionOriginalValueIdx())->getType();
8116 }
8117
8118 /// Promote \p ToBePromoted by moving \p Def downward through.
8119 /// I.e., we have the following sequence:
8120 /// Def = Transition <ty1> a to <ty2>
8121 /// b = ToBePromoted <ty2> Def, ...
8122 /// =>
8123 /// b = ToBePromoted <ty1> a, ...
8124 /// Def = Transition <ty1> ToBePromoted to <ty2>
8125 void promoteImpl(Instruction *ToBePromoted);
8126
8127 /// Check whether or not it is profitable to promote all the
8128 /// instructions enqueued to be promoted.
8129 bool isProfitableToPromote() {
8130 Value *ValIdx = Transition->getOperand(i: getTransitionOriginalValueIdx());
8131 unsigned Index = isa<ConstantInt>(Val: ValIdx)
8132 ? cast<ConstantInt>(Val: ValIdx)->getZExtValue()
8133 : -1;
8134 Type *PromotedType = getTransitionType();
8135
8136 StoreInst *ST = cast<StoreInst>(Val: CombineInst);
8137 unsigned AS = ST->getPointerAddressSpace();
8138 // Check if this store is supported.
8139 if (!TLI.allowsMisalignedMemoryAccesses(
8140 TLI.getValueType(DL, Ty: ST->getValueOperand()->getType()), AddrSpace: AS,
8141 Alignment: ST->getAlign())) {
8142 // If this is not supported, there is no way we can combine
8143 // the extract with the store.
8144 return false;
8145 }
8146
8147 // The scalar chain of computation has to pay for the transition
8148 // scalar to vector.
8149 // The vector chain has to account for the combining cost.
8150 enum TargetTransformInfo::TargetCostKind CostKind =
8151 TargetTransformInfo::TCK_RecipThroughput;
8152 InstructionCost ScalarCost =
8153 TTI.getVectorInstrCost(I: *Transition, Val: PromotedType, CostKind, Index);
8154 InstructionCost VectorCost = StoreExtractCombineCost;
8155 for (const auto &Inst : InstsToBePromoted) {
8156 // Compute the cost.
8157 // By construction, all instructions being promoted are arithmetic ones.
8158 // Moreover, one argument is a constant that can be viewed as a splat
8159 // constant.
8160 Value *Arg0 = Inst->getOperand(i: 0);
8161 bool IsArg0Constant = isa<UndefValue>(Val: Arg0) || isa<ConstantInt>(Val: Arg0) ||
8162 isa<ConstantFP>(Val: Arg0);
8163 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
8164 if (IsArg0Constant)
8165 Arg0Info.Kind = TargetTransformInfo::OK_UniformConstantValue;
8166 else
8167 Arg1Info.Kind = TargetTransformInfo::OK_UniformConstantValue;
8168
8169 ScalarCost += TTI.getArithmeticInstrCost(
8170 Opcode: Inst->getOpcode(), Ty: Inst->getType(), CostKind, Opd1Info: Arg0Info, Opd2Info: Arg1Info);
8171 VectorCost += TTI.getArithmeticInstrCost(Opcode: Inst->getOpcode(), Ty: PromotedType,
8172 CostKind, Opd1Info: Arg0Info, Opd2Info: Arg1Info);
8173 }
8174 LLVM_DEBUG(
8175 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
8176 << ScalarCost << "\nVector: " << VectorCost << '\n');
8177 return ScalarCost > VectorCost;
8178 }
8179
8180 /// Generate a constant vector with \p Val with the same
8181 /// number of elements as the transition.
8182 /// \p UseSplat defines whether or not \p Val should be replicated
8183 /// across the whole vector.
8184 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
8185 /// otherwise we generate a vector with as many poison as possible:
8186 /// <poison, ..., poison, Val, poison, ..., poison> where \p Val is only
8187 /// used at the index of the extract.
8188 Value *getConstantVector(Constant *Val, bool UseSplat) const {
8189 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
8190 if (!UseSplat) {
8191 // If we cannot determine where the constant must be, we have to
8192 // use a splat constant.
8193 Value *ValExtractIdx = Transition->getOperand(i: getTransitionIdx());
8194 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(Val: ValExtractIdx))
8195 ExtractIdx = CstVal->getSExtValue();
8196 else
8197 UseSplat = true;
8198 }
8199
8200 ElementCount EC = cast<VectorType>(Val: getTransitionType())->getElementCount();
8201 if (UseSplat)
8202 return ConstantVector::getSplat(EC, Elt: Val);
8203
8204 if (!EC.isScalable()) {
8205 SmallVector<Constant *, 4> ConstVec;
8206 PoisonValue *PoisonVal = PoisonValue::get(T: Val->getType());
8207 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
8208 if (Idx == ExtractIdx)
8209 ConstVec.push_back(Elt: Val);
8210 else
8211 ConstVec.push_back(Elt: PoisonVal);
8212 }
8213 return ConstantVector::get(V: ConstVec);
8214 } else
8215 llvm_unreachable(
8216 "Generate scalable vector for non-splat is unimplemented");
8217 }
8218
8219 /// Check if promoting to a vector type an operand at \p OperandIdx
8220 /// in \p Use can trigger undefined behavior.
8221 static bool canCauseUndefinedBehavior(const Instruction *Use,
8222 unsigned OperandIdx) {
8223 // This is not safe to introduce undef when the operand is on
8224 // the right hand side of a division-like instruction.
8225 if (OperandIdx != 1)
8226 return false;
8227 switch (Use->getOpcode()) {
8228 default:
8229 return false;
8230 case Instruction::SDiv:
8231 case Instruction::UDiv:
8232 case Instruction::SRem:
8233 case Instruction::URem:
8234 return true;
8235 case Instruction::FDiv:
8236 case Instruction::FRem:
8237 return !Use->hasNoNaNs();
8238 }
8239 llvm_unreachable(nullptr);
8240 }
8241
8242public:
8243 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
8244 const TargetTransformInfo &TTI, Instruction *Transition,
8245 unsigned CombineCost, bool StressStoreExtract)
8246 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
8247 StoreExtractCombineCost(CombineCost),
8248 StressStoreExtract(StressStoreExtract) {
8249 assert(Transition && "Do not know how to promote null");
8250 }
8251
8252 /// Check if we can promote \p ToBePromoted to \p Type.
8253 bool canPromote(const Instruction *ToBePromoted) const {
8254 // We could support CastInst too.
8255 return isa<BinaryOperator>(Val: ToBePromoted);
8256 }
8257
8258 /// Check if it is profitable to promote \p ToBePromoted
8259 /// by moving downward the transition through.
8260 bool shouldPromote(const Instruction *ToBePromoted) const {
8261 if (!isSafeToSpeculativelyExecuteWithVariableReplaced(I: ToBePromoted))
8262 return false;
8263 // Promote only if all the operands can be statically expanded.
8264 // Indeed, we do not want to introduce any new kind of transitions.
8265 for (const Use &U : ToBePromoted->operands()) {
8266 const Value *Val = U.get();
8267 if (Val == getEndOfTransition()) {
8268 continue;
8269 }
8270 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
8271 !isa<ConstantFP>(Val))
8272 return false;
8273 }
8274 // Check that the resulting operation is legal.
8275 int ISDOpcode = TLI.InstructionOpcodeToISD(Opcode: ToBePromoted->getOpcode());
8276 if (!ISDOpcode)
8277 return false;
8278 return StressStoreExtract ||
8279 TLI.isOperationLegalOrCustom(
8280 Op: ISDOpcode, VT: TLI.getValueType(DL, Ty: getTransitionType(), AllowUnknown: true));
8281 }
8282
8283 /// Check whether or not \p Use can be combined
8284 /// with the transition.
8285 /// I.e., is it possible to do Use(Transition) => AnotherUse?
8286 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Val: Use); }
8287
8288 /// Record \p ToBePromoted as part of the chain to be promoted.
8289 void enqueueForPromotion(Instruction *ToBePromoted) {
8290 InstsToBePromoted.push_back(Elt: ToBePromoted);
8291 }
8292
8293 /// Set the instruction that will be combined with the transition.
8294 void recordCombineInstruction(Instruction *ToBeCombined) {
8295 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
8296 CombineInst = ToBeCombined;
8297 }
8298
8299 /// Promote all the instructions enqueued for promotion if it is
8300 /// is profitable.
8301 /// \return True if the promotion happened, false otherwise.
8302 bool promote() {
8303 // Check if there is something to promote.
8304 // Right now, if we do not have anything to combine with,
8305 // we assume the promotion is not profitable.
8306 if (InstsToBePromoted.empty() || !CombineInst)
8307 return false;
8308
8309 // Check cost.
8310 if (!StressStoreExtract && !isProfitableToPromote())
8311 return false;
8312
8313 // Promote.
8314 for (auto &ToBePromoted : InstsToBePromoted)
8315 promoteImpl(ToBePromoted);
8316 InstsToBePromoted.clear();
8317 return true;
8318 }
8319};
8320
8321} // end anonymous namespace
8322
8323void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
8324 // At this point, we know that all the operands of ToBePromoted but Def
8325 // can be statically promoted.
8326 // For Def, we need to use its parameter in ToBePromoted:
8327 // b = ToBePromoted ty1 a
8328 // Def = Transition ty1 b to ty2
8329 // Move the transition down.
8330 // 1. Replace all uses of the promoted operation by the transition.
8331 // = ... b => = ... Def.
8332 assert(ToBePromoted->getType() == Transition->getType() &&
8333 "The type of the result of the transition does not match "
8334 "the final type");
8335 ToBePromoted->replaceAllUsesWith(V: Transition);
8336 // 2. Update the type of the uses.
8337 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
8338 Type *TransitionTy = getTransitionType();
8339 ToBePromoted->mutateType(Ty: TransitionTy);
8340 // 3. Update all the operands of the promoted operation with promoted
8341 // operands.
8342 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
8343 for (Use &U : ToBePromoted->operands()) {
8344 Value *Val = U.get();
8345 Value *NewVal = nullptr;
8346 if (Val == Transition)
8347 NewVal = Transition->getOperand(i: getTransitionOriginalValueIdx());
8348 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
8349 isa<ConstantFP>(Val)) {
8350 // Use a splat constant if it is not safe to use undef.
8351 NewVal = getConstantVector(
8352 Val: cast<Constant>(Val),
8353 UseSplat: isa<UndefValue>(Val) ||
8354 canCauseUndefinedBehavior(Use: ToBePromoted, OperandIdx: U.getOperandNo()));
8355 } else
8356 llvm_unreachable("Did you modified shouldPromote and forgot to update "
8357 "this?");
8358 ToBePromoted->setOperand(i: U.getOperandNo(), Val: NewVal);
8359 }
8360 Transition->moveAfter(MovePos: ToBePromoted);
8361 Transition->setOperand(i: getTransitionOriginalValueIdx(), Val: ToBePromoted);
8362}
8363
8364/// Some targets can do store(extractelement) with one instruction.
8365/// Try to push the extractelement towards the stores when the target
8366/// has this feature and this is profitable.
8367bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
8368 unsigned CombineCost = std::numeric_limits<unsigned>::max();
8369 if (!Opts.cgp_store_extract ||
8370 (!Opts.cgp_stress_store_extract &&
8371 !TLI->canCombineStoreAndExtract(VectorTy: Inst->getOperand(i: 0)->getType(),
8372 Idx: Inst->getOperand(i: 1), Cost&: CombineCost)))
8373 return false;
8374
8375 // At this point we know that Inst is a vector to scalar transition.
8376 // Try to move it down the def-use chain, until:
8377 // - We can combine the transition with its single use
8378 // => we got rid of the transition.
8379 // - We escape the current basic block
8380 // => we would need to check that we are moving it at a cheaper place and
8381 // we do not do that for now.
8382 BasicBlock *Parent = Inst->getParent();
8383 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
8384 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost,
8385 Opts.cgp_stress_store_extract);
8386 // If the transition has more than one use, assume this is not going to be
8387 // beneficial.
8388 while (Inst->hasOneUse()) {
8389 Instruction *ToBePromoted = cast<Instruction>(Val: *Inst->user_begin());
8390 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
8391
8392 if (ToBePromoted->getParent() != Parent) {
8393 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
8394 << ToBePromoted->getParent()->getName()
8395 << ") than the transition (" << Parent->getName()
8396 << ").\n");
8397 return false;
8398 }
8399
8400 if (VPH.canCombine(Use: ToBePromoted)) {
8401 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
8402 << "will be combined with: " << *ToBePromoted << '\n');
8403 VPH.recordCombineInstruction(ToBeCombined: ToBePromoted);
8404 bool Changed = VPH.promote();
8405 NumStoreExtractExposed += Changed;
8406 return Changed;
8407 }
8408
8409 LLVM_DEBUG(dbgs() << "Try promoting.\n");
8410 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
8411 return false;
8412
8413 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
8414
8415 VPH.enqueueForPromotion(ToBePromoted);
8416 Inst = ToBePromoted;
8417 }
8418 return false;
8419}
8420
8421/// For the instruction sequence of store below, F and I values
8422/// are bundled together as an i64 value before being stored into memory.
8423/// Sometimes it is more efficient to generate separate stores for F and I,
8424/// which can remove the bitwise instructions or sink them to colder places.
8425///
8426/// (store (or (zext (bitcast F to i32) to i64),
8427/// (shl (zext I to i64), 32)), addr) -->
8428/// (store F, addr) and (store I, addr+4)
8429///
8430/// Similarly, splitting for other merged store can also be beneficial, like:
8431/// For pair of {i32, i32}, i64 store --> two i32 stores.
8432/// For pair of {i32, i16}, i64 store --> two i32 stores.
8433/// For pair of {i16, i16}, i32 store --> two i16 stores.
8434/// For pair of {i16, i8}, i32 store --> two i16 stores.
8435/// For pair of {i8, i8}, i16 store --> two i8 stores.
8436///
8437/// We allow each target to determine specifically which kind of splitting is
8438/// supported.
8439///
8440/// The store patterns are commonly seen from the simple code snippet below
8441/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
8442/// void goo(const std::pair<int, float> &);
8443/// hoo() {
8444/// ...
8445/// goo(std::make_pair(tmp, ftmp));
8446/// ...
8447/// }
8448///
8449/// Although we already have similar splitting in DAG Combine, we duplicate
8450/// it in CodeGenPrepare to catch the case in which pattern is across
8451/// multiple BBs. The logic in DAG Combine is kept to catch case generated
8452/// during code expansion.
8453static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
8454 const TargetLowering &TLI,
8455 bool ForceSplitStore) {
8456 // Handle simple but common cases only.
8457 Type *StoreType = SI.getValueOperand()->getType();
8458
8459 // The code below assumes shifting a value by <number of bits>,
8460 // whereas scalable vectors would have to be shifted by
8461 // <2log(vscale) + number of bits> in order to store the
8462 // low/high parts. Bailing out for now.
8463 if (StoreType->isScalableTy())
8464 return false;
8465
8466 if (!DL.typeSizeEqualsStoreSize(Ty: StoreType) ||
8467 DL.getTypeSizeInBits(Ty: StoreType) == 0)
8468 return false;
8469
8470 unsigned HalfValBitSize = DL.getTypeSizeInBits(Ty: StoreType) / 2;
8471 Type *SplitStoreType = Type::getIntNTy(C&: SI.getContext(), N: HalfValBitSize);
8472 if (!DL.typeSizeEqualsStoreSize(Ty: SplitStoreType))
8473 return false;
8474
8475 // Don't split the store if it is volatile or atomic.
8476 if (!SI.isSimple())
8477 return false;
8478
8479 // Match the following patterns:
8480 // (store (or (zext LValue to i64),
8481 // (shl (zext HValue to i64), 32)), HalfValBitSize)
8482 // or
8483 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
8484 // (zext LValue to i64),
8485 // Expect both operands of OR and the first operand of SHL have only
8486 // one use.
8487 Value *LValue, *HValue;
8488 if (!match(V: SI.getValueOperand(),
8489 P: m_c_Or(L: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: LValue))),
8490 R: m_OneUse(SubPattern: m_Shl(L: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: HValue))),
8491 R: m_SpecificInt(V: HalfValBitSize))))))
8492 return false;
8493
8494 // Check LValue and HValue are int with size less or equal than 32.
8495 if (!LValue->getType()->isIntegerTy() ||
8496 DL.getTypeSizeInBits(Ty: LValue->getType()) > HalfValBitSize ||
8497 !HValue->getType()->isIntegerTy() ||
8498 DL.getTypeSizeInBits(Ty: HValue->getType()) > HalfValBitSize)
8499 return false;
8500
8501 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
8502 // as the input of target query.
8503 auto *LBC = dyn_cast<BitCastInst>(Val: LValue);
8504 auto *HBC = dyn_cast<BitCastInst>(Val: HValue);
8505 EVT LowTy = LBC ? EVT::getEVT(Ty: LBC->getOperand(i_nocapture: 0)->getType())
8506 : EVT::getEVT(Ty: LValue->getType());
8507 EVT HighTy = HBC ? EVT::getEVT(Ty: HBC->getOperand(i_nocapture: 0)->getType())
8508 : EVT::getEVT(Ty: HValue->getType());
8509 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LTy: LowTy, HTy: HighTy))
8510 return false;
8511
8512 // Start to split store.
8513 IRBuilder<> Builder(&SI);
8514
8515 // If LValue/HValue is a bitcast in another BB, create a new one in current
8516 // BB so it may be merged with the splitted stores by dag combiner.
8517 if (LBC && LBC->getParent() != SI.getParent())
8518 LValue = Builder.CreateBitCast(V: LBC->getOperand(i_nocapture: 0), DestTy: LBC->getType());
8519 if (HBC && HBC->getParent() != SI.getParent())
8520 HValue = Builder.CreateBitCast(V: HBC->getOperand(i_nocapture: 0), DestTy: HBC->getType());
8521
8522 bool IsLE = SI.getDataLayout().isLittleEndian();
8523 auto CreateSplitStore = [&](Value *V, bool Upper) {
8524 V = Builder.CreateZExtOrBitCast(V, DestTy: SplitStoreType);
8525 Value *Addr = SI.getPointerOperand();
8526 Align Alignment = SI.getAlign();
8527 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
8528 if (IsOffsetStore) {
8529 Addr = Builder.CreateGEP(
8530 Ty: SplitStoreType, Ptr: Addr,
8531 IdxList: ConstantInt::get(Ty: Type::getInt32Ty(C&: SI.getContext()), V: 1));
8532
8533 // When splitting the store in half, naturally one half will retain the
8534 // alignment of the original wider store, regardless of whether it was
8535 // over-aligned or not, while the other will require adjustment.
8536 Alignment = commonAlignment(A: Alignment, Offset: HalfValBitSize / 8);
8537 }
8538 Builder.CreateAlignedStore(Val: V, Ptr: Addr, Align: Alignment);
8539 };
8540
8541 CreateSplitStore(LValue, false);
8542 CreateSplitStore(HValue, true);
8543
8544 // Delete the old store.
8545 SI.eraseFromParent();
8546 return true;
8547}
8548
8549// Return true if the GEP has two operands, the first operand is of a sequential
8550// type, and the second operand is a constant.
8551static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
8552 gep_type_iterator I = gep_type_begin(GEP: *GEP);
8553 return GEP->getNumOperands() == 2 && I.isSequential() &&
8554 isa<ConstantInt>(Val: GEP->getOperand(i_nocapture: 1));
8555}
8556
8557// Try unmerging GEPs to reduce liveness interference (register pressure) across
8558// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
8559// reducing liveness interference across those edges benefits global register
8560// allocation. Currently handles only certain cases.
8561//
8562// For example, unmerge %GEPI and %UGEPI as below.
8563//
8564// ---------- BEFORE ----------
8565// SrcBlock:
8566// ...
8567// %GEPIOp = ...
8568// ...
8569// %GEPI = gep %GEPIOp, Idx
8570// ...
8571// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
8572// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
8573// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
8574// %UGEPI)
8575//
8576// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
8577// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
8578// ...
8579//
8580// DstBi:
8581// ...
8582// %UGEPI = gep %GEPIOp, UIdx
8583// ...
8584// ---------------------------
8585//
8586// ---------- AFTER ----------
8587// SrcBlock:
8588// ... (same as above)
8589// (* %GEPI is still alive on the indirectbr edges)
8590// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
8591// unmerging)
8592// ...
8593//
8594// DstBi:
8595// ...
8596// %UGEPI = gep %GEPI, (UIdx-Idx)
8597// ...
8598// ---------------------------
8599//
8600// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
8601// no longer alive on them.
8602//
8603// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
8604// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
8605// not to disable further simplications and optimizations as a result of GEP
8606// merging.
8607//
8608// Note this unmerging may increase the length of the data flow critical path
8609// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
8610// between the register pressure and the length of data-flow critical
8611// path. Restricting this to the uncommon IndirectBr case would minimize the
8612// impact of potentially longer critical path, if any, and the impact on compile
8613// time.
8614static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
8615 const TargetTransformInfo *TTI) {
8616 BasicBlock *SrcBlock = GEPI->getParent();
8617 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
8618 // (non-IndirectBr) cases exit early here.
8619 if (!isa<IndirectBrInst>(Val: SrcBlock->getTerminator()))
8620 return false;
8621 // Check that GEPI is a simple gep with a single constant index.
8622 if (!GEPSequentialConstIndexed(GEP: GEPI))
8623 return false;
8624 ConstantInt *GEPIIdx = cast<ConstantInt>(Val: GEPI->getOperand(i_nocapture: 1));
8625 // Check that GEPI is a cheap one.
8626 if (TTI->getIntImmCost(Imm: GEPIIdx->getValue(), Ty: GEPIIdx->getType(),
8627 CostKind: TargetTransformInfo::TCK_SizeAndLatency) >
8628 TargetTransformInfo::TCC_Basic)
8629 return false;
8630 Value *GEPIOp = GEPI->getOperand(i_nocapture: 0);
8631 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
8632 if (!isa<Instruction>(Val: GEPIOp))
8633 return false;
8634 auto *GEPIOpI = cast<Instruction>(Val: GEPIOp);
8635 if (GEPIOpI->getParent() != SrcBlock)
8636 return false;
8637 // Check that GEP is used outside the block, meaning it's alive on the
8638 // IndirectBr edge(s).
8639 if (llvm::none_of(Range: GEPI->users(), P: [&](User *Usr) {
8640 if (auto *I = dyn_cast<Instruction>(Val: Usr)) {
8641 if (I->getParent() != SrcBlock) {
8642 return true;
8643 }
8644 }
8645 return false;
8646 }))
8647 return false;
8648 // The second elements of the GEP chains to be unmerged.
8649 std::vector<GetElementPtrInst *> UGEPIs;
8650 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
8651 // on IndirectBr edges.
8652 for (User *Usr : GEPIOp->users()) {
8653 if (Usr == GEPI)
8654 continue;
8655 // Check if Usr is an Instruction. If not, give up.
8656 if (!isa<Instruction>(Val: Usr))
8657 return false;
8658 auto *UI = cast<Instruction>(Val: Usr);
8659 // Check if Usr in the same block as GEPIOp, which is fine, skip.
8660 if (UI->getParent() == SrcBlock)
8661 continue;
8662 // Check if Usr is a GEP. If not, give up.
8663 if (!isa<GetElementPtrInst>(Val: Usr))
8664 return false;
8665 auto *UGEPI = cast<GetElementPtrInst>(Val: Usr);
8666 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
8667 // the pointer operand to it. If so, record it in the vector. If not, give
8668 // up.
8669 if (!GEPSequentialConstIndexed(GEP: UGEPI))
8670 return false;
8671 if (UGEPI->getOperand(i_nocapture: 0) != GEPIOp)
8672 return false;
8673 if (UGEPI->getSourceElementType() != GEPI->getSourceElementType())
8674 return false;
8675 if (GEPIIdx->getType() !=
8676 cast<ConstantInt>(Val: UGEPI->getOperand(i_nocapture: 1))->getType())
8677 return false;
8678 ConstantInt *UGEPIIdx = cast<ConstantInt>(Val: UGEPI->getOperand(i_nocapture: 1));
8679 if (TTI->getIntImmCost(Imm: UGEPIIdx->getValue(), Ty: UGEPIIdx->getType(),
8680 CostKind: TargetTransformInfo::TCK_SizeAndLatency) >
8681 TargetTransformInfo::TCC_Basic)
8682 return false;
8683 UGEPIs.push_back(x: UGEPI);
8684 }
8685 if (UGEPIs.size() == 0)
8686 return false;
8687 // Check the materializing cost of (Uidx-Idx).
8688 for (GetElementPtrInst *UGEPI : UGEPIs) {
8689 ConstantInt *UGEPIIdx = cast<ConstantInt>(Val: UGEPI->getOperand(i_nocapture: 1));
8690 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8691 InstructionCost ImmCost = TTI->getIntImmCost(
8692 Imm: NewIdx, Ty: GEPIIdx->getType(), CostKind: TargetTransformInfo::TCK_SizeAndLatency);
8693 if (ImmCost > TargetTransformInfo::TCC_Basic)
8694 return false;
8695 }
8696 // Now unmerge between GEPI and UGEPIs.
8697 for (GetElementPtrInst *UGEPI : UGEPIs) {
8698 UGEPI->setOperand(i_nocapture: 0, Val_nocapture: GEPI);
8699 ConstantInt *UGEPIIdx = cast<ConstantInt>(Val: UGEPI->getOperand(i_nocapture: 1));
8700 auto NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8701 Constant *NewUGEPIIdx = ConstantInt::get(Ty: GEPIIdx->getType(), V: NewIdx);
8702 UGEPI->setOperand(i_nocapture: 1, Val_nocapture: NewUGEPIIdx);
8703
8704 auto SourceFlags = GEPI->getNoWrapFlags();
8705 // Intersect flags to avoid UB in updated GEP.
8706 auto TargetFlags =
8707 UGEPI->getNoWrapFlags().intersectForOffsetAdd(Other: SourceFlags);
8708 // If UGEPI now has a negative index, drop the nuw flag.
8709 if (NewIdx.isNegative() && TargetFlags.hasNoUnsignedWrap())
8710 TargetFlags = TargetFlags.withoutNoUnsignedWrap();
8711 UGEPI->setNoWrapFlags(TargetFlags);
8712 }
8713 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
8714 // alive on IndirectBr edges).
8715 assert(llvm::none_of(GEPIOp->users(),
8716 [&](User *Usr) {
8717 return cast<Instruction>(Usr)->getParent() != SrcBlock;
8718 }) &&
8719 "GEPIOp is used outside SrcBlock");
8720 return true;
8721}
8722
8723static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI,
8724 SmallPtrSet<BasicBlock *, 32> &FreshBBs,
8725 bool IsHugeFunc) {
8726 // Try and convert
8727 // %c = icmp ult %x, 8
8728 // br %c, bla, blb
8729 // %tc = lshr %x, 3
8730 // to
8731 // %tc = lshr %x, 3
8732 // %c = icmp eq %tc, 0
8733 // br %c, bla, blb
8734 // Creating the cmp to zero can be better for the backend, especially if the
8735 // lshr produces flags that can be used automatically.
8736 if (!TLI.preferZeroCompareBranch())
8737 return false;
8738
8739 ICmpInst *Cmp = dyn_cast<ICmpInst>(Val: Branch->getCondition());
8740 if (!Cmp || !isa<ConstantInt>(Val: Cmp->getOperand(i_nocapture: 1)) || !Cmp->hasOneUse())
8741 return false;
8742
8743 Value *X = Cmp->getOperand(i_nocapture: 0);
8744 if (!X->hasUseList())
8745 return false;
8746
8747 APInt CmpC = cast<ConstantInt>(Val: Cmp->getOperand(i_nocapture: 1))->getValue();
8748
8749 for (auto *U : X->users()) {
8750 Instruction *UI = dyn_cast<Instruction>(Val: U);
8751 // A quick dominance check
8752 if (!UI ||
8753 (UI->getParent() != Branch->getParent() &&
8754 UI->getParent() != Branch->getSuccessor(i: 0) &&
8755 UI->getParent() != Branch->getSuccessor(i: 1)) ||
8756 (UI->getParent() != Branch->getParent() &&
8757 !UI->getParent()->getSinglePredecessor()))
8758 continue;
8759
8760 if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
8761 match(V: UI, P: m_Shr(L: m_Specific(V: X), R: m_SpecificInt(V: CmpC.logBase2())))) {
8762 IRBuilder<> Builder(Branch);
8763 if (UI->getParent() != Branch->getParent())
8764 UI->moveBefore(InsertPos: Branch->getIterator());
8765 UI->dropPoisonGeneratingFlags();
8766 Value *NewCmp = Builder.CreateCmp(Pred: ICmpInst::ICMP_EQ, LHS: UI,
8767 RHS: ConstantInt::get(Ty: UI->getType(), V: 0));
8768 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8769 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8770 replaceAllUsesWith(Old: Cmp, New: NewCmp, FreshBBs, IsHuge: IsHugeFunc);
8771 return true;
8772 }
8773 if (Cmp->isEquality() &&
8774 (match(V: UI, P: m_Add(L: m_Specific(V: X), R: m_SpecificInt(V: -CmpC))) ||
8775 match(V: UI, P: m_Sub(L: m_Specific(V: X), R: m_SpecificInt(V: CmpC))) ||
8776 match(V: UI, P: m_Xor(L: m_Specific(V: X), R: m_SpecificInt(V: CmpC))))) {
8777 IRBuilder<> Builder(Branch);
8778 if (UI->getParent() != Branch->getParent())
8779 UI->moveBefore(InsertPos: Branch->getIterator());
8780 UI->dropPoisonGeneratingFlags();
8781 Value *NewCmp = Builder.CreateCmp(Pred: Cmp->getPredicate(), LHS: UI,
8782 RHS: ConstantInt::get(Ty: UI->getType(), V: 0));
8783 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8784 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8785 replaceAllUsesWith(Old: Cmp, New: NewCmp, FreshBBs, IsHuge: IsHugeFunc);
8786 return true;
8787 }
8788 }
8789 return false;
8790}
8791
8792bool CodeGenPrepare::optimizeInst(Instruction *I, ModifyDT &ModifiedDT) {
8793 bool AnyChange = false;
8794 AnyChange = fixupDbgVariableRecordsOnInst(I&: *I);
8795
8796 // Bail out if we inserted the instruction to prevent optimizations from
8797 // stepping on each other's toes.
8798 if (InsertedInsts.count(Ptr: I))
8799 return AnyChange;
8800
8801 // TODO: Move into the switch on opcode below here.
8802 if (PHINode *P = dyn_cast<PHINode>(Val: I)) {
8803 // It is possible for very late stage optimizations (such as SimplifyCFG)
8804 // to introduce PHI nodes too late to be cleaned up. If we detect such a
8805 // trivial PHI, go ahead and zap it here.
8806 if (Value *V = simplifyInstruction(I: P, Q: {*DL, TLInfo})) {
8807 LargeOffsetGEPMap.erase(Key: P);
8808 replaceAllUsesWith(Old: P, New: V, FreshBBs, IsHuge: IsHugeFunc);
8809 P->eraseFromParent();
8810 ++NumPHIsElim;
8811 return true;
8812 }
8813 return AnyChange;
8814 }
8815
8816 if (CastInst *CI = dyn_cast<CastInst>(Val: I)) {
8817 // If the source of the cast is a constant, then this should have
8818 // already been constant folded. The only reason NOT to constant fold
8819 // it is if something (e.g. LSR) was careful to place the constant
8820 // evaluation in a block other than then one that uses it (e.g. to hoist
8821 // the address of globals out of a loop). If this is the case, we don't
8822 // want to forward-subst the cast.
8823 if (auto *BCI = dyn_cast<BitCastInst>(Val: CI)) {
8824 // Hoist bitcasts of illegal types to reduce cross-block register pressure
8825 // and prevent register splitting.
8826 if (optimizeBitCast(BCI, TLI: *TLI, DL: *DL)) {
8827 return true;
8828 }
8829 }
8830
8831 if (isa<Constant>(Val: CI->getOperand(i_nocapture: 0)))
8832 return AnyChange;
8833
8834 if (OptimizeNoopCopyExpression(CI, TLI: *TLI, DL: *DL))
8835 return true;
8836
8837 if ((isa<UIToFPInst>(Val: I) || isa<SIToFPInst>(Val: I) || isa<FPToUIInst>(Val: I) ||
8838 isa<TruncInst>(Val: I)) &&
8839 TLI->optimizeExtendOrTruncateConversion(
8840 I, L: LI->getLoopFor(BB: I->getParent()), TTI: *TTI))
8841 return true;
8842
8843 if (isa<ZExtInst>(Val: I) || isa<SExtInst>(Val: I)) {
8844 /// Sink a zext or sext into its user blocks if the target type doesn't
8845 /// fit in one register
8846 if (TLI->getTypeAction(Context&: CI->getContext(),
8847 VT: TLI->getValueType(DL: *DL, Ty: CI->getType())) ==
8848 TargetLowering::TypeExpandInteger) {
8849 return SinkCast(CI);
8850 } else {
8851 if (TLI->optimizeExtendOrTruncateConversion(
8852 I, L: LI->getLoopFor(BB: I->getParent()), TTI: *TTI))
8853 return true;
8854
8855 bool MadeChange = optimizeExt(Inst&: I);
8856 return MadeChange | optimizeExtUses(I);
8857 }
8858 }
8859 return AnyChange;
8860 }
8861
8862 if (auto *Cmp = dyn_cast<CmpInst>(Val: I))
8863 if (optimizeCmp(Cmp, ModifiedDT))
8864 return true;
8865
8866 if (match(V: I, P: m_URem(L: m_Value(), R: m_Value())))
8867 if (optimizeURem(Rem: I))
8868 return true;
8869
8870 if (LoadInst *LI = dyn_cast<LoadInst>(Val: I)) {
8871 LI->setMetadata(KindID: LLVMContext::MD_invariant_group, Node: nullptr);
8872 bool Modified = optimizeLoadExt(Load: LI);
8873 unsigned AS = LI->getPointerAddressSpace();
8874 Modified |= optimizeMemoryInst(MemoryInst: I, Addr: I->getOperand(i: 0), AccessTy: LI->getType(), AddrSpace: AS);
8875 return Modified;
8876 }
8877
8878 if (StoreInst *SI = dyn_cast<StoreInst>(Val: I)) {
8879 if (splitMergedValStore(SI&: *SI, DL: *DL, TLI: *TLI, ForceSplitStore: Opts.cgp_force_split_store))
8880 return true;
8881 SI->setMetadata(KindID: LLVMContext::MD_invariant_group, Node: nullptr);
8882 unsigned AS = SI->getPointerAddressSpace();
8883 return optimizeMemoryInst(MemoryInst: I, Addr: SI->getOperand(i_nocapture: 1),
8884 AccessTy: SI->getOperand(i_nocapture: 0)->getType(), AddrSpace: AS);
8885 }
8886
8887 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Val: I)) {
8888 unsigned AS = RMW->getPointerAddressSpace();
8889 return optimizeMemoryInst(MemoryInst: I, Addr: RMW->getPointerOperand(), AccessTy: RMW->getType(), AddrSpace: AS);
8890 }
8891
8892 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Val: I)) {
8893 unsigned AS = CmpX->getPointerAddressSpace();
8894 return optimizeMemoryInst(MemoryInst: I, Addr: CmpX->getPointerOperand(),
8895 AccessTy: CmpX->getCompareOperand()->getType(), AddrSpace: AS);
8896 }
8897
8898 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val: I);
8899
8900 if (BinOp && BinOp->getOpcode() == Instruction::And &&
8901 Opts.cgp_andcmp_sinking &&
8902 sinkAndCmp0Expression(AndI: BinOp, TLI: *TLI, InsertedInsts))
8903 return true;
8904
8905 // TODO: Move this into the switch on opcode - it handles shifts already.
8906 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
8907 BinOp->getOpcode() == Instruction::LShr)) {
8908 ConstantInt *CI = dyn_cast<ConstantInt>(Val: BinOp->getOperand(i_nocapture: 1));
8909 if (CI && TLI->hasExtractBitsInsn())
8910 if (OptimizeExtractBits(ShiftI: BinOp, CI, TLI: *TLI, DL: *DL))
8911 return true;
8912 }
8913
8914 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Val: I)) {
8915 if (GEPI->hasAllZeroIndices()) {
8916 /// The GEP operand must be a pointer, so must its result -> BitCast
8917 Instruction *NC = new BitCastInst(GEPI->getOperand(i_nocapture: 0), GEPI->getType(),
8918 GEPI->getName(), GEPI->getIterator());
8919 NC->setDebugLoc(GEPI->getDebugLoc());
8920 replaceAllUsesWith(Old: GEPI, New: NC, FreshBBs, IsHuge: IsHugeFunc);
8921 RecursivelyDeleteTriviallyDeadInstructions(
8922 V: GEPI, TLI: TLInfo, MSSAU: nullptr,
8923 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
8924 ++NumGEPsElim;
8925 optimizeInst(I: NC, ModifiedDT);
8926 return true;
8927 }
8928 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
8929 return true;
8930 }
8931 }
8932
8933 if (FreezeInst *FI = dyn_cast<FreezeInst>(Val: I)) {
8934 // freeze(icmp a, const)) -> icmp (freeze a), const
8935 // This helps generate efficient conditional jumps.
8936 CmpInst *CmpI = dyn_cast<CmpInst>(Val: FI->getOperand(i_nocapture: 0));
8937 if (CmpI && CmpI->hasOneUse()) {
8938 auto Op0 = CmpI->getOperand(i_nocapture: 0), Op1 = CmpI->getOperand(i_nocapture: 1);
8939 bool Const0 = isa<ConstantInt>(Val: Op0) || isa<ConstantFP>(Val: Op0) ||
8940 isa<ConstantPointerNull>(Val: Op0);
8941 bool Const1 = isa<ConstantInt>(Val: Op1) || isa<ConstantFP>(Val: Op1) ||
8942 isa<ConstantPointerNull>(Val: Op1);
8943 if (Const0 || Const1) {
8944 if (!Const0 || !Const1) {
8945 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI->getIterator());
8946 F->takeName(V: FI);
8947 CmpI->setOperand(i_nocapture: Const0 ? 1 : 0, Val_nocapture: F);
8948 }
8949 CmpI->dropPoisonGeneratingFlags();
8950 replaceAllUsesWith(Old: FI, New: CmpI, FreshBBs, IsHuge: IsHugeFunc);
8951 FI->eraseFromParent();
8952 return true;
8953 }
8954 }
8955 return AnyChange;
8956 }
8957
8958 if (tryToSinkFreeOperands(I))
8959 return true;
8960
8961 switch (I->getOpcode()) {
8962 case Instruction::Shl:
8963 case Instruction::LShr:
8964 case Instruction::AShr:
8965 return optimizeShiftInst(Shift: cast<BinaryOperator>(Val: I));
8966 case Instruction::Call:
8967 return optimizeCallInst(CI: cast<CallInst>(Val: I), ModifiedDT);
8968 case Instruction::Select:
8969 return optimizeSelectInst(SI: cast<SelectInst>(Val: I));
8970 case Instruction::ShuffleVector:
8971 return optimizeShuffleVectorInst(SVI: cast<ShuffleVectorInst>(Val: I));
8972 case Instruction::Switch:
8973 return optimizeSwitchInst(SI: cast<SwitchInst>(Val: I));
8974 case Instruction::ExtractElement:
8975 return optimizeExtractElementInst(Inst: cast<ExtractElementInst>(Val: I));
8976 case Instruction::CondBr:
8977 return optimizeBranch(Branch: cast<CondBrInst>(Val: I), TLI: *TLI, FreshBBs, IsHugeFunc);
8978 }
8979
8980 return AnyChange;
8981}
8982
8983/// Given an OR instruction, check to see if this is a bitreverse
8984/// idiom. If so, insert the new intrinsic and return true.
8985bool CodeGenPrepare::makeBitReverse(Instruction &I) {
8986 if (!I.getType()->isIntegerTy() ||
8987 !TLI->isOperationLegalOrCustom(Op: ISD::BITREVERSE,
8988 VT: TLI->getValueType(DL: *DL, Ty: I.getType(), AllowUnknown: true)))
8989 return false;
8990
8991 SmallVector<Instruction *, 4> Insts;
8992 if (!recognizeBSwapOrBitReverseIdiom(I: &I, MatchBSwaps: false, MatchBitReversals: true, InsertedInsts&: Insts))
8993 return false;
8994 Instruction *LastInst = Insts.back();
8995 replaceAllUsesWith(Old: &I, New: LastInst, FreshBBs, IsHuge: IsHugeFunc);
8996 RecursivelyDeleteTriviallyDeadInstructions(
8997 V: &I, TLI: TLInfo, MSSAU: nullptr,
8998 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
8999 return true;
9000}
9001
9002// In this pass we look for GEP and cast instructions that are used
9003// across basic blocks and rewrite them to improve basic-block-at-a-time
9004// selection.
9005bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
9006 SunkAddrs.clear();
9007 bool MadeChange = false;
9008
9009 do {
9010 CurInstIterator = BB.begin();
9011 ModifiedDT = ModifyDT::NotModifyDT;
9012 while (CurInstIterator != BB.end()) {
9013 MadeChange |= optimizeInst(I: &*CurInstIterator++, ModifiedDT);
9014 if (ModifiedDT != ModifyDT::NotModifyDT) {
9015 // For huge function we tend to quickly go though the inner optmization
9016 // opportunities in the BB. So we go back to the BB head to re-optimize
9017 // each instruction instead of go back to the function head.
9018 if (IsHugeFunc)
9019 break;
9020 return true;
9021 }
9022 }
9023 } while (ModifiedDT == ModifyDT::ModifyInstDT);
9024
9025 bool MadeBitReverse = true;
9026 while (MadeBitReverse) {
9027 MadeBitReverse = false;
9028 for (auto &I : reverse(C&: BB)) {
9029 if (makeBitReverse(I)) {
9030 MadeBitReverse = MadeChange = true;
9031 break;
9032 }
9033 }
9034 }
9035 MadeChange |= dupRetToEnableTailCallOpts(BB: &BB, ModifiedDT);
9036
9037 return MadeChange;
9038}
9039
9040bool CodeGenPrepare::fixupDbgVariableRecordsOnInst(Instruction &I) {
9041 bool AnyChange = false;
9042 for (DbgVariableRecord &DVR : filterDbgVars(R: I.getDbgRecordRange()))
9043 AnyChange |= fixupDbgVariableRecord(I&: DVR);
9044 return AnyChange;
9045}
9046
9047// FIXME: should updating debug-info really cause the "changed" flag to fire,
9048// which can cause a function to be reprocessed?
9049bool CodeGenPrepare::fixupDbgVariableRecord(DbgVariableRecord &DVR) {
9050 if (DVR.Type != DbgVariableRecord::LocationType::Value &&
9051 DVR.Type != DbgVariableRecord::LocationType::Assign)
9052 return false;
9053
9054 // Does this DbgVariableRecord refer to a sunk address calculation?
9055 bool AnyChange = false;
9056 SmallDenseSet<Value *> LocationOps(DVR.location_ops().begin(),
9057 DVR.location_ops().end());
9058 for (Value *Location : LocationOps) {
9059 WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
9060 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
9061 if (SunkAddr) {
9062 // Point dbg.value at locally computed address, which should give the best
9063 // opportunity to be accurately lowered. This update may change the type
9064 // of pointer being referred to; however this makes no difference to
9065 // debugging information, and we can't generate bitcasts that may affect
9066 // codegen.
9067 DVR.replaceVariableLocationOp(OldValue: Location, NewValue: SunkAddr);
9068 AnyChange = true;
9069 }
9070 }
9071 return AnyChange;
9072}
9073
9074static void DbgInserterHelper(DbgVariableRecord *DVR, BasicBlock::iterator VI) {
9075 DVR->removeFromParent();
9076 BasicBlock *VIBB = VI->getParent();
9077 if (isa<PHINode>(Val: VI))
9078 VIBB->insertDbgRecordBefore(DR: DVR, Here: VIBB->getFirstInsertionPt());
9079 else
9080 VIBB->insertDbgRecordAfter(DR: DVR, I: &*VI);
9081}
9082
9083// A llvm.dbg.value may be using a value before its definition, due to
9084// optimizations in this pass and others. Scan for such dbg.values, and rescue
9085// them by moving the dbg.value to immediately after the value definition.
9086// FIXME: Ideally this should never be necessary, and this has the potential
9087// to re-order dbg.value intrinsics.
9088bool CodeGenPrepare::placeDbgValues(Function &F) {
9089 bool MadeChange = false;
9090 DominatorTree &DT = getDT();
9091
9092 auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
9093 SmallVector<Instruction *, 4> VIs;
9094 for (Value *V : DbgItem->location_ops())
9095 if (Instruction *VI = dyn_cast_or_null<Instruction>(Val: V))
9096 VIs.push_back(Elt: VI);
9097
9098 // This item may depend on multiple instructions, complicating any
9099 // potential sink. This block takes the defensive approach, opting to
9100 // "undef" the item if it has more than one instruction and any of them do
9101 // not dominate iem.
9102 for (Instruction *VI : VIs) {
9103 if (VI->isTerminator())
9104 continue;
9105
9106 // If VI is a phi in a block with an EHPad terminator, we can't insert
9107 // after it.
9108 if (isa<PHINode>(Val: VI) && VI->getParent()->getTerminator()->isEHPad())
9109 continue;
9110
9111 // If the defining instruction dominates the dbg.value, we do not need
9112 // to move the dbg.value.
9113 if (DT.dominates(Def: VI, User: Position))
9114 continue;
9115
9116 // If we depend on multiple instructions and any of them doesn't
9117 // dominate this DVI, we probably can't salvage it: moving it to
9118 // after any of the instructions could cause us to lose the others.
9119 if (VIs.size() > 1) {
9120 LLVM_DEBUG(
9121 dbgs()
9122 << "Unable to find valid location for Debug Value, undefing:\n"
9123 << *DbgItem);
9124 DbgItem->setKillLocation();
9125 break;
9126 }
9127
9128 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
9129 << *DbgItem << ' ' << *VI);
9130 DbgInserterHelper(DbgItem, VI->getIterator());
9131 MadeChange = true;
9132 ++NumDbgValueMoved;
9133 }
9134 };
9135
9136 for (BasicBlock &BB : F) {
9137 for (Instruction &Insn : llvm::make_early_inc_range(Range&: BB)) {
9138 // Process any DbgVariableRecord records attached to this
9139 // instruction.
9140 for (DbgVariableRecord &DVR : llvm::make_early_inc_range(
9141 Range: filterDbgVars(R: Insn.getDbgRecordRange()))) {
9142 if (DVR.Type != DbgVariableRecord::LocationType::Value)
9143 continue;
9144 DbgProcessor(&DVR, &Insn);
9145 }
9146 }
9147 }
9148
9149 return MadeChange;
9150}
9151
9152// Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
9153// probes can be chained dependencies of other regular DAG nodes and block DAG
9154// combine optimizations.
9155bool CodeGenPrepare::placePseudoProbes(Function &F) {
9156 bool MadeChange = false;
9157 for (auto &Block : F) {
9158 // Move the rest probes to the beginning of the block.
9159 auto FirstInst = Block.getFirstInsertionPt();
9160 while (FirstInst != Block.end() && FirstInst->isDebugOrPseudoInst())
9161 ++FirstInst;
9162 BasicBlock::iterator I(FirstInst);
9163 I++;
9164 while (I != Block.end()) {
9165 if (auto *II = dyn_cast<PseudoProbeInst>(Val: I++)) {
9166 II->moveBefore(InsertPos: FirstInst);
9167 MadeChange = true;
9168 }
9169 }
9170 }
9171 return MadeChange;
9172}
9173
9174/// Some targets prefer to split a conditional branch like:
9175/// \code
9176/// %0 = icmp ne i32 %a, 0
9177/// %1 = icmp ne i32 %b, 0
9178/// %or.cond = or i1 %0, %1
9179/// br i1 %or.cond, label %TrueBB, label %FalseBB
9180/// \endcode
9181/// into multiple branch instructions like:
9182/// \code
9183/// bb1:
9184/// %0 = icmp ne i32 %a, 0
9185/// br i1 %0, label %TrueBB, label %bb2
9186/// bb2:
9187/// %1 = icmp ne i32 %b, 0
9188/// br i1 %1, label %TrueBB, label %FalseBB
9189/// \endcode
9190/// This usually allows instruction selection to do even further optimizations
9191/// and combine the compare with the branch instruction. Currently this is
9192/// applied for targets which have "cheap" jump instructions.
9193///
9194/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
9195///
9196bool CodeGenPrepare::splitBranchCondition(Function &F) {
9197 if (!TM->Options.EnableFastISel || TLI->isJumpExpensive())
9198 return false;
9199
9200 bool MadeChange = false;
9201 for (auto &BB : F) {
9202 // Does this BB end with the following?
9203 // %cond1 = icmp|fcmp|binary instruction ...
9204 // %cond2 = icmp|fcmp|binary instruction ...
9205 // %cond.or = or|and i1 %cond1, cond2
9206 // br i1 %cond.or label %dest1, label %dest2"
9207 Instruction *LogicOp;
9208 BasicBlock *TBB, *FBB;
9209 if (!match(V: BB.getTerminator(),
9210 P: m_Br(C: m_OneUse(SubPattern: m_Instruction(I&: LogicOp)), T&: TBB, F&: FBB)))
9211 continue;
9212
9213 auto *Br1 = cast<CondBrInst>(Val: BB.getTerminator());
9214 if (Br1->getMetadata(KindID: LLVMContext::MD_unpredictable))
9215 continue;
9216
9217 // The merging of mostly empty BB can cause a degenerate branch.
9218 if (TBB == FBB)
9219 continue;
9220
9221 unsigned Opc;
9222 Value *Cond1, *Cond2;
9223 if (match(V: LogicOp,
9224 P: m_LogicalAnd(L: m_OneUse(SubPattern: m_Value(V&: Cond1)), R: m_OneUse(SubPattern: m_Value(V&: Cond2)))))
9225 Opc = Instruction::And;
9226 else if (match(V: LogicOp, P: m_LogicalOr(L: m_OneUse(SubPattern: m_Value(V&: Cond1)),
9227 R: m_OneUse(SubPattern: m_Value(V&: Cond2)))))
9228 Opc = Instruction::Or;
9229 else
9230 continue;
9231
9232 auto IsGoodCond = [](Value *Cond) {
9233 return match(
9234 V: Cond,
9235 P: m_CombineOr(Ps: m_Cmp(), Ps: m_CombineOr(Ps: m_LogicalAnd(L: m_Value(), R: m_Value()),
9236 Ps: m_LogicalOr(L: m_Value(), R: m_Value()))));
9237 };
9238 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
9239 continue;
9240
9241 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
9242
9243 // Create a new BB.
9244 auto *TmpBB =
9245 BasicBlock::Create(Context&: BB.getContext(), Name: BB.getName() + ".cond.split",
9246 Parent: BB.getParent(), InsertBefore: BB.getNextNode());
9247 if (IsHugeFunc)
9248 FreshBBs.insert(Ptr: TmpBB);
9249
9250 // Update original basic block by using the first condition directly by the
9251 // branch instruction and removing the no longer needed and/or instruction.
9252 Br1->setCondition(Cond1);
9253 LogicOp->eraseFromParent();
9254
9255 // Depending on the condition we have to either replace the true or the
9256 // false successor of the original branch instruction.
9257 if (Opc == Instruction::And)
9258 Br1->setSuccessor(idx: 0, NewSucc: TmpBB);
9259 else
9260 Br1->setSuccessor(idx: 1, NewSucc: TmpBB);
9261
9262 // Fill in the new basic block.
9263 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond: Cond2, True: TBB, False: FBB);
9264 if (auto *I = dyn_cast<Instruction>(Val: Cond2)) {
9265 I->removeFromParent();
9266 I->insertBefore(InsertPos: Br2->getIterator());
9267 }
9268
9269 // Update PHI nodes in both successors. The original BB needs to be
9270 // replaced in one successor's PHI nodes, because the branch comes now from
9271 // the newly generated BB (NewBB). In the other successor we need to add one
9272 // incoming edge to the PHI nodes, because both branch instructions target
9273 // now the same successor. Depending on the original branch condition
9274 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
9275 // we perform the correct update for the PHI nodes.
9276 // This doesn't change the successor order of the just created branch
9277 // instruction (or any other instruction).
9278 if (Opc == Instruction::Or)
9279 std::swap(a&: TBB, b&: FBB);
9280
9281 // Replace the old BB with the new BB.
9282 TBB->replacePhiUsesWith(Old: &BB, New: TmpBB);
9283
9284 // Add another incoming edge from the new BB.
9285 for (PHINode &PN : FBB->phis()) {
9286 auto *Val = PN.getIncomingValueForBlock(BB: &BB);
9287 PN.addIncoming(V: Val, BB: TmpBB);
9288 }
9289
9290 if (Loop *L = LI->getLoopFor(BB: &BB))
9291 L->addBasicBlockToLoop(NewBB: TmpBB, LI&: *LI);
9292
9293 // The edge we need to delete starts at BB and ends at whatever TBB ends
9294 // up pointing to.
9295 DTU->applyUpdates(Updates: {{DominatorTree::Insert, &BB, TmpBB},
9296 {DominatorTree::Insert, TmpBB, TBB},
9297 {DominatorTree::Insert, TmpBB, FBB},
9298 {DominatorTree::Delete, &BB, TBB}});
9299
9300 // Update the branch weights (from SelectionDAGBuilder::
9301 // FindMergedConditions).
9302 if (Opc == Instruction::Or) {
9303 // Codegen X | Y as:
9304 // BB1:
9305 // jmp_if_X TBB
9306 // jmp TmpBB
9307 // TmpBB:
9308 // jmp_if_Y TBB
9309 // jmp FBB
9310 //
9311
9312 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
9313 // The requirement is that
9314 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
9315 // = TrueProb for original BB.
9316 // Assuming the original weights are A and B, one choice is to set BB1's
9317 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
9318 // assumes that
9319 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
9320 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
9321 // TmpBB, but the math is more complicated.
9322 uint64_t TrueWeight, FalseWeight;
9323 if (extractBranchWeights(I: *Br1, TrueVal&: TrueWeight, FalseVal&: FalseWeight)) {
9324 uint64_t NewTrueWeight = TrueWeight;
9325 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
9326 setFittedBranchWeights(I&: *Br1, Weights: {NewTrueWeight, NewFalseWeight},
9327 IsExpected: hasBranchWeightOrigin(I: *Br1));
9328
9329 NewTrueWeight = TrueWeight;
9330 NewFalseWeight = 2 * FalseWeight;
9331 setFittedBranchWeights(I&: *Br2, Weights: {NewTrueWeight, NewFalseWeight},
9332 /*IsExpected=*/false);
9333 }
9334 } else {
9335 // Codegen X & Y as:
9336 // BB1:
9337 // jmp_if_X TmpBB
9338 // jmp FBB
9339 // TmpBB:
9340 // jmp_if_Y TBB
9341 // jmp FBB
9342 //
9343 // This requires creation of TmpBB after CurBB.
9344
9345 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
9346 // The requirement is that
9347 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
9348 // = FalseProb for original BB.
9349 // Assuming the original weights are A and B, one choice is to set BB1's
9350 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
9351 // assumes that
9352 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
9353 uint64_t TrueWeight, FalseWeight;
9354 if (extractBranchWeights(I: *Br1, TrueVal&: TrueWeight, FalseVal&: FalseWeight)) {
9355 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
9356 uint64_t NewFalseWeight = FalseWeight;
9357 setFittedBranchWeights(I&: *Br1, Weights: {NewTrueWeight, NewFalseWeight},
9358 /*IsExpected=*/false);
9359
9360 NewTrueWeight = 2 * TrueWeight;
9361 NewFalseWeight = FalseWeight;
9362 setFittedBranchWeights(I&: *Br2, Weights: {NewTrueWeight, NewFalseWeight},
9363 /*IsExpected=*/false);
9364 }
9365 }
9366
9367 MadeChange = true;
9368
9369 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
9370 TmpBB->dump());
9371 }
9372 return MadeChange;
9373}
9374