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