LLVM 24.0.0git
CodeGenPrepare.cpp
Go to the documentation of this file.
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
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"
22#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Statistic.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"
58#include "llvm/IR/Dominators.h"
59#include "llvm/IR/Function.h"
61#include "llvm/IR/GlobalValue.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"
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"
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"
85#include "llvm/Pass.h"
91#include "llvm/Support/Debug.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>;
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>,
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 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
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)
404INITIALIZE_PASS_END(CodeGenPrepareLegacyPass, DEBUG_TYPE,
405 "Optimize for code generation", false, false)
406
408 return new CodeGenPrepareLegacyPass();
409}
410
413 CodeGenPrepare CGP(TM);
414
415 bool Changed = CGP.run(F, AM);
416 if (!Changed)
417 return PreservedAnalyses::all();
418
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>(F);
432 LI = &AM.getResult<LoopAnalysis>(F);
435 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
436 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
437 if (!PSI)
438 reportFatalUsageError("this pass requires the profile-summary module "
439 "analysis to be available");
440 BBSectionsProfileReader =
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(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(Attribute::Hot) ||
462 PSI->isFunctionHotInCallGraph(&F, *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, *BFI) ||
468 F.hasFnAttribute(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 =
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, 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(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(F)) {
543 if (FuncIterated && !FreshBBs.contains(&BB))
544 continue;
545
546 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
547 bool Changed = optimizeBlock(BB, 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(&BB);
562 else if (FuncIterated)
563 FreshBBs.erase(&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) {
618 MadeChange |= ConstantFoldTerminator(&BB, true, nullptr, DTU);
619 if (!MadeChange)
620 continue;
621
622 for (BasicBlock *Succ : Successors)
623 if (pred_empty(Succ))
624 WorkList.insert(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();
632
633 DeleteDeadBlock(BB, DTU);
634
635 for (BasicBlock *Succ : Successors)
636 if (pred_empty(Succ))
637 WorkList.insert(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) {
653 for (BasicBlock &BB : F)
654 for (Instruction &I : BB)
655 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
656 Statepoints.push_back(SP);
657 for (auto &I : Statepoints)
658 EverMadeChange |= simplifyOffsetableRelocate(*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>(I)) {
681 MadeChange = true;
682 Value *Operand = Assume->getOperand(0);
683 Assume->eraseFromParent();
684
685 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
686 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, 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(V);
698 NewGEPBases.erase(V);
699
701 if (!GEP)
702 return;
703
704 LargeOffsetGEPID.erase(GEP);
705
706 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
707 if (VecI == LargeOffsetGEPMap.end())
708 return;
709
710 auto &GEPVector = VecI->second;
711 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
712
713 if (GEPVector.empty())
714 LargeOffsetGEPMap.erase(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(*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(F)) {
735 auto *BB = &Block;
736 if (DTU->isBBPendingDeletion(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>(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(SinglePred);
753
754 if (IsHugeFunc) {
755 // Update FreshBBs to optimize the merged BB.
756 FreshBBs.insert(SinglePred);
757 FreshBBs.erase(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(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>(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.
781 if (BBI != BB->begin()) {
782 --BBI;
783 if (!isa<PHINode>(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(LoopList, *L);
808 if (BasicBlock *Preheader = L->getLoopPreheader())
809 Preheaders.insert(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(F)) {
817 // Delete phi nodes that could block deleting other empty blocks.
818 if (Opts.cgp_delete_phis)
819 MadeChange |= DeleteDeadPHIs(&Block, TLInfo, nullptr, &KnownNonDeadPHIs);
820 }
821
822 for (auto &Block : llvm::drop_begin(F)) {
823 auto *BB = &Block;
824 if (DTU->isBBPendingDeletion(BB))
825 continue;
826 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
827 if (!DestBB ||
828 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(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() &&
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>(Pred->getTerminator()) &&
854 llvm::is_contained(successors(Pred), 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>(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>(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(DestBB)) {
893 if (DestBBPred == BB)
894 continue;
895
896 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
897 return DestPN.getIncomingValueForBlock(BB) ==
898 DestPN.getIncomingValueForBlock(DestBBPred);
899 }))
900 SameIncomingValueBBs.insert(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(Pred))
907 return true;
908
909 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
910 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
911
912 for (auto *SameValueBB : SameIncomingValueBBs)
913 if (SameValueBB->getUniquePredecessor() == Pred &&
914 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
915 BBFreq += BFI->getBlockFreq(SameValueBB);
916
917 std::optional<BlockFrequency> Limit =
918 BBFreq.mul(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>(U);
933 if (UI->getParent() != DestBB || !isa<PHINode>(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>(UI))
940 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
941 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
942 if (Insn && Insn->getParent() == BB &&
943 Insn->getParent() != UPN->getIncomingBlock(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>(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>(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(BBPN->getIncomingBlock(i));
963 } else {
964 BBPreds.insert_range(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(Pred)) { // Common predecessor?
971 for (const PHINode &PN : DestBB->phis()) {
972 const Value *V1 = PN.getIncomingValueForBlock(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>(V2))
977 if (V2PN->getParent() == BB)
978 V2 = V2PN->getIncomingValueForBlock(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,
993 bool IsHuge) {
994 auto *OldI = dyn_cast<Instruction>(Old);
995 if (OldI) {
996 for (Instruction::user_iterator UI = OldI->user_begin(),
997 E = OldI->user_end();
998 UI != E; ++UI) {
1000 if (IsHuge)
1001 FreshBBs.insert(User->getParent());
1002 }
1003 }
1004 Old->replaceAllUsesWith(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>(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(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(SinglePred);
1032 FreshBBs.erase(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, 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>(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(InValPhi->getIncomingValue(i),
1051 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>(BB->begin())) {
1056 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1057 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1058 } else {
1059 for (BasicBlock *Pred : predecessors(BB))
1060 PN.addIncoming(InVal, Pred);
1061 }
1062 }
1063 }
1064
1065 // Preserve loop Metadata.
1066 if (BI->hasMetadata(LLVMContext::MD_loop)) {
1067 for (auto *Pred : predecessors(BB))
1068 Pred->getTerminator()->copyMetadata(*BI, LLVMContext::MD_loop);
1069 }
1070
1071 // The PHIs are now updated, change everything that refers to BB to use
1072 // DestBB and remove BB.
1074 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1075 SmallPtrSet<BasicBlock *, 8> PredOfDestBB(llvm::from_range,
1076 predecessors(DestBB));
1077 for (auto *Pred : predecessors(BB)) {
1078 if (!PredOfDestBB.contains(Pred)) {
1079 if (SeenPreds.insert(Pred).second)
1080 DTUpdates.push_back({DominatorTree::Insert, Pred, DestBB});
1081 }
1082 }
1083 SeenPreds.clear();
1084 for (auto *Pred : predecessors(BB)) {
1085 if (SeenPreds.insert(Pred).second)
1086 DTUpdates.push_back({DominatorTree::Delete, Pred, BB});
1087 }
1088 DTUpdates.push_back({DominatorTree::Delete, BB, DestBB});
1089 BB->replaceAllUsesWith(DestBB);
1090 DTU->applyUpdates(DTUpdates);
1091 DTU->deleteBB(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
1101 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
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
1108 for (auto *ThisRelocate : AllRelocateCalls) {
1109 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1110 ThisRelocate->getDerivedPtrIndex());
1111 RelocateIdxMap.insert(std::make_pair(K, 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(Key.first, Key.first);
1121
1122 // We're iterating over RelocateIdxMap so we cannot modify it.
1123 auto MaybeBase = RelocateIdxMap.find(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(I);
1130 }
1131}
1132
1133// Accepts a GEP and extracts the operands into a vector provided they're all
1134// small integer constants
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>(GEP->getOperand(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(GEP->getOperand(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
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>(R))
1164 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1165 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1166 RelocatedBase->moveBefore(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>(ToReplace->getDerivedPtr());
1189 if (!Derived || Derived->getPointerOperand() != Base)
1190 continue;
1191
1193 if (!getGEPSmallConstantIntOffsetV(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(RelocatedBase, Base->getType());
1230 }
1231 Value *Replacement =
1232 Builder.CreateGEP(Derived->getSourceElementType(), ActualRelocatedBase,
1233 ArrayRef(OffsetV));
1234 Replacement->takeName(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(Replacement, ToReplace->getType());
1242 }
1243 ToReplace->replaceAllUsesWith(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>(U))
1273 // Collect all the relocate calls associated with a statepoint
1274 AllRelocateCalls.push_back(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(Item.first, 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.
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();
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>(User)) {
1312 UserBB = PN->getIncomingBlock(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>(CI->clone());
1340 InsertedCast->insertBefore(*UserBB, 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(*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>(BCI->getOperand(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, SrcTy);
1370 EVT DestVT = TLI.getValueType(DL, 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(BCI->getContext(), SrcVT) <=
1378 TLI.getNumRegisters(BCI->getContext(), 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(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>(SrcInst) ? SrcBB->getFirstInsertionPt()
1396 : std::next(SrcInst->getIterator());
1397 BCI->moveBefore(*SrcBB, 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.
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>(CI)) {
1412 if (!TLI.isFreeAddrSpaceCast(DL, ASC->getSrcAddressSpace(),
1413 ASC->getDestAddressSpace()))
1414 return false;
1415 }
1416
1417 // If this is a noop copy,
1418 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1419 EVT DstVT = TLI.getValueType(DL, 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(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(CI->getContext(), SrcVT) ==
1435 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1436 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1438 DstVT = TLI.getTypeToTransformTo(CI->getContext(), 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(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1454 m_Instruction(LHS), m_Constant(Step)))))
1455 return true;
1456 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1458 m_Instruction(LHS), m_Constant(Step))))) {
1459 Step = ConstantExpr::getNeg(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(PN->getParent());
1471 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1472 return std::nullopt;
1473 auto *IVInc =
1474 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1475 if (!IVInc || LI->getLoopFor(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(IVInc, Step);
1481 return std::nullopt;
1482}
1483
1484static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1485 auto *I = dyn_cast<Instruction>(V);
1486 if (!I)
1487 return false;
1488 Instruction *LHS = nullptr;
1489 Constant *Step = nullptr;
1490 if (!matchIncrement(I, LHS, Step))
1491 return false;
1492 if (auto *PN = dyn_cast<PHINode>(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(BO, LI))
1504 return false;
1505 const Loop *L = LI->getLoopFor(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(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(Cmp->getParent(), 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(Cmp->getParent(), 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");
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(IID, Arg0, Arg1);
1566 if (BO->getOpcode() != Instruction::Xor) {
1567 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1568 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1569 } else
1570 assert(BO->hasOneUse() &&
1571 "Patterns with XOr should use the BO only in the compare");
1572 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1573 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1574 Cmp->eraseFromParent();
1575 BO->eraseFromParent();
1576 return true;
1577}
1578
1579/// Match special-case patterns that check for unsigned add overflow.
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(0), *B = Cmp->getOperand(1);
1585
1586 // We are not expecting non-canonical/degenerate code. Just bail out.
1587 if (isa<Constant>(A))
1588 return false;
1589
1590 ICmpInst::Predicate Pred = Cmp->getPredicate();
1591 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1592 B = ConstantInt::get(B->getType(), 1);
1593 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1594 B = Constant::getAllOnesValue(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(U, m_Add(m_Specific(A), m_Specific(B)))) {
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(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1618 return false;
1619 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1620 A = Add->getOperand(0);
1621 B = Add->getOperand(1);
1622 EdgeCase = true;
1623 }
1624
1626 TLI->getValueType(*DL, Add->getType()),
1627 Add->hasNUsesOrMore(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(Add, A, B, Cmp,
1637 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(0), *B = Cmp->getOperand(1);
1649 if (isa<Constant>(A) && isa<Constant>(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, 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(B, m_ZeroInt())) {
1660 B = ConstantInt::get(B->getType(), 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(B, m_ZeroInt())) {
1665 std::swap(A, 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>(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(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1680 break;
1681 }
1682
1683 // A + (-C), A u< C (canonicalized form of (sub A, C))
1684 const APInt *CmpC, *AddC;
1685 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1686 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1688 break;
1689 }
1690 }
1691 if (!Sub)
1692 return false;
1693
1695 TLI->getValueType(*DL, Sub->getType()),
1696 Sub->hasNUsesOrMore(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(Sub, Sub->getOperand(0), Sub->getOperand(1),
1706 Cmp, 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(Cmp, m_ICmp(Pred, m_Ctpop(m_Value(X)), m_APIntAllowPoison(C))))
1724 return false;
1725
1726 // We're only interested in "is power of 2 [or zero]" patterns.
1727 bool IsStrictlyPowerOf2Test = ICmpInst::isEquality(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(TLI->getValueType(*DL, OpTy))) {
1738 // Look for `ctpop(x) ==/!= 1`, where `ctpop(x)` is known to be non-zero.
1739 if (!IsStrictlyPowerOf2Test || !isKnownNonZero(Cmp->getOperand(0), *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(1, ConstantInt::get(OpTy, 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(Cmp->getOperand(0), *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(X, Constant::getAllOnesValue(OpTy));
1760 Value *And = Builder.CreateAnd(X, Sub);
1761 CmpInst::Predicate NewPred =
1762 (Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_EQ)
1764 : CmpInst::ICMP_NE;
1765 NewCmp = Builder.CreateICmp(NewPred, And, ConstantInt::getNullValue(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(X, Constant::getAllOnesValue(OpTy));
1771 Value *Xor = Builder.CreateXor(X, Sub);
1772 CmpInst::Predicate NewPred =
1774 NewCmp = Builder.CreateICmp(NewPred, Xor, Sub);
1775 }
1776
1777 Cmp->replaceAllUsesWith(NewCmp);
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(EVT::getEVT(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>(Cmp))
1795 return false;
1796
1797 bool UsedInPhiOrCurrentBlock = any_of(Cmp->users(), [Cmp](User *U) {
1798 return isa<PHINode>(U) ||
1799 cast<Instruction>(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(0)->getType()->isIntegerTy() &&
1805 Cmp->getOperand(0)->getType()->getScalarSizeInBits() >
1806 DL.getLargestLegalIntTypeSizeInBits())
1807 return false;
1808
1809 // Only insert a cmp in each block once.
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();
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>(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(Cmp->getOpcode(), Cmp->getPredicate(),
1840 Cmp->getOperand(0), Cmp->getOperand(1), "");
1841 InsertedCmp->insertBefore(*UserBB, 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.
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>(U))
1893 continue;
1894 if (isa<SelectInst>(U) && cast<SelectInst>(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(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1912 return false;
1913 if (CmpBB != FalseBB)
1914 return false;
1915
1916 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1917 CmpPredicate DomPred;
1918 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(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>(U)) {
1932 BI->swapSuccessors();
1933 continue;
1934 }
1935 if (auto *SI = dyn_cast<SelectInst>(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(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.
1950 Value *Op0 = Cmp->getOperand(0);
1951 Value *Op1 = Cmp->getOperand(1);
1952 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Op0) ||
1953 isa<Constant>(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(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
1966 GoodToSwap++;
1967 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(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>(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, Cmp->getOperand(0)->getType());
1986 if (TLI.isFAbsFree(VT) &&
1988 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(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
1997 FCmp->getOperand(0), FCmp->getOperand(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(ClassVal, ClassTest);
2006 Cmp->replaceAllUsesWith(IsFPClass);
2008 return true;
2009}
2010
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(Rem, m_URem(m_Value(Incr), m_Value(RemAmt))))
2017 return false;
2018
2019 Value *AddInst, *AddOffset;
2020 // Find out loop increment PHI.
2021 PHINode *PN = dyn_cast<PHINode>(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(Incr, m_c_NUWAdd(m_Phi(PN), m_Value(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(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(Rem))
2047 return false;
2048
2049 // Only works if the remainder amount is a loop invaraint
2050 if (!L->isLoopInvariant(RemAmt))
2051 return false;
2052
2053 // Only works if the AddOffset is a loop invaraint
2054 if (AddOffset && !L->isLoopInvariant(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(LoopIncrInfo->second, m_One()))
2066 return false;
2067
2068 // Need the increment to not overflow.
2069 if (!match(LoopIncrInfo->first, m_c_NUWAdd(m_Specific(PN), 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;
2092 const LoopInfo *LI,
2094 bool IsHuge) {
2095 Value *AddOffset, *RemAmt, *AddInst;
2096 PHINode *LoopIncrPN;
2097 if (!isRemOfLoopIncrementWithLoopInvariant(Rem, LI, RemAmt, AddInst,
2098 AddOffset, 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(RemAmt, m_ImmConstant()))
2112 return false;
2113
2114 Loop *L = LI->getLoopFor(LoopIncrPN->getParent());
2115 Value *Start = LoopIncrPN->getIncomingValueForBlock(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(Start, AddOffset,
2127 match(AddInst, m_NSWAdd(m_Value(), m_Value())),
2128 /*IsNUW=*/true, *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(Start, RemAmt, *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, 2);
2142
2143 Builder.SetInsertPoint(cast<Instruction>(
2144 LoopIncrPN->getIncomingValueForBlock(L->getLoopLatch())));
2145 // `(add (urem x, y), 1)` is always nuw.
2146 Value *RemAdd = Builder.CreateNUWAdd(NewRem, ConstantInt::get(Ty, 1));
2147 Value *RemCmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, RemAdd, RemAmt);
2148 Value *RemSel =
2149 Builder.CreateSelect(RemCmp, Constant::getNullValue(Ty), RemAdd);
2150
2151 NewRem->addIncoming(Start, L->getLoopPreheader());
2152 NewRem->addIncoming(RemSel, L->getLoopLatch());
2153
2154 // Insert all touched BBs.
2155 FreshBBs.insert(LoopIncrPN->getParent());
2156 FreshBBs.insert(L->getLoopLatch());
2157 FreshBBs.insert(Rem->getParent());
2158 if (AddInst)
2159 FreshBBs.insert(cast<Instruction>(AddInst)->getParent());
2160 replaceAllUsesWith(Rem, NewRem, FreshBBs, IsHuge);
2161 Rem->eraseFromParent();
2162 if (AddInst && AddInst->use_empty())
2163 cast<Instruction>(AddInst)->eraseFromParent();
2164 return true;
2165}
2166
2167bool CodeGenPrepare::optimizeURem(Instruction *Rem) {
2168 if (foldURemOfLoopIncrement(Rem, DL, LI, FreshBBs, IsHugeFunc))
2169 return true;
2170 return false;
2171}
2172
2173bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
2174 if (sinkCmpExpression(Cmp, *TLI, *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, Opts.cgp_icmp_eq2icmp_st))
2187 return true;
2188
2190 return true;
2191
2192 if (foldFCmpToFPClassTest(Cmp, *TLI, *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.
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>(*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>(AndI->getOperand(0)) &&
2219 !isa<ConstantInt>(AndI->getOperand(1)) &&
2220 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
2221 return false;
2222
2223 for (auto *U : AndI->users()) {
2225
2226 // Only sink 'and' feeding icmp with 0.
2227 if (!isa<ICmpInst>(User))
2228 return false;
2229
2230 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
2231 if (!CmpC || !CmpC->isZero())
2232 return false;
2233 }
2234
2235 if (!TLI.isMaskAndCmp0FoldingBeneficial(*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();
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 Instruction::And, AndI->getOperand(0), AndI->getOperand(1), "",
2259 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
2280 if (!isa<TruncInst>(User)) {
2281 if (User->getOpcode() != Instruction::And ||
2283 return false;
2284
2285 const APInt &Cimm = cast<ConstantInt>(User->getOperand(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
2297 const TargetLowering &TLI, const DataLayout &DL) {
2298 BasicBlock *UserBB = User->getParent();
2300 auto *TruncI = cast<TruncInst>(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>(*TruncUI);
2309 // Preincrement use iterator so we don't invalidate it.
2310
2311 ++TruncUI;
2312
2313 int ISDOpcode = TLI.InstructionOpcodeToISD(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.
2323 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2324 continue;
2325
2326 // Don't bother for PHI nodes.
2327 if (isa<PHINode>(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(ShiftI->getOperand(0), CI, "");
2345 else
2346 InsertedShift =
2347 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2348 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2349 InsertedShift->insertBefore(*TruncUserBB, 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(), InsertedShift,
2359 TruncI->getType(), "");
2360 InsertedTrunc->insertBefore(*TruncUserBB, 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.
2389 const TargetLowering &TLI,
2390 const DataLayout &DL) {
2391 BasicBlock *DefBB = ShiftI->getParent();
2392
2393 /// Only insert instructions in each block once.
2395
2396 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, 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();
2404 // Preincrement use iterator so we don't invalidate it.
2405 ++UI;
2406
2407 // Don't bother for PHI nodes.
2408 if (isa<PHINode>(User))
2409 continue;
2410
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>(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(TLI.getValueType(DL, 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(ShiftI->getOperand(0), CI, "");
2451 else
2452 InsertedShift =
2453 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2454 InsertedShift->insertBefore(*UserBB, 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(*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,
2496 bool IsHugeFunc) {
2497 // If a zero input is undefined, it doesn't make sense to despeculate that.
2498 if (match(CountZeros->getOperand(1), 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(0);
2515 if (isKnownNonZero(Op, *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(StartBlock, CountZeros, DTU, LI,
2521 /* MSSAU */ nullptr, "cond.false");
2522 if (IsHugeFunc)
2523 FreshBBs.insert(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(BasicBlock::iterator(CountZeros));
2529 // Any debug-info after CountZeros should not be included.
2530 SplitPt.setHeadBit(true);
2531 BasicBlock *EndBlock = SplitBlock(CallBlock, &*SplitPt, DTU, LI,
2532 /* MSSAU */ nullptr, "cond.end");
2533 if (IsHugeFunc)
2534 FreshBBs.insert(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.
2545 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2546 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2547 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2548 StartBlock->getTerminator()->eraseFromParent();
2549 DTU->applyUpdates({{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, 2, "ctz");
2555 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2556 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2557 PN->addIncoming(BitWidth, StartBlock);
2558 PN->addIncoming(CountZeros, 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(1, 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(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 cast<PointerType>(Arg->getType())->getAddressSpace()),
2589 0);
2590 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2591 uint64_t Offset2 = Offset.getLimitedValue();
2592 if (!isAligned(PrefAlign, Offset2))
2593 continue;
2594 AllocaInst *AI;
2595 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign) {
2596 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(*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) < PrefAlign &&
2607 GV->getGlobalSize(*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>(CI)) {
2614 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2615 MaybeAlign MIDestAlign = MI->getDestAlign();
2616 if (!MIDestAlign || DestAlign > *MIDestAlign)
2617 MI->setDestAlignment(DestAlign);
2618 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2619 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2620 Align SrcAlign = getKnownAlignment(MTI->getSource(), *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(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(CI, Arg, Arg->getType(), AS))
2637 return true;
2638 }
2639
2640 IntrinsicInst *II = dyn_cast<IntrinsicInst>(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(II->getContext());
2658 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2659 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, 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>(CI->getArgOperand(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(CI->getIterator());
2675 // Mark this instruction as "inserted by CGP", so that other
2676 // optimizations don't touch it.
2677 InsertedInsts.insert(ExtVal);
2678 return true;
2679 }
2680
2681 case Intrinsic::launder_invariant_group: {
2682 Value *ArgVal = II->getArgOperand(0);
2683 auto it = LargeOffsetGEPMap.find(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(GEPs.begin(), GEPs.end());
2690 LargeOffsetGEPMap.erase(II);
2691 }
2692
2693 replaceAllUsesWith(II, ArgVal, FreshBBs, 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(II, DTU, LI, TLI, DL, ModifiedDT, FreshBBs,
2701 IsHugeFunc);
2702 case Intrinsic::fshl:
2703 case Intrinsic::fshr:
2704 return optimizeFunnelShift(II);
2705 case Intrinsic::masked_gather:
2706 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2707 case Intrinsic::masked_scatter:
2708 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2709 case Intrinsic::masked_load:
2710 // Treat v1X masked load as load X type.
2711 if (auto *VT = dyn_cast<FixedVectorType>(II->getType())) {
2712 if (VT->getNumElements() == 1) {
2713 Value *PtrVal = II->getArgOperand(0);
2714 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2715 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), 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>(II->getArgOperand(0)->getType())) {
2724 if (VT->getNumElements() == 1) {
2725 Value *PtrVal = II->getArgOperand(1);
2726 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2727 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2728 return true;
2729 }
2730 }
2731 return false;
2732 case Intrinsic::umul_with_overflow:
2733 return optimizeMulWithOverflow(II, /*IsSigned=*/false, ModifiedDT);
2734 case Intrinsic::smul_with_overflow:
2735 return optimizeMulWithOverflow(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(II, PtrVal, AccessTy, 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, Builder)) {
2761 replaceAllUsesWith(CI, V, FreshBBs, 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>(BB.getTerminator())) {
2777 if (auto *V = dyn_cast<GlobalVariable>(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(RV->uses())) {
2795 auto *I = dyn_cast<Instruction>(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(I)) {
2802 U.set(CI);
2803 MadeChange = true;
2804 }
2805 }
2806
2807 return MadeChange;
2808 }
2809 }
2810
2811 return false;
2812}
2813
2815 const CallInst *CI) {
2816 assert(CI && CI->use_empty());
2817
2818 if (const auto *II = dyn_cast<IntrinsicInst>(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(*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>(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>(V);
2889 if (BCI)
2890 V = BCI->getOperand(0);
2891
2893 if (EVI) {
2894 V = EVI->getOperand(0);
2895 if (!llvm::all_of(EVI->indices(), equal_to(0)))
2896 return false;
2897 }
2898
2899 PN = dyn_cast<PHINode>(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>(Inst);
2907 if (BC && BC->hasOneUse())
2908 Inst = BC->user_back();
2909
2910 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
2911 return II->getIntrinsicID() == Intrinsic::lifetime_end;
2912 return false;
2913 };
2914
2916
2917 auto isFakeUse = [&FakeUses](const Instruction *Inst) {
2918 if (auto *II = dyn_cast<IntrinsicInst>(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>(II->getOperand(0))) {
2928 FakeUses.push_back(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.
2939 // Skip over pseudo-probes and the bitcast.
2940 while (&*BI == BCI || &*BI == EVI || isa<PseudoProbeInst>(BI) ||
2941 isLifetimeEndOrBitCastFor(&*BI) || isFakeUse(&*BI))
2942 BI = std::next(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.
2957 if (PN) {
2958 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2959 // Look through bitcasts.
2960 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2961 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
2962 BasicBlock *PredBB = PN->getIncomingBlock(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(PredBB);
2967 CallInsts.push_back(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)
2981 PredBB->getTerminator()->getPrevNode());
2982
2983 if (CI && CI->use_empty() &&
2984 isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
2985 IncomingVal == CI->getArgOperand(0) &&
2986 MayBePermittedAsTailCall(CI)) {
2987 TailCallBBs.push_back(PredBB);
2988 CallInsts.push_back(CI);
2989 }
2990 }
2991 }
2992 } else {
2993 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
2994 for (BasicBlock *Pred : predecessors(BB)) {
2995 if (!VisitedBBs.insert(Pred).second)
2996 continue;
2997 if (Instruction *I = Pred->rbegin()->getPrevNode()) {
2998 CallInst *CI = dyn_cast<CallInst>(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>(V) ||
3003 (isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3004 V == CI->getArgOperand(0))) {
3005 TailCallBBs.push_back(Pred);
3006 CallInsts.push_back(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>(TailCallBB->getTerminator());
3018 if (!BI || BI->getSuccessor() != BB)
3019 continue;
3020
3021 // Duplicate the return into TailCallBB.
3022 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB, DTU);
3023 assert(!Opts.cgp_verify_bfi_updates ||
3024 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
3025 BFI->setBlockFreq(BB,
3026 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(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(CI->getIterator());
3040 }
3041 }
3042 DTU->deleteBB(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(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(IntPtrTy, 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(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(Point.PrevInst);
3308 } else {
3309 BasicBlock::iterator Position = Point.BB->getFirstInsertionPt();
3310 if (Inst->getParent())
3311 Inst->moveBefore(*Point.BB, Position);
3312 else
3313 Inst->insertBefore(*Point.BB, Position);
3314 }
3315
3316 Inst->getParent()->reinsertInstInDbgRecords(Inst, 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(Idx);
3336 Inst->setOperand(Idx, 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(Idx, 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(NumOpnds);
3360 for (unsigned It = 0; It < NumOpnds; ++It) {
3361 // Save the current operand.
3362 Value *Val = Inst->getOperand(It);
3363 OriginalValues.push_back(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(It, PoisonValue::get(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(It, 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(Opnd, Ty, "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(Opnd, Ty, "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(Opnd, Ty, "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(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(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).
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
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>(U.getUser());
3514 OriginalUses.push_back(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(Inst, DbgVariableRecords);
3519
3520 // Now, we can replace the uses.
3521 Inst->replaceAllUsesWith(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(Use.Idx, 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(New, 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(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(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.
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(std::make_unique<TypePromotionTransaction::OperandSetter>(
3646 Inst, Idx, NewVal));
3647}
3648
3649void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3650 Value *NewVal) {
3651 Actions.push_back(
3652 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3653 Inst, RemovedInsts, NewVal));
3654}
3655
3656void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3657 Value *New) {
3658 Actions.push_back(
3659 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3660}
3661
3662void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3663 Actions.push_back(
3664 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, 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(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(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(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(V, 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.
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(std::make_pair(Ptr, NodeList.size())).second) {
3872 NodeList.push_back(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(Ptr)) {
3883 SkipRemovedElements(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(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(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(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(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({From, To}); }
3978
3979 void ReplacePhi(PHINode *From, PHINode *To) {
3980 Value *OldReplacement = Get(From);
3981 while (OldReplacement != From) {
3982 From = To;
3983 To = dyn_cast<PHINode>(OldReplacement);
3984 OldReplacement = Get(From);
3985 }
3986 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
3987 Put(From, To);
3988 From->replaceAllUsesWith(To);
3989 AllPhiNodes.erase(From);
3990 From->eraseFromParent();
3991 }
3992
3993 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
3994
3995 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3996
3997 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(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(CommonType);
4006 for (auto *I : AllPhiNodes) {
4007 I->replaceAllUsesWith(Dummy);
4008 I->eraseFromParent();
4009 }
4010 AllPhiNodes.clear();
4011 for (auto *I : AllSelectNodes) {
4012 I->replaceAllUsesWith(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.
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(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(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(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(DifferentField, 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>(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(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(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(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, Opts.cgp_addr_sink_new_phis, PhiNotMatchedCount)) {
4229 ST.destroyNewNodes(CommonType);
4230 return nullptr;
4231 }
4232
4233 auto *Result = ST.Get(Map.find(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({PHI, Candidate});
4248 SmallPtrSet<PHINode *, 8> MatchedPHIs;
4249 MatchedPHIs.insert(PHI);
4250 WorkList.push_back({PHI, Candidate});
4251 SmallSet<PHIPair, 8> Visited;
4252 while (!WorkList.empty()) {
4253 auto Item = WorkList.pop_back_val();
4254 if (!Visited.insert(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(B);
4263 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
4264 if (FirstValue == SecondValue)
4265 continue;
4266
4267 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
4268 PHINode *SecondPhi = dyn_cast<PHINode>(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(FirstPhi) ||
4275 FirstPhi->getParent() != SecondPhi->getParent())
4276 return false;
4277
4278 // If we already matched them then continue.
4279 if (Matcher.count({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(FirstPhi).second)
4285 Matcher.insert({FirstPhi, SecondPhi});
4286 // But me must check it.
4287 WorkList.push_back({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(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(&P))
4316 continue;
4317 if ((IsMatched = MatchPhiNode(PHI, &P, 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(llvm::make_first_range(Matched));
4323 Matched.clear();
4324 }
4325 if (IsMatched) {
4326 // Replace all matched values and erase them.
4327 for (auto MV : Matched)
4328 ST.ReplacePhi(MV.first, 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(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>(V)) {
4352 // CurrentValue also must be Select.
4353 auto *CurrentSelect = cast<SelectInst>(Current);
4354 auto *TrueValue = CurrentSelect->getTrueValue();
4355 assert(Map.contains(TrueValue) && "No True Value!");
4356 Select->setTrueValue(ST.Get(Map[TrueValue]));
4357 auto *FalseValue = CurrentSelect->getFalseValue();
4358 assert(Map.contains(FalseValue) && "No False Value!");
4359 Select->setFalseValue(ST.Get(Map[FalseValue]));
4360 } else {
4361 // Must be a Phi node then.
4362 auto *PHI = cast<PHINode>(V);
4363 // Fill the Phi node with values from predecessors.
4364 for (auto *B : predecessors(PHI->getParent())) {
4365 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
4366 assert(Map.contains(PV) && "No predecessor Value!");
4367 PHI->addIncoming(ST.Get(Map[PV]), 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(CommonType);
4385 Worklist.push_back(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(Current))
4390 continue;
4391 TraverseOrder.push_back(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>(Current)) {
4396 // Is it OK to get metadata from OrigSelect?!
4397 // Create a Select placeholder with dummy value.
4398 SelectInst *Select =
4399 SelectInst::Create(CurrentSelect->getCondition(), Dummy, Dummy,
4400 CurrentSelect->getName(),
4401 CurrentSelect->getIterator(), CurrentSelect);
4402 Map[Current] = Select;
4403 ST.insertNewSelect(Select);
4404 // We are interested in True and False values.
4405 Worklist.push_back(CurrentSelect->getTrueValue());
4406 Worklist.push_back(CurrentSelect->getFalseValue());
4407 } else {
4408 // It must be a Phi node then.
4409 PHINode *CurrentPhi = cast<PHINode>(Current);
4410 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4411 PHINode *PHI =
4412 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi->getIterator());
4413 Map[Current] = PHI;
4414 ST.insertNewPhi(PHI);
4415 append_range(Worklist, 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(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, TestAddrMode, 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>(ScaleReg) && // not a constant expr.
4479 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
4480 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(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, TestAddrMode, AccessTy, AddrSpace)) {
4488 AddrModeInsts.push_back(cast<Instruction>(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>(V);
4501 if (!PN)
4502 return std::nullopt;
4503 auto IVInc = getIVIncrement(PN, &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>(IVInc->first))
4513 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4514 return std::nullopt;
4515 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4516 return std::make_pair(IVInc->first, 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(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, TestAddrMode, AccessTy, AddrSpace) &&
4549 getDTFn().dominates(IVInc, MemoryInst)) {
4550 AddrModeInsts.push_back(cast<Instruction>(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.
4569 switch (I->getOpcode()) {
4570 case Instruction::BitCast:
4571 case Instruction::AddrSpaceCast:
4572 // Don't touch identity bitcasts.
4573 if (I->getType() == I->getOperand(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::Or:
4585 return cast<PossiblyDisjointInst>(I)->isDisjoint();
4586 case Instruction::Mul:
4587 case Instruction::Shl:
4588 // Can only handle X*C and X << C.
4589 return isa<ConstantInt>(I->getOperand(1));
4590 case Instruction::GetElementPtr:
4591 return true;
4592 default:
4593 return false;
4594 }
4595}
4596
4597/// Check whether or not \p Val is a legal instruction for \p TLI.
4598/// \note \p Val is assumed to be the product of some type promotion.
4599/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4600/// to be legal, as the non-promoted value would have had the same state.
4602 const DataLayout &DL, Value *Val) {
4603 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4604 if (!PromotedInst)
4605 return false;
4606 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4607 // If the ISDOpcode is undefined, it was undefined before the promotion.
4608 if (!ISDOpcode)
4609 return true;
4610 // Otherwise, check if the promoted instruction is legal or not.
4611 return TLI.isOperationLegalOrCustom(
4612 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4613}
4614
4615namespace {
4616
4617/// Hepler class to perform type promotion.
4618class TypePromotionHelper {
4619 /// Utility function to add a promoted instruction \p ExtOpnd to
4620 /// \p PromotedInsts and record the type of extension we have seen.
4621 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4622 Instruction *ExtOpnd, bool IsSExt) {
4623 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4624 auto [It, Inserted] = PromotedInsts.try_emplace(ExtOpnd);
4625 if (!Inserted) {
4626 // If the new extension is same as original, the information in
4627 // PromotedInsts[ExtOpnd] is still correct.
4628 if (It->second.getInt() == ExtTy)
4629 return;
4630
4631 // Now the new extension is different from old extension, we make
4632 // the type information invalid by setting extension type to
4633 // BothExtension.
4634 ExtTy = BothExtension;
4635 }
4636 It->second = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4637 }
4638
4639 /// Utility function to query the original type of instruction \p Opnd
4640 /// with a matched extension type. If the extension doesn't match, we
4641 /// cannot use the information we had on the original type.
4642 /// BothExtension doesn't match any extension type.
4643 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4644 Instruction *Opnd, bool IsSExt) {
4645 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4646 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4647 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4648 return It->second.getPointer();
4649 return nullptr;
4650 }
4651
4652 /// Utility function to check whether or not a sign or zero extension
4653 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4654 /// either using the operands of \p Inst or promoting \p Inst.
4655 /// The type of the extension is defined by \p IsSExt.
4656 /// In other words, check if:
4657 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4658 /// #1 Promotion applies:
4659 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4660 /// #2 Operand reuses:
4661 /// ext opnd1 to ConsideredExtType.
4662 /// \p PromotedInsts maps the instructions to their type before promotion.
4663 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4664 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4665
4666 /// Utility function to determine if \p OpIdx should be promoted when
4667 /// promoting \p Inst.
4668 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4669 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4670 }
4671
4672 /// Utility function to promote the operand of \p Ext when this
4673 /// operand is a promotable trunc or sext or zext.
4674 /// \p PromotedInsts maps the instructions to their type before promotion.
4675 /// \p CreatedInstsCost[out] contains the cost of all instructions
4676 /// created to promote the operand of Ext.
4677 /// Newly added extensions are inserted in \p Exts.
4678 /// Newly added truncates are inserted in \p Truncs.
4679 /// Should never be called directly.
4680 /// \return The promoted value which is used instead of Ext.
4681 static Value *promoteOperandForTruncAndAnyExt(
4682 Instruction *Ext, TypePromotionTransaction &TPT,
4683 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4684 SmallVectorImpl<Instruction *> *Exts,
4685 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4686
4687 /// Utility function to promote the operand of \p Ext when this
4688 /// operand is promotable and is not a supported trunc or sext.
4689 /// \p PromotedInsts maps the instructions to their type before promotion.
4690 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4691 /// created to promote the operand of Ext.
4692 /// Newly added extensions are inserted in \p Exts.
4693 /// Newly added truncates are inserted in \p Truncs.
4694 /// Should never be called directly.
4695 /// \return The promoted value which is used instead of Ext.
4696 static Value *promoteOperandForOther(Instruction *Ext,
4697 TypePromotionTransaction &TPT,
4698 InstrToOrigTy &PromotedInsts,
4699 unsigned &CreatedInstsCost,
4700 SmallVectorImpl<Instruction *> *Exts,
4701 SmallVectorImpl<Instruction *> *Truncs,
4702 const TargetLowering &TLI, bool IsSExt);
4703
4704 /// \see promoteOperandForOther.
4705 static Value *signExtendOperandForOther(
4706 Instruction *Ext, TypePromotionTransaction &TPT,
4707 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4708 SmallVectorImpl<Instruction *> *Exts,
4709 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4710 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4711 Exts, Truncs, TLI, true);
4712 }
4713
4714 /// \see promoteOperandForOther.
4715 static Value *zeroExtendOperandForOther(
4716 Instruction *Ext, TypePromotionTransaction &TPT,
4717 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4718 SmallVectorImpl<Instruction *> *Exts,
4719 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4720 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4721 Exts, Truncs, TLI, false);
4722 }
4723
4724public:
4725 /// Type for the utility function that promotes the operand of Ext.
4726 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4727 InstrToOrigTy &PromotedInsts,
4728 unsigned &CreatedInstsCost,
4729 SmallVectorImpl<Instruction *> *Exts,
4730 SmallVectorImpl<Instruction *> *Truncs,
4731 const TargetLowering &TLI);
4732
4733 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4734 /// action to promote the operand of \p Ext instead of using Ext.
4735 /// \return NULL if no promotable action is possible with the current
4736 /// sign extension.
4737 /// \p InsertedInsts keeps track of all the instructions inserted by the
4738 /// other CodeGenPrepare optimizations. This information is important
4739 /// because we do not want to promote these instructions as CodeGenPrepare
4740 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4741 /// \p PromotedInsts maps the instructions to their type before promotion.
4742 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4743 const TargetLowering &TLI,
4744 const InstrToOrigTy &PromotedInsts);
4745};
4746
4747} // end anonymous namespace
4748
4749bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4750 Type *ConsideredExtType,
4751 const InstrToOrigTy &PromotedInsts,
4752 bool IsSExt) {
4753 // The promotion helper does not know how to deal with vector types yet.
4754 // To be able to fix that, we would need to fix the places where we
4755 // statically extend, e.g., constants and such.
4756 if (Inst->getType()->isVectorTy())
4757 return false;
4758
4759 // We can always get through zext.
4760 if (isa<ZExtInst>(Inst))
4761 return true;
4762
4763 // sext(sext) is ok too.
4764 if (IsSExt && isa<SExtInst>(Inst))
4765 return true;
4766
4767 // We can get through binary operator, if it is legal. In other words, the
4768 // binary operator must have a nuw or nsw flag.
4769 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4770 if (isa<OverflowingBinaryOperator>(BinOp) &&
4771 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4772 (IsSExt && BinOp->hasNoSignedWrap())))
4773 return true;
4774
4775 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4776 if ((Inst->getOpcode() == Instruction::And ||
4777 Inst->getOpcode() == Instruction::Or))
4778 return true;
4779
4780 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4781 if (Inst->getOpcode() == Instruction::Xor) {
4782 // Make sure it is not a NOT.
4783 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4784 if (!Cst->getValue().isAllOnes())
4785 return true;
4786 }
4787
4788 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4789 // It may change a poisoned value into a regular value, like
4790 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4791 // poisoned value regular value
4792 // It should be OK since undef covers valid value.
4793 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4794 return true;
4795
4796 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4797 // It may change a poisoned value into a regular value, like
4798 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4799 // poisoned value regular value
4800 // It should be OK since undef covers valid value.
4801 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4802 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4803 if (ExtInst->hasOneUse()) {
4804 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4805 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4806 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4807 if (Cst &&
4808 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4809 return true;
4810 }
4811 }
4812 }
4813
4814 // Check if we can do the following simplification.
4815 // ext(trunc(opnd)) --> ext(opnd)
4816 if (!isa<TruncInst>(Inst))
4817 return false;
4818
4819 Value *OpndVal = Inst->getOperand(0);
4820 // Check if we can use this operand in the extension.
4821 // If the type is larger than the result type of the extension, we cannot.
4822 if (!OpndVal->getType()->isIntegerTy() ||
4823 OpndVal->getType()->getIntegerBitWidth() >
4824 ConsideredExtType->getIntegerBitWidth())
4825 return false;
4826
4827 // If the operand of the truncate is not an instruction, we will not have
4828 // any information on the dropped bits.
4829 // (Actually we could for constant but it is not worth the extra logic).
4830 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4831 if (!Opnd)
4832 return false;
4833
4834 // Check if the source of the type is narrow enough.
4835 // I.e., check that trunc just drops extended bits of the same kind of
4836 // the extension.
4837 // #1 get the type of the operand and check the kind of the extended bits.
4838 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4839 if (OpndType)
4840 ;
4841 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4842 OpndType = Opnd->getOperand(0)->getType();
4843 else
4844 return false;
4845
4846 // #2 check that the truncate just drops extended bits.
4847 return Inst->getType()->getIntegerBitWidth() >=
4848 OpndType->getIntegerBitWidth();
4849}
4850
4851TypePromotionHelper::Action TypePromotionHelper::getAction(
4852 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4853 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4854 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4855 "Unexpected instruction type");
4856 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4857 Type *ExtTy = Ext->getType();
4858 bool IsSExt = isa<SExtInst>(Ext);
4859 // If the operand of the extension is not an instruction, we cannot
4860 // get through.
4861 // If it, check we can get through.
4862 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4863 return nullptr;
4864
4865 // Do not promote if the operand has been added by codegenprepare.
4866 // Otherwise, it means we are undoing an optimization that is likely to be
4867 // redone, thus causing potential infinite loop.
4868 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4869 return nullptr;
4870
4871 // SExt or Trunc instructions.
4872 // Return the related handler.
4873 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4874 isa<ZExtInst>(ExtOpnd))
4875 return promoteOperandForTruncAndAnyExt;
4876
4877 // Regular instruction.
4878 // Abort early if we will have to insert non-free instructions.
4879 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4880 return nullptr;
4881 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4882}
4883
4884Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4885 Instruction *SExt, TypePromotionTransaction &TPT,
4886 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4887 SmallVectorImpl<Instruction *> *Exts,
4888 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4889 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4890 // get through it and this method should not be called.
4891 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4892 Value *ExtVal = SExt;
4893 bool HasMergedNonFreeExt = false;
4894 if (isa<ZExtInst>(SExtOpnd)) {
4895 // Replace s|zext(zext(opnd))
4896 // => zext(opnd).
4897 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4898 Value *ZExt =
4899 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4900 TPT.replaceAllUsesWith(SExt, ZExt);
4901 TPT.eraseInstruction(SExt);
4902 ExtVal = ZExt;
4903 } else {
4904 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4905 // => z|sext(opnd).
4906 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4907 }
4908 CreatedInstsCost = 0;
4909
4910 // Remove dead code.
4911 if (SExtOpnd->use_empty())
4912 TPT.eraseInstruction(SExtOpnd);
4913
4914 // Check if the extension is still needed.
4915 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4916 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4917 if (ExtInst) {
4918 if (Exts)
4919 Exts->push_back(ExtInst);
4920 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4921 }
4922 return ExtVal;
4923 }
4924
4925 // At this point we have: ext ty opnd to ty.
4926 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4927 Value *NextVal = ExtInst->getOperand(0);
4928 TPT.eraseInstruction(ExtInst, NextVal);
4929 return NextVal;
4930}
4931
4932Value *TypePromotionHelper::promoteOperandForOther(
4933 Instruction *Ext, TypePromotionTransaction &TPT,
4934 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4935 SmallVectorImpl<Instruction *> *Exts,
4936 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
4937 bool IsSExt) {
4938 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4939 // get through it and this method should not be called.
4940 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4941 CreatedInstsCost = 0;
4942 if (!ExtOpnd->hasOneUse()) {
4943 // ExtOpnd will be promoted.
4944 // All its uses, but Ext, will need to use a truncated value of the
4945 // promoted version.
4946 // Create the truncate now.
4947 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4948 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4949 // Insert it just after the definition.
4950 ITrunc->moveAfter(ExtOpnd);
4951 if (Truncs)
4952 Truncs->push_back(ITrunc);
4953 }
4954
4955 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4956 // Restore the operand of Ext (which has been replaced by the previous call
4957 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4958 TPT.setOperand(Ext, 0, ExtOpnd);
4959 }
4960
4961 // Get through the Instruction:
4962 // 1. Update its type.
4963 // 2. Replace the uses of Ext by Inst.
4964 // 3. Extend each operand that needs to be extended.
4965
4966 // Remember the original type of the instruction before promotion.
4967 // This is useful to know that the high bits are sign extended bits.
4968 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4969 // Step #1.
4970 TPT.mutateType(ExtOpnd, Ext->getType());
4971 // Step #2.
4972 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4973 // Step #3.
4974 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
4975 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4976 ++OpIdx) {
4977 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4978 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4979 !shouldExtOperand(ExtOpnd, OpIdx)) {
4980 LLVM_DEBUG(dbgs() << "No need to propagate\n");
4981 continue;
4982 }
4983 // Check if we can statically extend the operand.
4984 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4985 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4986 LLVM_DEBUG(dbgs() << "Statically extend\n");
4987 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4988 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4989 : Cst->getValue().zext(BitWidth);
4990 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4991 continue;
4992 }
4993 // UndefValue are typed, so we have to statically sign extend them.
4994 if (isa<UndefValue>(Opnd)) {
4995 LLVM_DEBUG(dbgs() << "Statically extend\n");
4996 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4997 continue;
4998 }
4999
5000 // Otherwise we have to explicitly sign extend the operand.
5001 Value *ValForExtOpnd = IsSExt
5002 ? TPT.createSExt(ExtOpnd, Opnd, Ext->getType())
5003 : TPT.createZExt(ExtOpnd, Opnd, Ext->getType());
5004 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
5005 Instruction *InstForExtOpnd = dyn_cast<Instruction>(ValForExtOpnd);
5006 if (!InstForExtOpnd)
5007 continue;
5008
5009 if (Exts)
5010 Exts->push_back(InstForExtOpnd);
5011
5012 CreatedInstsCost += !TLI.isExtFree(InstForExtOpnd);
5013 }
5014 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
5015 TPT.eraseInstruction(Ext);
5016 return ExtOpnd;
5017}
5018
5019/// Check whether or not promoting an instruction to a wider type is profitable.
5020/// \p NewCost gives the cost of extension instructions created by the
5021/// promotion.
5022/// \p OldCost gives the cost of extension instructions before the promotion
5023/// plus the number of instructions that have been
5024/// matched in the addressing mode the promotion.
5025/// \p PromotedOperand is the value that has been promoted.
5026/// \return True if the promotion is profitable, false otherwise.
5027bool AddressingModeMatcher::isPromotionProfitable(
5028 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
5029 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
5030 << '\n');
5031 // The cost of the new extensions is greater than the cost of the
5032 // old extension plus what we folded.
5033 // This is not profitable.
5034 if (NewCost > OldCost)
5035 return false;
5036 if (NewCost < OldCost)
5037 return true;
5038 // The promotion is neutral but it may help folding the sign extension in
5039 // loads for instance.
5040 // Check that we did not create an illegal instruction.
5041 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
5042}
5043
5044/// Given an instruction or constant expr, see if we can fold the operation
5045/// into the addressing mode. If so, update the addressing mode and return
5046/// true, otherwise return false without modifying AddrMode.
5047/// If \p MovedAway is not NULL, it contains the information of whether or
5048/// not AddrInst has to be folded into the addressing mode on success.
5049/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
5050/// because it has been moved away.
5051/// Thus AddrInst must not be added in the matched instructions.
5052/// This state can happen when AddrInst is a sext, since it may be moved away.
5053/// Therefore, AddrInst may not be valid when MovedAway is true and it must
5054/// not be referenced anymore.
5055bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
5056 unsigned Depth,
5057 bool *MovedAway) {
5058 // Avoid exponential behavior on extremely deep expression trees.
5059 if (Depth >= 5)
5060 return false;
5061
5062 // By default, all matched instructions stay in place.
5063 if (MovedAway)
5064 *MovedAway = false;
5065
5066 switch (Opcode) {
5067 case Instruction::PtrToInt:
5068 // PtrToInt is always a noop, as we know that the int type is pointer sized.
5069 return matchAddr(AddrInst->getOperand(0), Depth);
5070 case Instruction::IntToPtr: {
5071 auto AS = AddrInst->getType()->getPointerAddressSpace();
5072 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
5073 // This inttoptr is a no-op if the integer type is pointer sized.
5074 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
5075 return matchAddr(AddrInst->getOperand(0), Depth);
5076 return false;
5077 }
5078 case Instruction::BitCast:
5079 // BitCast is always a noop, and we can handle it as long as it is
5080 // int->int or pointer->pointer (we don't want int<->fp or something).
5081 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
5082 // Don't touch identity bitcasts. These were probably put here by LSR,
5083 // and we don't want to mess around with them. Assume it knows what it
5084 // is doing.
5085 AddrInst->getOperand(0)->getType() != AddrInst->getType())
5086 return matchAddr(AddrInst->getOperand(0), Depth);
5087 return false;
5088 case Instruction::AddrSpaceCast: {
5089 unsigned SrcAS =
5090 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
5091 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
5092 if (TLI.getTargetMachine().isNoopAddrSpaceCast(DL, SrcAS, DestAS))
5093 return matchAddr(AddrInst->getOperand(0), Depth);
5094 return false;
5095 }
5096 case Instruction::Or:
5097 if (!cast<PossiblyDisjointInst>(AddrInst)->isDisjoint())
5098 return false;
5099 [[fallthrough]];
5100 case Instruction::Add: {
5101 // Check to see if we can merge in one operand, then the other. If so, we
5102 // win.
5103 ExtAddrMode BackupAddrMode = AddrMode;
5104 unsigned OldSize = AddrModeInsts.size();
5105 // Start a transaction at this point.
5106 // The LHS may match but not the RHS.
5107 // Therefore, we need a higher level restoration point to undo partially
5108 // matched operation.
5109 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5110 TPT.getRestorationPoint();
5111
5112 // Try to match an integer constant second to increase its chance of ending
5113 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
5114 int First = 0, Second = 1;
5115 if (isa<ConstantInt>(AddrInst->getOperand(First))
5116 && !isa<ConstantInt>(AddrInst->getOperand(Second)))
5117 std::swap(First, Second);
5118 AddrMode.InBounds = false;
5119 if (matchAddr(AddrInst->getOperand(First), Depth + 1) &&
5120 matchAddr(AddrInst->getOperand(Second), Depth + 1))
5121 return true;
5122
5123 // Restore the old addr mode info.
5124 AddrMode = BackupAddrMode;
5125 AddrModeInsts.resize(OldSize);
5126 TPT.rollback(LastKnownGood);
5127
5128 // Otherwise this was over-aggressive. Try merging operands in the opposite
5129 // order.
5130 if (matchAddr(AddrInst->getOperand(Second), Depth + 1) &&
5131 matchAddr(AddrInst->getOperand(First), Depth + 1))
5132 return true;
5133
5134 // Otherwise we definitely can't merge the ADD in.
5135 AddrMode = BackupAddrMode;
5136 AddrModeInsts.resize(OldSize);
5137 TPT.rollback(LastKnownGood);
5138 break;
5139 }
5140 case Instruction::Mul:
5141 case Instruction::Shl: {
5142 // Can only handle X*C and X << C.
5143 AddrMode.InBounds = false;
5144 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
5145 if (!RHS || RHS->getBitWidth() > 64)
5146 return false;
5147 int64_t Scale = Opcode == Instruction::Shl
5148 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
5149 : RHS->getSExtValue();
5150
5151 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
5152 }
5153 case Instruction::GetElementPtr: {
5154 // Scan the GEP. We check it if it contains constant offsets and at most
5155 // one variable offset.
5156 int VariableOperand = -1;
5157 unsigned VariableScale = 0;
5158
5159 int64_t ConstantOffset = 0;
5160 gep_type_iterator GTI = gep_type_begin(AddrInst);
5161 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
5162 if (StructType *STy = GTI.getStructTypeOrNull()) {
5163 const StructLayout *SL = DL.getStructLayout(STy);
5164 unsigned Idx =
5165 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
5166 ConstantOffset += SL->getElementOffset(Idx);
5167 } else {
5168 TypeSize TS = GTI.getSequentialElementStride(DL);
5169 if (TS.isNonZero()) {
5170 // The optimisations below currently only work for fixed offsets.
5171 if (TS.isScalable())
5172 return false;
5173 int64_t TypeSize = TS.getFixedValue();
5174 if (ConstantInt *CI =
5175 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
5176 const APInt &CVal = CI->getValue();
5177 if (CVal.getSignificantBits() <= 64) {
5178 ConstantOffset += CVal.getSExtValue() * TypeSize;
5179 continue;
5180 }
5181 }
5182 // We only allow one variable index at the moment.
5183 if (VariableOperand != -1)
5184 return false;
5185
5186 // Remember the variable index.
5187 VariableOperand = i;
5188 VariableScale = TypeSize;
5189 }
5190 }
5191 }
5192
5193 // A common case is for the GEP to only do a constant offset. In this case,
5194 // just add it to the disp field and check validity.
5195 if (VariableOperand == -1) {
5196 AddrMode.BaseOffs += ConstantOffset;
5197 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5198 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5199 AddrMode.InBounds = false;
5200 return true;
5201 }
5202 AddrMode.BaseOffs -= ConstantOffset;
5203
5204 if (Opts.cgp_split_large_offset_gep && isa<GetElementPtrInst>(AddrInst) &&
5205 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
5206 ConstantOffset != 0) {
5207 // Record GEPs with non-zero offsets as candidates for splitting in
5208 // the event that the offset cannot fit into the r+i addressing mode.
5209 // Simple and common case that only one GEP is used in calculating the
5210 // address for the memory access.
5211 Value *Base = AddrInst->getOperand(0);
5212 auto *BaseI = dyn_cast<Instruction>(Base);
5213 auto *GEP = cast<GetElementPtrInst>(AddrInst);
5215 (BaseI && !isa<CastInst>(BaseI) &&
5216 !isa<GetElementPtrInst>(BaseI))) {
5217 // Make sure the parent block allows inserting non-PHI instructions
5218 // before the terminator.
5219 BasicBlock *Parent =
5220 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
5221 if (!Parent->getTerminator()->isEHPad())
5222 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
5223 }
5224 }
5225
5226 return false;
5227 }
5228
5229 // Save the valid addressing mode in case we can't match.
5230 ExtAddrMode BackupAddrMode = AddrMode;
5231 unsigned OldSize = AddrModeInsts.size();
5232
5233 // See if the scale and offset amount is valid for this target.
5234 AddrMode.BaseOffs += ConstantOffset;
5235 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5236 AddrMode.InBounds = false;
5237
5238 // Match the base operand of the GEP.
5239 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5240 // If it couldn't be matched, just stuff the value in a register.
5241 if (AddrMode.HasBaseReg) {
5242 AddrMode = BackupAddrMode;
5243 AddrModeInsts.resize(OldSize);
5244 return false;
5245 }
5246 AddrMode.HasBaseReg = true;
5247 AddrMode.BaseReg = AddrInst->getOperand(0);
5248 }
5249
5250 // Match the remaining variable portion of the GEP.
5251 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
5252 Depth)) {
5253 // If it couldn't be matched, try stuffing the base into a register
5254 // instead of matching it, and retrying the match of the scale.
5255 AddrMode = BackupAddrMode;
5256 AddrModeInsts.resize(OldSize);
5257 if (AddrMode.HasBaseReg)
5258 return false;
5259 AddrMode.HasBaseReg = true;
5260 AddrMode.BaseReg = AddrInst->getOperand(0);
5261 AddrMode.BaseOffs += ConstantOffset;
5262 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
5263 VariableScale, Depth)) {
5264 // If even that didn't work, bail.
5265 AddrMode = BackupAddrMode;
5266 AddrModeInsts.resize(OldSize);
5267 return false;
5268 }
5269 }
5270
5271 return true;
5272 }
5273 case Instruction::SExt:
5274 case Instruction::ZExt: {
5275 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
5276 if (!Ext)
5277 return false;
5278
5279 // Try to move this ext out of the way of the addressing mode.
5280 // Ask for a method for doing so.
5281 TypePromotionHelper::Action TPH =
5282 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
5283 if (!TPH)
5284 return false;
5285
5286 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5287 TPT.getRestorationPoint();
5288 unsigned CreatedInstsCost = 0;
5289 unsigned ExtCost = !TLI.isExtFree(Ext);
5290 Value *PromotedOperand =
5291 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
5292 // SExt has been moved away.
5293 // Thus either it will be rematched later in the recursive calls or it is
5294 // gone. Anyway, we must not fold it into the addressing mode at this point.
5295 // E.g.,
5296 // op = add opnd, 1
5297 // idx = ext op
5298 // addr = gep base, idx
5299 // is now:
5300 // promotedOpnd = ext opnd <- no match here
5301 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
5302 // addr = gep base, op <- match
5303 if (MovedAway)
5304 *MovedAway = true;
5305
5306 assert(PromotedOperand &&
5307 "TypePromotionHelper should have filtered out those cases");
5308
5309 ExtAddrMode BackupAddrMode = AddrMode;
5310 unsigned OldSize = AddrModeInsts.size();
5311
5312 if (!matchAddr(PromotedOperand, Depth) ||
5313 // The total of the new cost is equal to the cost of the created
5314 // instructions.
5315 // The total of the old cost is equal to the cost of the extension plus
5316 // what we have saved in the addressing mode.
5317 !isPromotionProfitable(CreatedInstsCost,
5318 ExtCost + (AddrModeInsts.size() - OldSize),
5319 PromotedOperand)) {
5320 AddrMode = BackupAddrMode;
5321 AddrModeInsts.resize(OldSize);
5322 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
5323 TPT.rollback(LastKnownGood);
5324 return false;
5325 }
5326
5327 // SExt has been deleted. Make sure it is not referenced by the AddrMode.
5328 AddrMode.replaceWith(Ext, PromotedOperand);
5329 return true;
5330 }
5331 case Instruction::Call:
5332 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(AddrInst)) {
5333 if (II->getIntrinsicID() == Intrinsic::threadlocal_address) {
5334 GlobalValue &GV = cast<GlobalValue>(*II->getArgOperand(0));
5335 if (TLI.addressingModeSupportsTLS(GV))
5336 return matchAddr(AddrInst->getOperand(0), Depth);
5337 }
5338 }
5339 break;
5340 }
5341 return false;
5342}
5343
5344/// If we can, try to add the value of 'Addr' into the current addressing mode.
5345/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
5346/// unmodified. This assumes that Addr is either a pointer type or intptr_t
5347/// for the target.
5348///
5349bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
5350 // Start a transaction at this point that we will rollback if the matching
5351 // fails.
5352 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5353 TPT.getRestorationPoint();
5354 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
5355 if (CI->getValue().isSignedIntN(64)) {
5356 // Check if the addition would result in a signed overflow.
5357 int64_t Result;
5358 bool Overflow =
5359 AddOverflow(AddrMode.BaseOffs, CI->getSExtValue(), Result);
5360 if (!Overflow) {
5361 // Fold in immediates if legal for the target.
5362 AddrMode.BaseOffs = Result;
5363 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5364 return true;
5365 AddrMode.BaseOffs -= CI->getSExtValue();
5366 }
5367 }
5368 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
5369 // If this is a global variable, try to fold it into the addressing mode.
5370 if (!AddrMode.BaseGV) {
5371 AddrMode.BaseGV = GV;
5372 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5373 return true;
5374 AddrMode.BaseGV = nullptr;
5375 }
5376 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
5377 ExtAddrMode BackupAddrMode = AddrMode;
5378 unsigned OldSize = AddrModeInsts.size();
5379
5380 // Check to see if it is possible to fold this operation.
5381 bool MovedAway = false;
5382 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
5383 // This instruction may have been moved away. If so, there is nothing
5384 // to check here.
5385 if (MovedAway)
5386 return true;
5387 // Okay, it's possible to fold this. Check to see if it is actually
5388 // *profitable* to do so. We use a simple cost model to avoid increasing
5389 // register pressure too much.
5390 if (I->hasOneUse() ||
5391 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
5392 AddrModeInsts.push_back(I);
5393 return true;
5394 }
5395
5396 // It isn't profitable to do this, roll back.
5397 AddrMode = BackupAddrMode;
5398 AddrModeInsts.resize(OldSize);
5399 TPT.rollback(LastKnownGood);
5400 }
5401 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
5402 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
5403 return true;
5404 TPT.rollback(LastKnownGood);
5405 } else if (isa<ConstantPointerNull>(Addr)) {
5406 // Null pointer gets folded without affecting the addressing mode.
5407 return true;
5408 }
5409
5410 // Worse case, the target should support [reg] addressing modes. :)
5411 if (!AddrMode.HasBaseReg) {
5412 AddrMode.HasBaseReg = true;
5413 AddrMode.BaseReg = Addr;
5414 // Still check for legality in case the target supports [imm] but not [i+r].
5415 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5416 return true;
5417 AddrMode.HasBaseReg = false;
5418 AddrMode.BaseReg = nullptr;
5419 }
5420
5421 // If the base register is already taken, see if we can do [r+r].
5422 if (AddrMode.Scale == 0) {
5423 AddrMode.Scale = 1;
5424 AddrMode.ScaledReg = Addr;
5425 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5426 return true;
5427 AddrMode.Scale = 0;
5428 AddrMode.ScaledReg = nullptr;
5429 }
5430 // Couldn't match.
5431 TPT.rollback(LastKnownGood);
5432 return false;
5433}
5434
5435/// Check to see if all uses of OpVal by the specified inline asm call are due
5436/// to memory operands. If so, return true, otherwise return false.
5438 const TargetLowering &TLI,
5439 const TargetRegisterInfo &TRI) {
5440 const Function *F = CI->getFunction();
5441 TargetLowering::AsmOperandInfoVector TargetConstraints =
5442 TLI.ParseConstraints(F->getDataLayout(), &TRI, *CI);
5443
5444 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5445 // Compute the constraint code and ConstraintType to use.
5446 TLI.ComputeConstraintToUse(OpInfo, SDValue());
5447
5448 // If this asm operand is our Value*, and if it isn't an indirect memory
5449 // operand, we can't fold it! TODO: Also handle C_Address?
5450 if (OpInfo.CallOperandVal == OpVal &&
5451 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
5452 !OpInfo.isIndirect))
5453 return false;
5454 }
5455
5456 return true;
5457}
5458
5459/// Recursively walk all the uses of I until we find a memory use.
5460/// If we find an obviously non-foldable instruction, return true.
5461/// Add accessed addresses and types to MemoryUses.
5463 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5464 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
5465 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
5466 BlockFrequencyInfo *BFI, unsigned &SeenInsts, unsigned MaxUsersToScan) {
5467 // If we already considered this instruction, we're done.
5468 if (!ConsideredInsts.insert(I).second)
5469 return false;
5470
5471 // If this is an obviously unfoldable instruction, bail out.
5472 if (!MightBeFoldableInst(I))
5473 return true;
5474
5475 // Loop over all the uses, recursively processing them.
5476 for (Use &U : I->uses()) {
5477 // Conservatively return true if we're seeing a large number or a deep chain
5478 // of users. This avoids excessive compilation times in pathological cases.
5479 if (SeenInsts++ >= MaxUsersToScan)
5480 return true;
5481
5482 Instruction *UserI = cast<Instruction>(U.getUser());
5483 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
5484 MemoryUses.push_back({&U, LI->getType()});
5485 continue;
5486 }
5487
5488 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
5489 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
5490 return true; // Storing addr, not into addr.
5491 MemoryUses.push_back({&U, SI->getValueOperand()->getType()});
5492 continue;
5493 }
5494
5495 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
5496 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5497 return true; // Storing addr, not into addr.
5498 MemoryUses.push_back({&U, RMW->getValOperand()->getType()});
5499 continue;
5500 }
5501
5503 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5504 return true; // Storing addr, not into addr.
5505 MemoryUses.push_back({&U, CmpX->getCompareOperand()->getType()});
5506 continue;
5507 }
5508
5511 Type *AccessTy;
5512 if (!TLI.getAddrModeArguments(II, PtrOps, AccessTy))
5513 return true;
5514
5515 if (!find(PtrOps, U.get()))
5516 return true;
5517
5518 MemoryUses.push_back({&U, AccessTy});
5519 continue;
5520 }
5521
5522 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
5523 if (CI->hasFnAttr(Attribute::Cold)) {
5524 // If this is a cold call, we can sink the addressing calculation into
5525 // the cold path. See optimizeCallInst
5526 if (!llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI))
5527 continue;
5528 }
5529
5530 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
5531 if (!IA)
5532 return true;
5533
5534 // If this is a memory operand, we're cool, otherwise bail out.
5535 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
5536 return true;
5537 continue;
5538 }
5539
5540 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5541 PSI, BFI, SeenInsts, MaxUsersToScan))
5542 return true;
5543 }
5544
5545 return false;
5546}
5547
5549 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5550 const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize,
5551 ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, unsigned MaxUsersToScan) {
5552 unsigned SeenInsts = 0;
5553 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5554 return FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5555 PSI, BFI, SeenInsts, MaxUsersToScan);
5556}
5557
5558/// Return true if Val is already known to be live at the use site that we're
5559/// folding it into. If so, there is no cost to include it in the addressing
5560/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5561/// instruction already.
5562bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5563 Value *KnownLive1,
5564 Value *KnownLive2) {
5565 // If Val is either of the known-live values, we know it is live!
5566 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5567 return true;
5568
5569 // All values other than instructions and arguments (e.g. constants) are live.
5570 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5571 return true;
5572
5573 // If Val is a constant sized alloca in the entry block, it is live, this is
5574 // true because it is just a reference to the stack/frame pointer, which is
5575 // live for the whole function.
5576 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5577 if (AI->isStaticAlloca())
5578 return true;
5579
5580 // Check to see if this value is already used in the memory instruction's
5581 // block. If so, it's already live into the block at the very least, so we
5582 // can reasonably fold it.
5583 return Val->isUsedInBasicBlock(MemoryInst->getParent());
5584}
5585
5586/// It is possible for the addressing mode of the machine to fold the specified
5587/// instruction into a load or store that ultimately uses it.
5588/// However, the specified instruction has multiple uses.
5589/// Given this, it may actually increase register pressure to fold it
5590/// into the load. For example, consider this code:
5591///
5592/// X = ...
5593/// Y = X+1
5594/// use(Y) -> nonload/store
5595/// Z = Y+1
5596/// load Z
5597///
5598/// In this case, Y has multiple uses, and can be folded into the load of Z
5599/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5600/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5601/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5602/// number of computations either.
5603///
5604/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5605/// X was live across 'load Z' for other reasons, we actually *would* want to
5606/// fold the addressing mode in the Z case. This would make Y die earlier.
5607bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5608 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5609 if (IgnoreProfitability)
5610 return true;
5611
5612 // AMBefore is the addressing mode before this instruction was folded into it,
5613 // and AMAfter is the addressing mode after the instruction was folded. Get
5614 // the set of registers referenced by AMAfter and subtract out those
5615 // referenced by AMBefore: this is the set of values which folding in this
5616 // address extends the lifetime of.
5617 //
5618 // Note that there are only two potential values being referenced here,
5619 // BaseReg and ScaleReg (global addresses are always available, as are any
5620 // folded immediates).
5621 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5622
5623 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5624 // lifetime wasn't extended by adding this instruction.
5625 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5626 BaseReg = nullptr;
5627 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5628 ScaledReg = nullptr;
5629
5630 // If folding this instruction (and it's subexprs) didn't extend any live
5631 // ranges, we're ok with it.
5632 if (!BaseReg && !ScaledReg)
5633 return true;
5634
5635 // If all uses of this instruction can have the address mode sunk into them,
5636 // we can remove the addressing mode and effectively trade one live register
5637 // for another (at worst.) In this context, folding an addressing mode into
5638 // the use is just a particularly nice way of sinking it.
5640 if (FindAllMemoryUses(I, MemoryUses, TLI, TRI, OptSize, PSI, BFI,
5641 Opts.cgp_max_address_users_to_scan))
5642 return false; // Has a non-memory, non-foldable use!
5643
5644 // Now that we know that all uses of this instruction are part of a chain of
5645 // computation involving only operations that could theoretically be folded
5646 // into a memory use, loop over each of these memory operation uses and see
5647 // if they could *actually* fold the instruction. The assumption is that
5648 // addressing modes are cheap and that duplicating the computation involved
5649 // many times is worthwhile, even on a fastpath. For sinking candidates
5650 // (i.e. cold call sites), this serves as a way to prevent excessive code
5651 // growth since most architectures have some reasonable small and fast way to
5652 // compute an effective address. (i.e LEA on x86)
5653 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5654 for (const std::pair<Use *, Type *> &Pair : MemoryUses) {
5655 Value *Address = Pair.first->get();
5656 Instruction *UserI = cast<Instruction>(Pair.first->getUser());
5657 Type *AddressAccessTy = Pair.second;
5658 unsigned AS = Address->getType()->getPointerAddressSpace();
5659
5660 // Do a match against the root of this address, ignoring profitability. This
5661 // will tell us if the addressing mode for the memory operation will
5662 // *actually* cover the shared instruction.
5663 ExtAddrMode Result;
5664 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5665 0);
5666 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5667 TPT.getRestorationPoint();
5668 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5669 AddressAccessTy, AS, UserI, Result,
5670 InsertedInsts, PromotedInsts, TPT,
5671 LargeOffsetGEP, OptSize, PSI, BFI, Opts);
5672 Matcher.IgnoreProfitability = true;
5673 bool Success = Matcher.matchAddr(Address, 0);
5674 (void)Success;
5675 assert(Success && "Couldn't select *anything*?");
5676
5677 // The match was to check the profitability, the changes made are not
5678 // part of the original matcher. Therefore, they should be dropped
5679 // otherwise the original matcher will not present the right state.
5680 TPT.rollback(LastKnownGood);
5681
5682 // If the match didn't cover I, then it won't be shared by it.
5683 if (!is_contained(MatchedAddrModeInsts, I))
5684 return false;
5685
5686 MatchedAddrModeInsts.clear();
5687 }
5688
5689 return true;
5690}
5691
5692/// Return true if the specified values are defined in a
5693/// different basic block than BB.
5694static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5696 return I->getParent() != BB;
5697 return false;
5698}
5699
5700// Find an insert position of Addr for MemoryInst. We can't guarantee MemoryInst
5701// is the first instruction that will use Addr. So we need to find the first
5702// user of Addr in current BB.
5704 Value *SunkAddr) {
5705 if (Addr->hasOneUse())
5706 return MemoryInst->getIterator();
5707
5708 // We already have a SunkAddr in current BB, but we may need to insert cast
5709 // instruction after it.
5710 if (SunkAddr) {
5711 if (Instruction *AddrInst = dyn_cast<Instruction>(SunkAddr))
5712 return std::next(AddrInst->getIterator());
5713 }
5714
5715 // Find the first user of Addr in current BB.
5716 Instruction *Earliest = MemoryInst;
5717 for (User *U : Addr->users()) {
5718 Instruction *UserInst = dyn_cast<Instruction>(U);
5719 if (UserInst && UserInst->getParent() == MemoryInst->getParent()) {
5720 if (isa<PHINode>(UserInst))
5721 continue;
5722 if (UserInst->comesBefore(Earliest))
5723 Earliest = UserInst;
5724 }
5725 }
5726 return Earliest->getIterator();
5727}
5728
5729/// Sink addressing mode computation immediate before MemoryInst if doing so
5730/// can be done without increasing register pressure. The need for the
5731/// register pressure constraint means this can end up being an all or nothing
5732/// decision for all uses of the same addressing computation.
5733///
5734/// Load and Store Instructions often have addressing modes that can do
5735/// significant amounts of computation. As such, instruction selection will try
5736/// to get the load or store to do as much computation as possible for the
5737/// program. The problem is that isel can only see within a single block. As
5738/// such, we sink as much legal addressing mode work into the block as possible.
5739///
5740/// This method is used to optimize both load/store and inline asms with memory
5741/// operands. It's also used to sink addressing computations feeding into cold
5742/// call sites into their (cold) basic block.
5743///
5744/// The motivation for handling sinking into cold blocks is that doing so can
5745/// both enable other address mode sinking (by satisfying the register pressure
5746/// constraint above), and reduce register pressure globally (by removing the
5747/// addressing mode computation from the fast path entirely.).
5748bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5749 Type *AccessTy, unsigned AddrSpace) {
5750 Value *Repl = Addr;
5751
5752 // Try to collapse single-value PHI nodes. This is necessary to undo
5753 // unprofitable PRE transformations.
5754 SmallVector<Value *, 8> worklist;
5755 SmallPtrSet<Value *, 16> Visited;
5756 worklist.push_back(Addr);
5757
5758 // Use a worklist to iteratively look through PHI and select nodes, and
5759 // ensure that the addressing mode obtained from the non-PHI/select roots of
5760 // the graph are compatible.
5761 bool PhiOrSelectSeen = false;
5762 SmallVector<Instruction *, 16> AddrModeInsts;
5763 AddressingModeCombiner AddrModes(*DL, Opts, Addr);
5764 TypePromotionTransaction TPT(RemovedInsts);
5765 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5766 TPT.getRestorationPoint();
5767 while (!worklist.empty()) {
5768 Value *V = worklist.pop_back_val();
5769
5770 // We allow traversing cyclic Phi nodes.
5771 // In case of success after this loop we ensure that traversing through
5772 // Phi nodes ends up with all cases to compute address of the form
5773 // BaseGV + Base + Scale * Index + Offset
5774 // where Scale and Offset are constans and BaseGV, Base and Index
5775 // are exactly the same Values in all cases.
5776 // It means that BaseGV, Scale and Offset dominate our memory instruction
5777 // and have the same value as they had in address computation represented
5778 // as Phi. So we can safely sink address computation to memory instruction.
5779 if (!Visited.insert(V).second)
5780 continue;
5781
5782 // For a PHI node, push all of its incoming values.
5783 if (PHINode *P = dyn_cast<PHINode>(V)) {
5784 append_range(worklist, P->incoming_values());
5785 PhiOrSelectSeen = true;
5786 continue;
5787 }
5788 // Similar for select.
5789 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
5790 worklist.push_back(SI->getFalseValue());
5791 worklist.push_back(SI->getTrueValue());
5792 PhiOrSelectSeen = true;
5793 continue;
5794 }
5795
5796 // For non-PHIs, determine the addressing mode being computed. Note that
5797 // the result may differ depending on what other uses our candidate
5798 // addressing instructions might have.
5799 AddrModeInsts.clear();
5800 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5801 0);
5802 // Defer the query (and possible computation of) the dom tree to point of
5803 // actual use. It's expected that most address matches don't actually need
5804 // the domtree.
5805 auto getDTFn = [this]() -> const DominatorTree & { return getDT(); };
5806 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5807 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
5808 *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5809 BFI, Opts);
5810
5811 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5812 if (GEP && !NewGEPBases.count(GEP)) {
5813 // If splitting the underlying data structure can reduce the offset of a
5814 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5815 // previously split data structures.
5816 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5817 LargeOffsetGEPID.insert(std::make_pair(GEP, LargeOffsetGEPID.size()));
5818 }
5819
5820 NewAddrMode.OriginalValue = V;
5821 if (!AddrModes.addNewAddrMode(NewAddrMode))
5822 break;
5823 }
5824
5825 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5826 // or we have multiple but either couldn't combine them or combining them
5827 // wouldn't do anything useful, bail out now.
5828 if (!AddrModes.combineAddrModes()) {
5829 TPT.rollback(LastKnownGood);
5830 return false;
5831 }
5832 bool Modified = TPT.commit();
5833
5834 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5835 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5836
5837 // If all the instructions matched are already in this BB, don't do anything.
5838 // If we saw a Phi node then it is not local definitely, and if we saw a
5839 // select then we want to push the address calculation past it even if it's
5840 // already in this BB.
5841 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
5842 return IsNonLocalValue(V, MemoryInst->getParent());
5843 })) {
5844 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
5845 << "\n");
5846 return Modified;
5847 }
5848
5849 // Now that we determined the addressing expression we want to use and know
5850 // that we have to sink it into this block. Check to see if we have already
5851 // done this for some other load/store instr in this block. If so, reuse
5852 // the computation. Before attempting reuse, check if the address is valid
5853 // as it may have been erased.
5854
5855 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5856
5857 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5858 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5859
5860 // The current BB may be optimized multiple times, we can't guarantee the
5861 // reuse of Addr happens later, call findInsertPos to find an appropriate
5862 // insert position.
5863 auto InsertPos = findInsertPos(Addr, MemoryInst, SunkAddr);
5864
5865 // TODO: Adjust insert point considering (Base|Scaled)Reg if possible.
5866 if (!SunkAddr) {
5867 auto &DT = getDT();
5868 if ((AddrMode.BaseReg && !DT.dominates(AddrMode.BaseReg, &*InsertPos)) ||
5869 (AddrMode.ScaledReg && !DT.dominates(AddrMode.ScaledReg, &*InsertPos)))
5870 return Modified;
5871 }
5872
5873 IRBuilder<> Builder(InsertPos);
5874
5875 if (SunkAddr) {
5876 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
5877 << " for " << *MemoryInst << "\n");
5878 if (SunkAddr->getType() != Addr->getType()) {
5879 if (SunkAddr->getType()->getPointerAddressSpace() !=
5880 Addr->getType()->getPointerAddressSpace() &&
5881 !DL->isNonIntegralPointerType(Addr->getType())) {
5882 // There are two reasons the address spaces might not match: a no-op
5883 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5884 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5885 // TODO: allow bitcast between different address space pointers with the
5886 // same size.
5887 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
5888 SunkAddr =
5889 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
5890 } else
5891 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5892 }
5893 } else if (valueOr(Opts.cgp_addr_sink_using_gep, true) ||
5894 (Opts.cgp_addr_sink_using_gep == BoolOrDefault::Default &&
5895 SubtargetInfo->addrSinkUsingGEPs())) {
5896 // By default, we use the GEP-based method when AA is used later. This
5897 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
5898 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
5899 << " for " << *MemoryInst << "\n");
5900 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
5901
5902 // First, find the pointer.
5903 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
5904 ResultPtr = AddrMode.BaseReg;
5905 AddrMode.BaseReg = nullptr;
5906 }
5907
5908 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
5909 // We can't add more than one pointer together, nor can we scale a
5910 // pointer (both of which seem meaningless).
5911 if (ResultPtr || AddrMode.Scale != 1)
5912 return Modified;
5913
5914 ResultPtr = AddrMode.ScaledReg;
5915 AddrMode.Scale = 0;
5916 }
5917
5918 // It is only safe to sign extend the BaseReg if we know that the math
5919 // required to create it did not overflow before we extend it. Since
5920 // the original IR value was tossed in favor of a constant back when
5921 // the AddrMode was created we need to bail out gracefully if widths
5922 // do not match instead of extending it.
5923 //
5924 // (See below for code to add the scale.)
5925 if (AddrMode.Scale) {
5926 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
5928 cast<IntegerType>(ScaledRegTy)->getBitWidth())
5929 return Modified;
5930 }
5931
5932 GlobalValue *BaseGV = AddrMode.BaseGV;
5933 if (BaseGV != nullptr) {
5934 if (ResultPtr)
5935 return Modified;
5936
5937 if (BaseGV->isThreadLocal()) {
5938 ResultPtr = Builder.CreateThreadLocalAddress(BaseGV);
5939 } else {
5940 ResultPtr = BaseGV;
5941 }
5942 }
5943
5944 // If the real base value actually came from an inttoptr, then the matcher
5945 // will look through it and provide only the integer value. In that case,
5946 // use it here.
5947 if (!DL->isNonIntegralPointerType(Addr->getType())) {
5948 if (!ResultPtr && AddrMode.BaseReg) {
5949 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
5950 "sunkaddr");
5951 AddrMode.BaseReg = nullptr;
5952 } else if (!ResultPtr && AddrMode.Scale == 1) {
5953 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
5954 "sunkaddr");
5955 AddrMode.Scale = 0;
5956 }
5957 }
5958
5959 if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
5960 !AddrMode.BaseOffs) {
5961 SunkAddr = Constant::getNullValue(Addr->getType());
5962 } else if (!ResultPtr) {
5963 return Modified;
5964 } else {
5965 Type *I8PtrTy =
5966 Builder.getPtrTy(Addr->getType()->getPointerAddressSpace());
5967
5968 // Start with the base register. Do this first so that subsequent address
5969 // matching finds it last, which will prevent it from trying to match it
5970 // as the scaled value in case it happens to be a mul. That would be
5971 // problematic if we've sunk a different mul for the scale, because then
5972 // we'd end up sinking both muls.
5973 if (AddrMode.BaseReg) {
5974 Value *V = AddrMode.BaseReg;
5975 if (V->getType() != IntPtrTy)
5976 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
5977
5978 ResultIndex = V;
5979 }
5980
5981 // Add the scale value.
5982 if (AddrMode.Scale) {
5983 Value *V = AddrMode.ScaledReg;
5984 if (V->getType() == IntPtrTy) {
5985 // done.
5986 } else {
5988 cast<IntegerType>(V->getType())->getBitWidth() &&
5989 "We can't transform if ScaledReg is too narrow");
5990 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
5991 }
5992
5993 if (AddrMode.Scale != 1)
5994 V = Builder.CreateMul(
5995 V, ConstantInt::getSigned(IntPtrTy, AddrMode.Scale), "sunkaddr");
5996 if (ResultIndex)
5997 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
5998 else
5999 ResultIndex = V;
6000 }
6001
6002 // Add in the Base Offset if present.
6003 if (AddrMode.BaseOffs) {
6005 if (ResultIndex) {
6006 // We need to add this separately from the scale above to help with
6007 // SDAG consecutive load/store merging.
6008 if (ResultPtr->getType() != I8PtrTy)
6009 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6010 ResultPtr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
6011 AddrMode.InBounds);
6012 }
6013
6014 ResultIndex = V;
6015 }
6016
6017 if (!ResultIndex) {
6018 auto PtrInst = dyn_cast<Instruction>(ResultPtr);
6019 // We know that we have a pointer without any offsets. If this pointer
6020 // originates from a different basic block than the current one, we
6021 // must be able to recreate it in the current basic block.
6022 // We do not support the recreation of any instructions yet.
6023 if (PtrInst && PtrInst->getParent() != MemoryInst->getParent())
6024 return Modified;
6025 SunkAddr = ResultPtr;
6026 } else {
6027 if (ResultPtr->getType() != I8PtrTy)
6028 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6029 SunkAddr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
6030 AddrMode.InBounds);
6031 }
6032
6033 if (SunkAddr->getType() != Addr->getType()) {
6034 if (SunkAddr->getType()->getPointerAddressSpace() !=
6035 Addr->getType()->getPointerAddressSpace() &&
6036 !DL->isNonIntegralPointerType(Addr->getType())) {
6037 // There are two reasons the address spaces might not match: a no-op
6038 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
6039 // ptrtoint/inttoptr pair to ensure we match the original semantics.
6040 // TODO: allow bitcast between different address space pointers with
6041 // the same size.
6042 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
6043 SunkAddr =
6044 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
6045 } else
6046 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
6047 }
6048 }
6049 } else {
6050 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
6051 // non-integral pointers, so in that case bail out now.
6052 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
6053 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
6054 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
6055 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
6056 if (DL->isNonIntegralPointerType(Addr->getType()) ||
6057 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
6058 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
6059 (AddrMode.BaseGV &&
6060 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
6061 return Modified;
6062
6063 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6064 << " for " << *MemoryInst << "\n");
6065 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
6066 Value *Result = nullptr;
6067
6068 // Start with the base register. Do this first so that subsequent address
6069 // matching finds it last, which will prevent it from trying to match it
6070 // as the scaled value in case it happens to be a mul. That would be
6071 // problematic if we've sunk a different mul for the scale, because then
6072 // we'd end up sinking both muls.
6073 if (AddrMode.BaseReg) {
6074 Value *V = AddrMode.BaseReg;
6075 if (V->getType()->isPointerTy())
6076 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6077 if (V->getType() != IntPtrTy)
6078 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
6079 Result = V;
6080 }
6081
6082 // Add the scale value.
6083 if (AddrMode.Scale) {
6084 Value *V = AddrMode.ScaledReg;
6085 if (V->getType() == IntPtrTy) {
6086 // done.
6087 } else if (V->getType()->isPointerTy()) {
6088 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6089 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
6090 cast<IntegerType>(V->getType())->getBitWidth()) {
6091 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
6092 } else {
6093 // It is only safe to sign extend the BaseReg if we know that the math
6094 // required to create it did not overflow before we extend it. Since
6095 // the original IR value was tossed in favor of a constant back when
6096 // the AddrMode was created we need to bail out gracefully if widths
6097 // do not match instead of extending it.
6099 if (I && (Result != AddrMode.BaseReg))
6100 I->eraseFromParent();
6101 return Modified;
6102 }
6103 if (AddrMode.Scale != 1)
6104 V = Builder.CreateMul(
6105 V, ConstantInt::getSigned(IntPtrTy, AddrMode.Scale), "sunkaddr");
6106 if (Result)
6107 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6108 else
6109 Result = V;
6110 }
6111
6112 // Add in the BaseGV if present.
6113 GlobalValue *BaseGV = AddrMode.BaseGV;
6114 if (BaseGV != nullptr) {
6115 Value *BaseGVPtr;
6116 if (BaseGV->isThreadLocal()) {
6117 BaseGVPtr = Builder.CreateThreadLocalAddress(BaseGV);
6118 } else {
6119 BaseGVPtr = BaseGV;
6120 }
6121 Value *V = Builder.CreatePtrToInt(BaseGVPtr, IntPtrTy, "sunkaddr");
6122 if (Result)
6123 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6124 else
6125 Result = V;
6126 }
6127
6128 // Add in the Base Offset if present.
6129 if (AddrMode.BaseOffs) {
6131 if (Result)
6132 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6133 else
6134 Result = V;
6135 }
6136
6137 if (!Result)
6138 SunkAddr = Constant::getNullValue(Addr->getType());
6139 else
6140 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
6141 }
6142
6143 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
6144 // Store the newly computed address into the cache. In the case we reused a
6145 // value, this should be idempotent.
6146 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
6147
6148 // If we have no uses, recursively delete the value and all dead instructions
6149 // using it.
6150 if (Repl->use_empty()) {
6151 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
6152 RecursivelyDeleteTriviallyDeadInstructions(
6153 Repl, TLInfo, nullptr,
6154 [&](Value *V) { removeAllAssertingVHReferences(V); });
6155 });
6156 }
6157 ++NumMemoryInsts;
6158 return true;
6159}
6160
6161/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
6162/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
6163/// only handle a 2 operand GEP in the same basic block or a splat constant
6164/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
6165/// index.
6166///
6167/// If the existing GEP has a vector base pointer that is splat, we can look
6168/// through the splat to find the scalar pointer. If we can't find a scalar
6169/// pointer there's nothing we can do.
6170///
6171/// If we have a GEP with more than 2 indices where the middle indices are all
6172/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
6173///
6174/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
6175/// followed by a GEP with an all zeroes vector index. This will enable
6176/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
6177/// zero index.
6178bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
6179 Value *Ptr) {
6180 Value *NewAddr;
6181
6182 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
6183 // Don't optimize GEPs that don't have indices.
6184 if (!GEP->hasIndices())
6185 return false;
6186
6187 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
6188 // FIXME: We should support this by sinking the GEP.
6189 if (MemoryInst->getParent() != GEP->getParent())
6190 return false;
6191
6192 SmallVector<Value *, 2> Ops(GEP->operands());
6193
6194 bool RewriteGEP = false;
6195
6196 if (Ops[0]->getType()->isVectorTy()) {
6197 Ops[0] = getSplatValue(Ops[0]);
6198 if (!Ops[0])
6199 return false;
6200 RewriteGEP = true;
6201 }
6202
6203 unsigned FinalIndex = Ops.size() - 1;
6204
6205 // Ensure all but the last index is 0.
6206 // FIXME: This isn't strictly required. All that's required is that they are
6207 // all scalars or splats.
6208 for (unsigned i = 1; i < FinalIndex; ++i) {
6209 auto *C = dyn_cast<Constant>(Ops[i]);
6210 if (!C)
6211 return false;
6212 if (isa<VectorType>(C->getType()))
6213 C = C->getSplatValue();
6214 auto *CI = dyn_cast_or_null<ConstantInt>(C);
6215 if (!CI || !CI->isZero())
6216 return false;
6217 // Scalarize the index if needed.
6218 Ops[i] = CI;
6219 }
6220
6221 // Try to scalarize the final index.
6222 if (Ops[FinalIndex]->getType()->isVectorTy()) {
6223 if (Value *V = getSplatValue(Ops[FinalIndex])) {
6224 auto *C = dyn_cast<ConstantInt>(V);
6225 // Don't scalarize all zeros vector.
6226 if (!C || !C->isZero()) {
6227 Ops[FinalIndex] = V;
6228 RewriteGEP = true;
6229 }
6230 }
6231 }
6232
6233 // If we made any changes or the we have extra operands, we need to generate
6234 // new instructions.
6235 if (!RewriteGEP && Ops.size() == 2)
6236 return false;
6237
6238 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6239
6240 IRBuilder<> Builder(MemoryInst);
6241
6242 Type *SourceTy = GEP->getSourceElementType();
6243 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
6244
6245 // If the final index isn't a vector, emit a scalar GEP containing all ops
6246 // and a vector GEP with all zeroes final index.
6247 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
6248 NewAddr = Builder.CreateGEP(SourceTy, Ops[0], ArrayRef(Ops).drop_front());
6249 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6250 auto *SecondTy = GetElementPtrInst::getIndexedType(
6251 SourceTy, ArrayRef(Ops).drop_front());
6252 NewAddr =
6253 Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
6254 } else {
6255 Value *Base = Ops[0];
6256 Value *Index = Ops[FinalIndex];
6257
6258 // Create a scalar GEP if there are more than 2 operands.
6259 if (Ops.size() != 2) {
6260 // Replace the last index with 0.
6261 Ops[FinalIndex] =
6262 Constant::getNullValue(Ops[FinalIndex]->getType()->getScalarType());
6263 Base = Builder.CreateGEP(SourceTy, Base, ArrayRef(Ops).drop_front());
6265 SourceTy, ArrayRef(Ops).drop_front());
6266 }
6267
6268 // Now create the GEP with scalar pointer and vector index.
6269 NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
6270 }
6271 } else if (!isa<Constant>(Ptr)) {
6272 // Not a GEP, maybe its a splat and we can create a GEP to enable
6273 // SelectionDAGBuilder to use it as a uniform base.
6274 Value *V = getSplatValue(Ptr);
6275 if (!V)
6276 return false;
6277
6278 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6279
6280 IRBuilder<> Builder(MemoryInst);
6281
6282 // Emit a vector GEP with a scalar pointer and all 0s vector index.
6283 Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
6284 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6285 Type *ScalarTy;
6286 if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6287 Intrinsic::masked_gather) {
6288 ScalarTy = MemoryInst->getType()->getScalarType();
6289 } else {
6290 assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6291 Intrinsic::masked_scatter);
6292 ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
6293 }
6294 NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
6295 } else {
6296 // Constant, SelectionDAGBuilder knows to check if its a splat.
6297 return false;
6298 }
6299
6300 MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
6301
6302 // If we have no uses, recursively delete the value and all dead instructions
6303 // using it.
6304 if (Ptr->use_empty())
6306 Ptr, TLInfo, nullptr,
6307 [&](Value *V) { removeAllAssertingVHReferences(V); });
6308
6309 return true;
6310}
6311
6312// This is a helper for CodeGenPrepare::optimizeMulWithOverflow.
6313// Check the pattern we are interested in where there are maximum 2 uses
6314// of the intrinsic which are the extract instructions.
6316 ExtractValueInst *&OverflowExtract) {
6317 // Bail out if it's more than 2 users:
6318 if (I->hasNUsesOrMore(3))
6319 return false;
6320
6321 for (User *U : I->users()) {
6322 auto *Extract = dyn_cast<ExtractValueInst>(U);
6323 if (!Extract || Extract->getNumIndices() != 1)
6324 return false;
6325
6326 unsigned Index = Extract->getIndices()[0];
6327 if (Index == 0)
6328 MulExtract = Extract;
6329 else if (Index == 1)
6330 OverflowExtract = Extract;
6331 else
6332 return false;
6333 }
6334 return true;
6335}
6336
6337// Rewrite the mul_with_overflow intrinsic by checking if both of the
6338// operands' value ranges are within the legal type. If so, we can optimize the
6339// multiplication algorithm. This code is supposed to be written during the step
6340// of type legalization, but given that we need to reconstruct the IR which is
6341// not doable there, we do it here.
6342// The IR after the optimization will look like:
6343// entry:
6344// if signed:
6345// ( (lhs_lo>>BW-1) ^ lhs_hi) || ( (rhs_lo>>BW-1) ^ rhs_hi) ? overflow,
6346// overflow_no
6347// else:
6348// (lhs_hi != 0) || (rhs_hi != 0) ? overflow, overflow_no
6349// overflow_no:
6350// overflow:
6351// overflow.res:
6352// \returns true if optimization was applied
6353// TODO: This optimization can be further improved to optimize branching on
6354// overflow where the 'overflow_no' BB can branch directly to the false
6355// successor of overflow, but that would add additional complexity so we leave
6356// it for future work.
6357bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
6358 ModifyDT &ModifiedDT) {
6359 // Check if target supports this optimization.
6361 I->getContext(),
6362 TLI->getValueType(*DL, I->getType()->getContainedType(0))))
6363 return false;
6364
6365 ExtractValueInst *MulExtract = nullptr, *OverflowExtract = nullptr;
6366 if (!matchOverflowPattern(I, MulExtract, OverflowExtract))
6367 return false;
6368
6369 // Keep track of the instruction to stop reoptimizing it again.
6370 InsertedInsts.insert(I);
6371
6372 Value *LHS = I->getOperand(0);
6373 Value *RHS = I->getOperand(1);
6374 Type *Ty = LHS->getType();
6375 unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
6376 Type *LegalTy = Ty->getWithNewBitWidth(VTHalfBitWidth);
6377
6378 // New BBs:
6379 BasicBlock *OverflowEntryBB =
6380 splitBlockBefore(I->getParent(), I, DTU, LI, nullptr, "");
6381 OverflowEntryBB->takeName(I->getParent());
6382 // Keep the 'br' instruction that is generated as a result of the split to be
6383 // erased/replaced later.
6384 Instruction *OldTerminator = OverflowEntryBB->getTerminator();
6385 BasicBlock *NoOverflowBB =
6386 BasicBlock::Create(I->getContext(), "overflow.no", I->getFunction());
6387 NoOverflowBB->moveAfter(OverflowEntryBB);
6388 BasicBlock *OverflowBB =
6389 BasicBlock::Create(I->getContext(), "overflow", I->getFunction());
6390 OverflowBB->moveAfter(NoOverflowBB);
6391
6392 // BB overflow.entry:
6393 IRBuilder<> Builder(OverflowEntryBB);
6394 // Extract low and high halves of LHS:
6395 Value *LoLHS = Builder.CreateTrunc(LHS, LegalTy, "lo.lhs");
6396 Value *HiLHS = Builder.CreateLShr(LHS, VTHalfBitWidth, "lhs.lsr");
6397 HiLHS = Builder.CreateTrunc(HiLHS, LegalTy, "hi.lhs");
6398
6399 // Extract low and high halves of RHS:
6400 Value *LoRHS = Builder.CreateTrunc(RHS, LegalTy, "lo.rhs");
6401 Value *HiRHS = Builder.CreateLShr(RHS, VTHalfBitWidth, "rhs.lsr");
6402 HiRHS = Builder.CreateTrunc(HiRHS, LegalTy, "hi.rhs");
6403
6404 Value *IsAnyBitTrue;
6405 if (IsSigned) {
6406 Value *SignLoLHS =
6407 Builder.CreateAShr(LoLHS, VTHalfBitWidth - 1, "sign.lo.lhs");
6408 Value *SignLoRHS =
6409 Builder.CreateAShr(LoRHS, VTHalfBitWidth - 1, "sign.lo.rhs");
6410 Value *XorLHS = Builder.CreateXor(HiLHS, SignLoLHS);
6411 Value *XorRHS = Builder.CreateXor(HiRHS, SignLoRHS);
6412 Value *Or = Builder.CreateOr(XorLHS, XorRHS, "or.lhs.rhs");
6413 IsAnyBitTrue = Builder.CreateCmp(ICmpInst::ICMP_NE, Or,
6414 ConstantInt::getNullValue(Or->getType()));
6415 } else {
6416 Value *CmpLHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiLHS,
6417 ConstantInt::getNullValue(LegalTy));
6418 Value *CmpRHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiRHS,
6419 ConstantInt::getNullValue(LegalTy));
6420 IsAnyBitTrue = Builder.CreateOr(CmpLHS, CmpRHS, "or.lhs.rhs");
6421 }
6422 Builder.CreateCondBr(IsAnyBitTrue, OverflowBB, NoOverflowBB);
6423
6424 // BB overflow.no:
6425 Builder.SetInsertPoint(NoOverflowBB);
6426 Value *ExtLoLHS, *ExtLoRHS;
6427 if (IsSigned) {
6428 ExtLoLHS = Builder.CreateSExt(LoLHS, Ty, "lo.lhs.ext");
6429 ExtLoRHS = Builder.CreateSExt(LoRHS, Ty, "lo.rhs.ext");
6430 } else {
6431 ExtLoLHS = Builder.CreateZExt(LoLHS, Ty, "lo.lhs.ext");
6432 ExtLoRHS = Builder.CreateZExt(LoRHS, Ty, "lo.rhs.ext");
6433 }
6434
6435 Value *Mul = Builder.CreateMul(ExtLoLHS, ExtLoRHS, "mul.overflow.no");
6436
6437 // Create the 'overflow.res' BB to merge the results of
6438 // the two paths:
6439 BasicBlock *OverflowResBB = I->getParent();
6440 OverflowResBB->setName("overflow.res");
6441
6442 // BB overflow.no: jump to overflow.res BB
6443 Builder.CreateBr(OverflowResBB);
6444 // No we don't need the old terminator in overflow.entry BB, erase it:
6445 OldTerminator->eraseFromParent();
6446
6447 // BB overflow.res:
6448 Builder.SetInsertPoint(OverflowResBB->getFirstInsertionPt());
6449 // Create PHI nodes to merge results from no.overflow BB and overflow BB to
6450 // replace the extract instructions.
6451 PHINode *OverflowResPHI = Builder.CreatePHI(Ty, 2),
6452 *OverflowFlagPHI =
6453 Builder.CreatePHI(IntegerType::getInt1Ty(I->getContext()), 2);
6454
6455 // Add the incoming values from no.overflow BB and later from overflow BB.
6456 OverflowResPHI->addIncoming(Mul, NoOverflowBB);
6457 OverflowFlagPHI->addIncoming(ConstantInt::getFalse(I->getContext()),
6458 NoOverflowBB);
6459
6460 // Replace all users of MulExtract and OverflowExtract to use the PHI nodes.
6461 if (MulExtract) {
6462 MulExtract->replaceAllUsesWith(OverflowResPHI);
6463 MulExtract->eraseFromParent();
6464 }
6465 if (OverflowExtract) {
6466 OverflowExtract->replaceAllUsesWith(OverflowFlagPHI);
6467 OverflowExtract->eraseFromParent();
6468 }
6469
6470 // Remove the intrinsic from parent (overflow.res BB) as it will be part of
6471 // overflow BB
6472 I->removeFromParent();
6473 // BB overflow:
6474 I->insertInto(OverflowBB, OverflowBB->end());
6475 Builder.SetInsertPoint(OverflowBB->end());
6476 Value *MulOverflow = Builder.CreateExtractValue(I, {0}, "mul.overflow");
6477 Value *OverflowFlag = Builder.CreateExtractValue(I, {1}, "overflow.flag");
6478 Builder.CreateBr(OverflowResBB);
6479
6480 // Add The Extracted values to the PHINodes in the overflow.res BB.
6481 OverflowResPHI->addIncoming(MulOverflow, OverflowBB);
6482 OverflowFlagPHI->addIncoming(OverflowFlag, OverflowBB);
6483
6484 DTU->applyUpdates({{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
6485 {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
6486 {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
6487 {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
6488 {DominatorTree::Insert, OverflowBB, OverflowResBB}});
6489
6490 ModifiedDT = ModifyDT::ModifyBBDT;
6491 return true;
6492}
6493
6494/// If there are any memory operands, use OptimizeMemoryInst to sink their
6495/// address computing into the block when possible / profitable.
6496bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
6497 bool MadeChange = false;
6498
6499 const TargetRegisterInfo *TRI =
6501 TargetLowering::AsmOperandInfoVector TargetConstraints =
6502 TLI->ParseConstraints(*DL, TRI, *CS);
6503 unsigned ArgNo = 0;
6504 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
6505 // Compute the constraint code and ConstraintType to use.
6506 TLI->ComputeConstraintToUse(OpInfo, SDValue());
6507
6508 // TODO: Also handle C_Address?
6509 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6510 OpInfo.isIndirect) {
6511 Value *OpVal = CS->getArgOperand(ArgNo++);
6512 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
6513 } else if (OpInfo.Type == InlineAsm::isInput)
6514 ArgNo++;
6515 }
6516
6517 return MadeChange;
6518}
6519
6520/// Check if all the uses of \p Val are equivalent (or free) zero or
6521/// sign extensions.
6522static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
6523 assert(!Val->use_empty() && "Input must have at least one use");
6524 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
6525 bool IsSExt = isa<SExtInst>(FirstUser);
6526 Type *ExtTy = FirstUser->getType();
6527 for (const User *U : Val->users()) {
6528 const Instruction *UI = cast<Instruction>(U);
6529 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
6530 return false;
6531 Type *CurTy = UI->getType();
6532 // Same input and output types: Same instruction after CSE.
6533 if (CurTy == ExtTy)
6534 continue;
6535
6536 // If IsSExt is true, we are in this situation:
6537 // a = Val
6538 // b = sext ty1 a to ty2
6539 // c = sext ty1 a to ty3
6540 // Assuming ty2 is shorter than ty3, this could be turned into:
6541 // a = Val
6542 // b = sext ty1 a to ty2
6543 // c = sext ty2 b to ty3
6544 // However, the last sext is not free.
6545 if (IsSExt)
6546 return false;
6547
6548 // This is a ZExt, maybe this is free to extend from one type to another.
6549 // In that case, we would not account for a different use.
6550 Type *NarrowTy;
6551 Type *LargeTy;
6552 if (ExtTy->getScalarType()->getIntegerBitWidth() >
6553 CurTy->getScalarType()->getIntegerBitWidth()) {
6554 NarrowTy = CurTy;
6555 LargeTy = ExtTy;
6556 } else {
6557 NarrowTy = ExtTy;
6558 LargeTy = CurTy;
6559 }
6560
6561 if (!TLI.isZExtFree(NarrowTy, LargeTy))
6562 return false;
6563 }
6564 // All uses are the same or can be derived from one another for free.
6565 return true;
6566}
6567
6568/// Try to speculatively promote extensions in \p Exts and continue
6569/// promoting through newly promoted operands recursively as far as doing so is
6570/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
6571/// When some promotion happened, \p TPT contains the proper state to revert
6572/// them.
6573///
6574/// \return true if some promotion happened, false otherwise.
6575bool CodeGenPrepare::tryToPromoteExts(
6576 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
6577 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
6578 unsigned CreatedInstsCost) {
6579 bool Promoted = false;
6580
6581 // Iterate over all the extensions to try to promote them.
6582 for (auto *I : Exts) {
6583 // Early check if we directly have ext(load).
6584 if (isa<LoadInst>(I->getOperand(0))) {
6585 ProfitablyMovedExts.push_back(I);
6586 continue;
6587 }
6588
6589 // Check whether or not we want to do any promotion. The reason we have
6590 // this check inside the for loop is to catch the case where an extension
6591 // is directly fed by a load because in such case the extension can be moved
6592 // up without any promotion on its operands.
6593 if (!TLI->enableExtLdPromotion() || !Opts.cgp_ext_ld_promotion)
6594 return false;
6595
6596 // Get the action to perform the promotion.
6597 TypePromotionHelper::Action TPH =
6598 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
6599 // Check if we can promote.
6600 if (!TPH) {
6601 // Save the current extension as we cannot move up through its operand.
6602 ProfitablyMovedExts.push_back(I);
6603 continue;
6604 }
6605
6606 // Save the current state.
6607 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6608 TPT.getRestorationPoint();
6609 SmallVector<Instruction *, 4> NewExts;
6610 unsigned NewCreatedInstsCost = 0;
6611 unsigned ExtCost = !TLI->isExtFree(I);
6612 // Promote.
6613 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
6614 &NewExts, nullptr, *TLI);
6615 assert(PromotedVal &&
6616 "TypePromotionHelper should have filtered out those cases");
6617
6618 // We would be able to merge only one extension in a load.
6619 // Therefore, if we have more than 1 new extension we heuristically
6620 // cut this search path, because it means we degrade the code quality.
6621 // With exactly 2, the transformation is neutral, because we will merge
6622 // one extension but leave one. However, we optimistically keep going,
6623 // because the new extension may be removed too. Also avoid replacing a
6624 // single free extension with multiple extensions, as this increases the
6625 // number of IR instructions while not providing any savings.
6626 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
6627 // FIXME: It would be possible to propagate a negative value instead of
6628 // conservatively ceiling it to 0.
6629 TotalCreatedInstsCost =
6630 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
6631 if (!Opts.cgp_stress_ext_ld_promotion &&
6632 (TotalCreatedInstsCost > 1 ||
6633 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal) ||
6634 (ExtCost == 0 && NewExts.size() > 1))) {
6635 // This promotion is not profitable, rollback to the previous state, and
6636 // save the current extension in ProfitablyMovedExts as the latest
6637 // speculative promotion turned out to be unprofitable.
6638 TPT.rollback(LastKnownGood);
6639 ProfitablyMovedExts.push_back(I);
6640 continue;
6641 }
6642 // Continue promoting NewExts as far as doing so is profitable.
6643 SmallVector<Instruction *, 2> NewlyMovedExts;
6644 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
6645 bool NewPromoted = false;
6646 for (auto *ExtInst : NewlyMovedExts) {
6647 Instruction *MovedExt = cast<Instruction>(ExtInst);
6648 Value *ExtOperand = MovedExt->getOperand(0);
6649 // If we have reached to a load, we need this extra profitability check
6650 // as it could potentially be merged into an ext(load).
6651 if (isa<LoadInst>(ExtOperand) &&
6652 !(Opts.cgp_stress_ext_ld_promotion ||
6653 NewCreatedInstsCost <= ExtCost ||
6654 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
6655 continue;
6656
6657 ProfitablyMovedExts.push_back(MovedExt);
6658 NewPromoted = true;
6659 }
6660
6661 // If none of speculative promotions for NewExts is profitable, rollback
6662 // and save the current extension (I) as the last profitable extension.
6663 if (!NewPromoted) {
6664 TPT.rollback(LastKnownGood);
6665 ProfitablyMovedExts.push_back(I);
6666 continue;
6667 }
6668 // The promotion is profitable.
6669 Promoted = true;
6670 }
6671 return Promoted;
6672}
6673
6674/// Merging redundant sexts when one is dominating the other.
6675bool CodeGenPrepare::mergeSExts(Function &F) {
6676 bool Changed = false;
6677 for (auto &Entry : ValToSExtendedUses) {
6678 SExts &Insts = Entry.second;
6679 SExts CurPts;
6680 for (Instruction *Inst : Insts) {
6681 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
6682 Inst->getOperand(0) != Entry.first)
6683 continue;
6684 bool inserted = false;
6685 for (auto &Pt : CurPts) {
6686 if (getDT().dominates(Inst, Pt)) {
6687 replaceAllUsesWith(Pt, Inst, FreshBBs, IsHugeFunc);
6688 RemovedInsts.insert(Pt);
6689 Pt->removeFromParent();
6690 Pt = Inst;
6691 inserted = true;
6692 Changed = true;
6693 break;
6694 }
6695 if (!getDT().dominates(Pt, Inst))
6696 // Give up if we need to merge in a common dominator as the
6697 // experiments show it is not profitable.
6698 continue;
6699 replaceAllUsesWith(Inst, Pt, FreshBBs, IsHugeFunc);
6700 RemovedInsts.insert(Inst);
6701 Inst->removeFromParent();
6702 inserted = true;
6703 Changed = true;
6704 break;
6705 }
6706 if (!inserted)
6707 CurPts.push_back(Inst);
6708 }
6709 }
6710 return Changed;
6711}
6712
6713// Splitting large data structures so that the GEPs accessing them can have
6714// smaller offsets so that they can be sunk to the same blocks as their users.
6715// For example, a large struct starting from %base is split into two parts
6716// where the second part starts from %new_base.
6717//
6718// Before:
6719// BB0:
6720// %base =
6721//
6722// BB1:
6723// %gep0 = gep %base, off0
6724// %gep1 = gep %base, off1
6725// %gep2 = gep %base, off2
6726//
6727// BB2:
6728// %load1 = load %gep0
6729// %load2 = load %gep1
6730// %load3 = load %gep2
6731//
6732// After:
6733// BB0:
6734// %base =
6735// %new_base = gep %base, off0
6736//
6737// BB1:
6738// %new_gep0 = %new_base
6739// %new_gep1 = gep %new_base, off1 - off0
6740// %new_gep2 = gep %new_base, off2 - off0
6741//
6742// BB2:
6743// %load1 = load i32, i32* %new_gep0
6744// %load2 = load i32, i32* %new_gep1
6745// %load3 = load i32, i32* %new_gep2
6746//
6747// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
6748// their offsets are smaller enough to fit into the addressing mode.
6749bool CodeGenPrepare::splitLargeGEPOffsets() {
6750 bool Changed = false;
6751 for (auto &Entry : LargeOffsetGEPMap) {
6752 Value *OldBase = Entry.first;
6753 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
6754 &LargeOffsetGEPs = Entry.second;
6755 auto compareGEPOffset =
6756 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
6757 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
6758 if (LHS.first == RHS.first)
6759 return false;
6760 if (LHS.second != RHS.second)
6761 return LHS.second < RHS.second;
6762 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
6763 };
6764 // Sorting all the GEPs of the same data structures based on the offsets.
6765 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
6766 LargeOffsetGEPs.erase(llvm::unique(LargeOffsetGEPs), LargeOffsetGEPs.end());
6767 // Skip if all the GEPs have the same offsets.
6768 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
6769 continue;
6770 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
6771 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
6772 Value *NewBaseGEP = nullptr;
6773
6774 auto createNewBase = [&](int64_t BaseOffset, Value *OldBase,
6775 GetElementPtrInst *GEP) {
6776 LLVMContext &Ctx = GEP->getContext();
6777 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6778 Type *I8PtrTy =
6779 PointerType::get(Ctx, GEP->getType()->getPointerAddressSpace());
6780
6781 BasicBlock::iterator NewBaseInsertPt;
6782 BasicBlock *NewBaseInsertBB;
6783 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
6784 // If the base of the struct is an instruction, the new base will be
6785 // inserted close to it.
6786 NewBaseInsertBB = BaseI->getParent();
6787 if (isa<PHINode>(BaseI))
6788 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6789 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
6790 NewBaseInsertBB =
6791 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest(), &getDT(), LI);
6792 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6793 } else
6794 NewBaseInsertPt = std::next(BaseI->getIterator());
6795 } else {
6796 // If the current base is an argument or global value, the new base
6797 // will be inserted to the entry block.
6798 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
6799 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6800 }
6801 IRBuilder<> NewBaseBuilder(NewBaseInsertPt);
6802 // Create a new base.
6803 // TODO: Avoid implicit trunc?
6804 // See https://github.com/llvm/llvm-project/issues/112510.
6805 Value *BaseIndex =
6806 ConstantInt::getSigned(PtrIdxTy, BaseOffset, /*ImplicitTrunc=*/true);
6807 NewBaseGEP = OldBase;
6808 if (NewBaseGEP->getType() != I8PtrTy)
6809 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
6810 NewBaseGEP =
6811 NewBaseBuilder.CreatePtrAdd(NewBaseGEP, BaseIndex, "splitgep");
6812 NewGEPBases.insert(NewBaseGEP);
6813 return;
6814 };
6815
6816 // Check whether all the offsets can be encoded with prefered common base.
6817 if (int64_t PreferBase = TLI->getPreferredLargeGEPBaseOffset(
6818 LargeOffsetGEPs.front().second, LargeOffsetGEPs.back().second)) {
6819 BaseOffset = PreferBase;
6820 // Create a new base if the offset of the BaseGEP can be decoded with one
6821 // instruction.
6822 createNewBase(BaseOffset, OldBase, BaseGEP);
6823 }
6824
6825 auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
6826 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
6827 GetElementPtrInst *GEP = LargeOffsetGEP->first;
6828 int64_t Offset = LargeOffsetGEP->second;
6829 if (Offset != BaseOffset) {
6830 TargetLowering::AddrMode AddrMode;
6831 AddrMode.HasBaseReg = true;
6832 AddrMode.BaseOffs = Offset - BaseOffset;
6833 // The result type of the GEP might not be the type of the memory
6834 // access.
6835 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
6836 GEP->getResultElementType(),
6837 GEP->getAddressSpace())) {
6838 // We need to create a new base if the offset to the current base is
6839 // too large to fit into the addressing mode. So, a very large struct
6840 // may be split into several parts.
6841 BaseGEP = GEP;
6842 BaseOffset = Offset;
6843 NewBaseGEP = nullptr;
6844 }
6845 }
6846
6847 // Generate a new GEP to replace the current one.
6848 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6849
6850 if (!NewBaseGEP) {
6851 // Create a new base if we don't have one yet. Find the insertion
6852 // pointer for the new base first.
6853 createNewBase(BaseOffset, OldBase, GEP);
6854 }
6855
6856 IRBuilder<> Builder(GEP);
6857 Value *NewGEP = NewBaseGEP;
6858 if (Offset != BaseOffset) {
6859 // Calculate the new offset for the new GEP.
6860 Value *Index = ConstantInt::get(PtrIdxTy, Offset - BaseOffset);
6861 NewGEP = Builder.CreatePtrAdd(NewBaseGEP, Index);
6862 }
6863 replaceAllUsesWith(GEP, NewGEP, FreshBBs, IsHugeFunc);
6864 LargeOffsetGEPID.erase(GEP);
6865 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
6866 GEP->eraseFromParent();
6867 Changed = true;
6868 }
6869 }
6870 return Changed;
6871}
6872
6873bool CodeGenPrepare::optimizePhiType(
6874 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
6875 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
6876 // We are looking for a collection on interconnected phi nodes that together
6877 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
6878 // are of the same type. Convert the whole set of nodes to the type of the
6879 // bitcast.
6880 Type *PhiTy = I->getType();
6881 Type *ConvertTy = nullptr;
6882 if (Visited.count(I) ||
6883 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
6884 return false;
6885
6886 SmallVector<Instruction *, 4> Worklist;
6887 Worklist.push_back(cast<Instruction>(I));
6888 SmallPtrSet<PHINode *, 4> PhiNodes;
6889 SmallPtrSet<ConstantData *, 4> Constants;
6890 PhiNodes.insert(I);
6891 Visited.insert(I);
6892 SmallPtrSet<Instruction *, 4> Defs;
6893 SmallPtrSet<Instruction *, 4> Uses;
6894 // This works by adding extra bitcasts between load/stores and removing
6895 // existing bitcasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
6896 // we can get in the situation where we remove a bitcast in one iteration
6897 // just to add it again in the next. We need to ensure that at least one
6898 // bitcast we remove are anchored to something that will not change back.
6899 bool AnyAnchored = false;
6900
6901 while (!Worklist.empty()) {
6902 Instruction *II = Worklist.pop_back_val();
6903
6904 if (auto *Phi = dyn_cast<PHINode>(II)) {
6905 // Handle Defs, which might also be PHI's
6906 for (Value *V : Phi->incoming_values()) {
6907 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
6908 if (!PhiNodes.count(OpPhi)) {
6909 if (!Visited.insert(OpPhi).second)
6910 return false;
6911 PhiNodes.insert(OpPhi);
6912 Worklist.push_back(OpPhi);
6913 }
6914 } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) {
6915 if (!OpLoad->isSimple())
6916 return false;
6917 if (Defs.insert(OpLoad).second)
6918 Worklist.push_back(OpLoad);
6919 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) {
6920 if (Defs.insert(OpEx).second)
6921 Worklist.push_back(OpEx);
6922 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
6923 if (!ConvertTy)
6924 ConvertTy = OpBC->getOperand(0)->getType();
6925 if (OpBC->getOperand(0)->getType() != ConvertTy)
6926 return false;
6927 if (Defs.insert(OpBC).second) {
6928 Worklist.push_back(OpBC);
6929 AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) &&
6930 !isa<ExtractElementInst>(OpBC->getOperand(0));
6931 }
6932 } else if (auto *OpC = dyn_cast<ConstantData>(V))
6933 Constants.insert(OpC);
6934 else
6935 return false;
6936 }
6937 }
6938
6939 // Handle uses which might also be phi's
6940 for (User *V : II->users()) {
6941 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
6942 if (!PhiNodes.count(OpPhi)) {
6943 if (Visited.count(OpPhi))
6944 return false;
6945 PhiNodes.insert(OpPhi);
6946 Visited.insert(OpPhi);
6947 Worklist.push_back(OpPhi);
6948 }
6949 } else if (auto *OpStore = dyn_cast<StoreInst>(V)) {
6950 if (!OpStore->isSimple() || OpStore->getOperand(0) != II)
6951 return false;
6952 Uses.insert(OpStore);
6953 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
6954 if (!ConvertTy)
6955 ConvertTy = OpBC->getType();
6956 if (OpBC->getType() != ConvertTy)
6957 return false;
6958 Uses.insert(OpBC);
6959 AnyAnchored |=
6960 any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); });
6961 } else {
6962 return false;
6963 }
6964 }
6965 }
6966
6967 if (!ConvertTy || !AnyAnchored || PhiTy == ConvertTy ||
6968 !TLI->shouldConvertPhiType(PhiTy, ConvertTy))
6969 return false;
6970
6971 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "
6972 << *ConvertTy << "\n");
6973
6974 // Create all the new phi nodes of the new type, and bitcast any loads to the
6975 // correct type.
6976 ValueToValueMap ValMap;
6977 for (ConstantData *C : Constants)
6978 ValMap[C] = ConstantExpr::getBitCast(C, ConvertTy);
6979 for (Instruction *D : Defs) {
6980 if (isa<BitCastInst>(D)) {
6981 ValMap[D] = D->getOperand(0);
6982 DeletedInstrs.insert(D);
6983 } else {
6984 BasicBlock::iterator insertPt = std::next(D->getIterator());
6985 ValMap[D] = new BitCastInst(D, ConvertTy, D->getName() + ".bc", insertPt);
6986 }
6987 }
6988 for (PHINode *Phi : PhiNodes)
6989 ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(),
6990 Phi->getName() + ".tc", Phi->getIterator());
6991 // Pipe together all the PhiNodes.
6992 for (PHINode *Phi : PhiNodes) {
6993 PHINode *NewPhi = cast<PHINode>(ValMap[Phi]);
6994 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
6995 NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)],
6996 Phi->getIncomingBlock(i));
6997 Visited.insert(NewPhi);
6998 }
6999 // And finally pipe up the stores and bitcasts
7000 for (Instruction *U : Uses) {
7001 if (isa<BitCastInst>(U)) {
7002 DeletedInstrs.insert(U);
7003 replaceAllUsesWith(U, ValMap[U->getOperand(0)], FreshBBs, IsHugeFunc);
7004 } else {
7005 U->setOperand(0, new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc",
7006 U->getIterator()));
7007 }
7008 }
7009
7010 // Save the removed phis to be deleted later.
7011 DeletedInstrs.insert_range(PhiNodes);
7012 return true;
7013}
7014
7015bool CodeGenPrepare::optimizePhiTypes(Function &F) {
7016 if (!Opts.cgp_optimize_phi_types)
7017 return false;
7018
7019 bool Changed = false;
7020 SmallPtrSet<PHINode *, 4> Visited;
7021 SmallPtrSet<Instruction *, 4> DeletedInstrs;
7022
7023 // Attempt to optimize all the phis in the functions to the correct type.
7024 for (auto &BB : F)
7025 for (auto &Phi : BB.phis())
7026 Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs);
7027
7028 // Remove any old phi's that have been converted.
7029 for (auto *I : DeletedInstrs) {
7030 replaceAllUsesWith(I, PoisonValue::get(I->getType()), FreshBBs, IsHugeFunc);
7031 I->eraseFromParent();
7032 }
7033
7034 return Changed;
7035}
7036
7037/// Return true, if an ext(load) can be formed from an extension in
7038/// \p MovedExts.
7039bool CodeGenPrepare::canFormExtLd(
7040 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
7041 Instruction *&Inst, bool HasPromoted) {
7042 for (auto *MovedExtInst : MovedExts) {
7043 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
7044 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
7045 Inst = MovedExtInst;
7046 break;
7047 }
7048 }
7049 if (!LI)
7050 return false;
7051
7052 // If they're already in the same block, there's nothing to do.
7053 // Make the cheap checks first if we did not promote.
7054 // If we promoted, we need to check if it is indeed profitable.
7055 if (!HasPromoted && LI->getParent() == Inst->getParent())
7056 return false;
7057
7058 return TLI->isExtLoad(LI, Inst, *DL);
7059}
7060
7061/// Move a zext or sext fed by a load into the same basic block as the load,
7062/// unless conditions are unfavorable. This allows SelectionDAG to fold the
7063/// extend into the load.
7064///
7065/// E.g.,
7066/// \code
7067/// %ld = load i32* %addr
7068/// %add = add nuw i32 %ld, 4
7069/// %zext = zext i32 %add to i64
7070// \endcode
7071/// =>
7072/// \code
7073/// %ld = load i32* %addr
7074/// %zext = zext i32 %ld to i64
7075/// %add = add nuw i64 %zext, 4
7076/// \encode
7077/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
7078/// allow us to match zext(load i32*) to i64.
7079///
7080/// Also, try to promote the computations used to obtain a sign extended
7081/// value used into memory accesses.
7082/// E.g.,
7083/// \code
7084/// a = add nsw i32 b, 3
7085/// d = sext i32 a to i64
7086/// e = getelementptr ..., i64 d
7087/// \endcode
7088/// =>
7089/// \code
7090/// f = sext i32 b to i64
7091/// a = add nsw i64 f, 3
7092/// e = getelementptr ..., i64 a
7093/// \endcode
7094///
7095/// \p Inst[in/out] the extension may be modified during the process if some
7096/// promotions apply.
7097bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
7098 bool AllowPromotionWithoutCommonHeader = false;
7099 /// See if it is an interesting sext operations for the address type
7100 /// promotion before trying to promote it, e.g., the ones with the right
7101 /// type and used in memory accesses.
7102 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
7103 *Inst, AllowPromotionWithoutCommonHeader);
7104 TypePromotionTransaction TPT(RemovedInsts);
7105 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
7106 TPT.getRestorationPoint();
7108 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
7109 Exts.push_back(Inst);
7110
7111 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
7112
7113 // Look for a load being extended.
7114 LoadInst *LI = nullptr;
7115 Instruction *ExtFedByLoad;
7116
7117 // Try to promote a chain of computation if it allows to form an extended
7118 // load.
7119 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
7120 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
7121 TPT.commit();
7122 // Move the extend into the same block as the load.
7123 ExtFedByLoad->moveAfter(LI);
7124 ++NumExtsMoved;
7125 Inst = ExtFedByLoad;
7126 return true;
7127 }
7128
7129 // Continue promoting SExts if known as considerable depending on targets.
7130 if (ATPConsiderable &&
7131 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
7132 HasPromoted, TPT, SpeculativelyMovedExts))
7133 return true;
7134
7135 TPT.rollback(LastKnownGood);
7136 return false;
7137}
7138
7139// Perform address type promotion if doing so is profitable.
7140// If AllowPromotionWithoutCommonHeader == false, we should find other sext
7141// instructions that sign extended the same initial value. However, if
7142// AllowPromotionWithoutCommonHeader == true, we expect promoting the
7143// extension is just profitable.
7144bool CodeGenPrepare::performAddressTypePromotion(
7145 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
7146 bool HasPromoted, TypePromotionTransaction &TPT,
7147 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
7148 bool Promoted = false;
7149 SmallPtrSet<Instruction *, 1> UnhandledExts;
7150 bool AllSeenFirst = true;
7151 for (auto *I : SpeculativelyMovedExts) {
7152 Value *HeadOfChain = I->getOperand(0);
7153 auto AlreadySeen = SeenChainsForSExt.find(HeadOfChain);
7154 // If there is an unhandled SExt which has the same header, try to promote
7155 // it as well.
7156 if (AlreadySeen != SeenChainsForSExt.end()) {
7157 if (AlreadySeen->second != nullptr)
7158 UnhandledExts.insert(AlreadySeen->second);
7159 AllSeenFirst = false;
7160 }
7161 }
7162
7163 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
7164 SpeculativelyMovedExts.size() == 1)) {
7165 TPT.commit();
7166 if (HasPromoted)
7167 Promoted = true;
7168 for (auto *I : SpeculativelyMovedExts) {
7169 Value *HeadOfChain = I->getOperand(0);
7170 SeenChainsForSExt[HeadOfChain] = nullptr;
7171 ValToSExtendedUses[HeadOfChain].push_back(I);
7172 }
7173 // Update Inst as promotion happen.
7174 Inst = SpeculativelyMovedExts.pop_back_val();
7175 } else {
7176 // This is the first chain visited from the header, keep the current chain
7177 // as unhandled. Defer to promote this until we encounter another SExt
7178 // chain derived from the same header.
7179 for (auto *I : SpeculativelyMovedExts) {
7180 Value *HeadOfChain = I->getOperand(0);
7181 SeenChainsForSExt[HeadOfChain] = Inst;
7182 }
7183 return false;
7184 }
7185
7186 if (!AllSeenFirst && !UnhandledExts.empty())
7187 for (auto *VisitedSExt : UnhandledExts) {
7188 if (RemovedInsts.count(VisitedSExt))
7189 continue;
7190 TypePromotionTransaction TPT(RemovedInsts);
7192 SmallVector<Instruction *, 2> Chains;
7193 Exts.push_back(VisitedSExt);
7194 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
7195 TPT.commit();
7196 if (HasPromoted)
7197 Promoted = true;
7198 for (auto *I : Chains) {
7199 Value *HeadOfChain = I->getOperand(0);
7200 // Mark this as handled.
7201 SeenChainsForSExt[HeadOfChain] = nullptr;
7202 ValToSExtendedUses[HeadOfChain].push_back(I);
7203 }
7204 }
7205 return Promoted;
7206}
7207
7208bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
7209 BasicBlock *DefBB = I->getParent();
7210
7211 // If the result of a {s|z}ext and its source are both live out, rewrite all
7212 // other uses of the source with result of extension.
7213 Value *Src = I->getOperand(0);
7214 if (Src->hasOneUse())
7215 return false;
7216
7217 // Only do this xform if truncating is free.
7218 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
7219 return false;
7220
7221 // Only safe to perform the optimization if the source is also defined in
7222 // this block.
7223 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
7224 return false;
7225
7226 bool DefIsLiveOut = false;
7227 for (User *U : I->users()) {
7229
7230 // Figure out which BB this ext is used in.
7231 BasicBlock *UserBB = UI->getParent();
7232 if (UserBB == DefBB)
7233 continue;
7234 DefIsLiveOut = true;
7235 break;
7236 }
7237 if (!DefIsLiveOut)
7238 return false;
7239
7240 // Make sure none of the uses are PHI nodes.
7241 for (User *U : Src->users()) {
7243 BasicBlock *UserBB = UI->getParent();
7244 if (UserBB == DefBB)
7245 continue;
7246 // Be conservative. We don't want this xform to end up introducing
7247 // reloads just before load / store instructions.
7248 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
7249 return false;
7250 }
7251
7252 // InsertedTruncs - Only insert one trunc in each block once.
7253 DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
7254
7255 bool MadeChange = false;
7256 for (Use &U : make_early_inc_range(Src->uses())) {
7257 Instruction *User = cast<Instruction>(U.getUser());
7258
7259 // Figure out which BB this ext is used in.
7260 BasicBlock *UserBB = User->getParent();
7261 if (UserBB == DefBB)
7262 continue;
7263
7264 // Both src and def are live in this block. Rewrite the use.
7265 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
7266
7267 if (!InsertedTrunc) {
7268 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
7269 assert(InsertPt != UserBB->end());
7270 InsertedTrunc = new TruncInst(I, Src->getType(), "");
7271 InsertedTrunc->insertBefore(*UserBB, InsertPt);
7272 InsertedInsts.insert(InsertedTrunc);
7273 }
7274
7275 // Replace a use of the {s|z}ext source with a use of the result.
7276 U = InsertedTrunc;
7277 ++NumExtUses;
7278 MadeChange = true;
7279 }
7280
7281 // The uses rewritten above read trunc(I), which equals Src only where I isn't
7282 // poison. A poison-generating flag such as zext nneg can only hold under a
7283 // guard, such as a sign check of Src, that itself is one of those uses.
7284 if (MadeChange)
7285 I->dropPoisonGeneratingFlags();
7286
7287 return MadeChange;
7288}
7289
7290// Find loads whose uses only use some of the loaded value's bits. Add an "and"
7291// just after the load if the target can fold this into one extload instruction,
7292// with the hope of eliminating some of the other later "and" instructions using
7293// the loaded value. "and"s that are made trivially redundant by the insertion
7294// of the new "and" are removed by this function, while others (e.g. those whose
7295// path from the load goes through a phi) are left for isel to potentially
7296// remove.
7297//
7298// For example:
7299//
7300// b0:
7301// x = load i32
7302// ...
7303// b1:
7304// y = and x, 0xff
7305// z = use y
7306//
7307// becomes:
7308//
7309// b0:
7310// x = load i32
7311// x' = and x, 0xff
7312// ...
7313// b1:
7314// z = use x'
7315//
7316// whereas:
7317//
7318// b0:
7319// x1 = load i32
7320// ...
7321// b1:
7322// x2 = load i32
7323// ...
7324// b2:
7325// x = phi x1, x2
7326// y = and x, 0xff
7327//
7328// becomes (after a call to optimizeLoadExt for each load):
7329//
7330// b0:
7331// x1 = load i32
7332// x1' = and x1, 0xff
7333// ...
7334// b1:
7335// x2 = load i32
7336// x2' = and x2, 0xff
7337// ...
7338// b2:
7339// x = phi x1', x2'
7340// y = and x, 0xff
7341bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
7342 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
7343 return false;
7344
7345 // Skip loads we've already transformed.
7346 if (Load->hasOneUse() &&
7347 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
7348 return false;
7349
7350 // Look at all uses of Load, looking through phis, to determine how many bits
7351 // of the loaded value are needed.
7352 SmallVector<Instruction *, 8> WorkList;
7353 SmallPtrSet<Instruction *, 16> Visited;
7354 SmallVector<Instruction *, 8> AndsToMaybeRemove;
7355 SmallVector<Instruction *, 8> DropFlags;
7356 for (auto *U : Load->users())
7357 WorkList.push_back(cast<Instruction>(U));
7358
7359 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
7360 unsigned BitWidth = LoadResultVT.getSizeInBits();
7361 // If the BitWidth is 0, do not try to optimize the type
7362 if (BitWidth == 0)
7363 return false;
7364
7365 APInt DemandBits(BitWidth, 0);
7366 APInt WidestAndBits(BitWidth, 0);
7367
7368 while (!WorkList.empty()) {
7369 Instruction *I = WorkList.pop_back_val();
7370
7371 // Break use-def graph loops.
7372 if (!Visited.insert(I).second)
7373 continue;
7374
7375 // For a PHI node, push all of its users.
7376 if (auto *Phi = dyn_cast<PHINode>(I)) {
7377 for (auto *U : Phi->users())
7378 WorkList.push_back(cast<Instruction>(U));
7379 continue;
7380 }
7381
7382 switch (I->getOpcode()) {
7383 case Instruction::And: {
7384 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
7385 if (!AndC)
7386 return false;
7387 APInt AndBits = AndC->getValue();
7388 DemandBits |= AndBits;
7389 // Keep track of the widest and mask we see.
7390 if (AndBits.ugt(WidestAndBits))
7391 WidestAndBits = AndBits;
7392 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
7393 AndsToMaybeRemove.push_back(I);
7394 break;
7395 }
7396
7397 case Instruction::Shl: {
7398 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
7399 if (!ShlC)
7400 return false;
7401 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
7402 DemandBits.setLowBits(BitWidth - ShiftAmt);
7403 DropFlags.push_back(I);
7404 break;
7405 }
7406
7407 case Instruction::Trunc: {
7408 EVT TruncVT = TLI->getValueType(*DL, I->getType());
7409 unsigned TruncBitWidth = TruncVT.getSizeInBits();
7410 DemandBits.setLowBits(TruncBitWidth);
7411 DropFlags.push_back(I);
7412 break;
7413 }
7414
7415 default:
7416 return false;
7417 }
7418 }
7419
7420 uint32_t ActiveBits = DemandBits.getActiveBits();
7421 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
7422 // target even if isLoadLegal says an i1 EXTLOAD is valid. For example,
7423 // for the AArch64 target isLoadLegal(i32, i1, ..., ZEXTLOAD, false) returns
7424 // true, but (and (load x) 1) is not matched as a single instruction, rather
7425 // as a LDR followed by an AND.
7426 // TODO: Look into removing this restriction by fixing backends to either
7427 // return false for isLoadLegal for i1 or have them select this pattern to
7428 // a single instruction.
7429 //
7430 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
7431 // mask, since these are the only ands that will be removed by isel.
7432 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
7433 WidestAndBits != DemandBits)
7434 return false;
7435
7436 LLVMContext &Ctx = Load->getType()->getContext();
7437 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
7438 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
7439
7440 // Reject cases that won't be matched as extloads.
7441 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
7442 !TLI->isLoadLegal(LoadResultVT, TruncVT, Load->getAlign(),
7443 Load->getPointerAddressSpace(), ISD::ZEXTLOAD, false))
7444 return false;
7445
7446 IRBuilder<> Builder(Load->getNextNode());
7447 auto *NewAnd = cast<Instruction>(
7448 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
7449 // Mark this instruction as "inserted by CGP", so that other
7450 // optimizations don't touch it.
7451 InsertedInsts.insert(NewAnd);
7452
7453 // Replace all uses of load with new and (except for the use of load in the
7454 // new and itself).
7455 replaceAllUsesWith(Load, NewAnd, FreshBBs, IsHugeFunc);
7456 NewAnd->setOperand(0, Load);
7457
7458 // Remove any and instructions that are now redundant.
7459 for (auto *And : AndsToMaybeRemove)
7460 // Check that the and mask is the same as the one we decided to put on the
7461 // new and.
7462 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
7463 replaceAllUsesWith(And, NewAnd, FreshBBs, IsHugeFunc);
7464 if (&*CurInstIterator == And)
7465 CurInstIterator = std::next(And->getIterator());
7466 And->eraseFromParent();
7467 ++NumAndUses;
7468 }
7469
7470 // NSW flags may not longer hold.
7471 for (auto *Inst : DropFlags)
7472 Inst->setHasNoSignedWrap(false);
7473
7474 ++NumAndsAdded;
7475 return true;
7476}
7477
7478/// Check if V (an operand of a select instruction) is an expensive instruction
7479/// that is only used once.
7481 auto *I = dyn_cast<Instruction>(V);
7482 // If it's safe to speculatively execute, then it should not have side
7483 // effects; therefore, it's safe to sink and possibly *not* execute.
7484 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
7485 TTI->isExpensiveToSpeculativelyExecute(I);
7486}
7487
7488/// Returns true if a SelectInst should be turned into an explicit branch.
7490 const TargetLowering *TLI,
7491 SelectInst *SI) {
7492 // If even a predictable select is cheap, then a branch can't be cheaper.
7493 if (!TLI->isPredictableSelectExpensive())
7494 return false;
7495
7496 // FIXME: This should use the same heuristics as IfConversion to determine
7497 // whether a select is better represented as a branch.
7498
7499 // If metadata tells us that the select condition is obviously predictable,
7500 // then we want to replace the select with a branch.
7501 uint64_t TrueWeight, FalseWeight;
7502 if (extractBranchWeights(*SI, TrueWeight, FalseWeight)) {
7503 uint64_t Max = std::max(TrueWeight, FalseWeight);
7504 uint64_t Sum = TrueWeight + FalseWeight;
7505 if (Sum != 0) {
7506 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
7507 if (Probability > TTI->getPredictableBranchThreshold())
7508 return true;
7509 }
7510 }
7511
7512 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
7513
7514 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
7515 // comparison condition. If the compare has more than one use, there's
7516 // probably another cmov or setcc around, so it's not worth emitting a branch.
7517 if (!Cmp || !Cmp->hasOneUse())
7518 return false;
7519
7520 // If either operand of the select is expensive and only needed on one side
7521 // of the select, we should form a branch.
7522 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
7523 sinkSelectOperand(TTI, SI->getFalseValue()))
7524 return true;
7525
7526 return false;
7527}
7528
7529/// If \p isTrue is true, return the true value of \p SI, otherwise return
7530/// false value of \p SI. If the true/false value of \p SI is defined by any
7531/// select instructions in \p Selects, look through the defining select
7532/// instruction until the true/false value is not defined in \p Selects.
7533static Value *
7535 const SmallPtrSet<const Instruction *, 2> &Selects) {
7536 Value *V = nullptr;
7537
7538 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
7539 DefSI = dyn_cast<SelectInst>(V)) {
7540 assert(DefSI->getCondition() == SI->getCondition() &&
7541 "The condition of DefSI does not match with SI");
7542 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
7543 }
7544
7545 assert(V && "Failed to get select true/false value");
7546 return V;
7547}
7548
7549bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
7550 assert(Shift->isShift() && "Expected a shift");
7551
7552 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
7553 // general vector shifts, and (3) the shift amount is a select-of-splatted
7554 // values, hoist the shifts before the select:
7555 // shift Op0, (select Cond, TVal, FVal) -->
7556 // select Cond, (shift Op0, TVal), (shift Op0, FVal)
7557 //
7558 // This is inverting a generic IR transform when we know that the cost of a
7559 // general vector shift is more than the cost of 2 shift-by-scalars.
7560 // We can't do this effectively in SDAG because we may not be able to
7561 // determine if the select operands are splats from within a basic block.
7562 Type *Ty = Shift->getType();
7563 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7564 return false;
7565 Value *Cond, *TVal, *FVal;
7566 if (!match(Shift->getOperand(1),
7567 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7568 return false;
7569 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7570 return false;
7571
7572 IRBuilder<> Builder(Shift);
7573 BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
7574 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
7575 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
7576 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7577 replaceAllUsesWith(Shift, NewSel, FreshBBs, IsHugeFunc);
7578 Shift->eraseFromParent();
7579 return true;
7580}
7581
7582bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
7583 Intrinsic::ID Opcode = Fsh->getIntrinsicID();
7584 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
7585 "Expected a funnel shift");
7586
7587 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
7588 // than general vector shifts, and (3) the shift amount is select-of-splatted
7589 // values, hoist the funnel shifts before the select:
7590 // fsh Op0, Op1, (select Cond, TVal, FVal) -->
7591 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
7592 //
7593 // This is inverting a generic IR transform when we know that the cost of a
7594 // general vector shift is more than the cost of 2 shift-by-scalars.
7595 // We can't do this effectively in SDAG because we may not be able to
7596 // determine if the select operands are splats from within a basic block.
7597 Type *Ty = Fsh->getType();
7598 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7599 return false;
7600 Value *Cond, *TVal, *FVal;
7601 if (!match(Fsh->getOperand(2),
7602 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7603 return false;
7604 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7605 return false;
7606
7607 IRBuilder<> Builder(Fsh);
7608 Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1);
7609 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, TVal});
7610 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, FVal});
7611 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7612 replaceAllUsesWith(Fsh, NewSel, FreshBBs, IsHugeFunc);
7613 Fsh->eraseFromParent();
7614 return true;
7615}
7616
7617/// If we have a SelectInst that will likely profit from branch prediction,
7618/// turn it into a branch.
7619bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
7620 if (!Opts.cgp_select2branch)
7621 return false;
7622
7623 // If the SelectOptimize pass is enabled, selects have already been optimized.
7624 if (!Opts.disable_select_optimize)
7625 return false;
7626
7627 // Find all consecutive select instructions that share the same condition.
7629 ASI.push_back(SI);
7631 It != SI->getParent()->end(); ++It) {
7632 SelectInst *I = dyn_cast<SelectInst>(&*It);
7633 if (I && SI->getCondition() == I->getCondition()) {
7634 ASI.push_back(I);
7635 } else {
7636 break;
7637 }
7638 }
7639
7640 SelectInst *LastSI = ASI.back();
7641 // Increment the current iterator to skip all the rest of select instructions
7642 // because they will be either "not lowered" or "all lowered" to branch.
7643 CurInstIterator = std::next(LastSI->getIterator());
7644 // Examine debug-info attached to the consecutive select instructions. They
7645 // won't be individually optimised by optimizeInst, so we need to perform
7646 // DbgVariableRecord maintenence here instead.
7647 for (SelectInst *SI : ArrayRef(ASI).drop_front())
7648 fixupDbgVariableRecordsOnInst(*SI);
7649
7650 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
7651
7652 // Can we convert the 'select' to CF ?
7653 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
7654 return false;
7655
7656 TargetLowering::SelectSupportKind SelectKind;
7657 if (SI->getType()->isVectorTy())
7658 SelectKind = TargetLowering::ScalarCondVectorVal;
7659 else
7660 SelectKind = TargetLowering::ScalarValSelect;
7661
7662 if (TLI->isSelectSupported(SelectKind) &&
7664 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI)))
7665 return false;
7666
7667 // Transform a sequence like this:
7668 // start:
7669 // %cmp = cmp uge i32 %a, %b
7670 // %sel = select i1 %cmp, i32 %c, i32 %d
7671 //
7672 // Into:
7673 // start:
7674 // %cmp = cmp uge i32 %a, %b
7675 // %cmp.frozen = freeze %cmp
7676 // br i1 %cmp.frozen, label %select.true, label %select.false
7677 // select.true:
7678 // br label %select.end
7679 // select.false:
7680 // br label %select.end
7681 // select.end:
7682 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
7683 //
7684 // %cmp should be frozen, otherwise it may introduce undefined behavior.
7685 // In addition, we may sink instructions that produce %c or %d from
7686 // the entry block into the destination(s) of the new branch.
7687 // If the true or false blocks do not contain a sunken instruction, that
7688 // block and its branch may be optimized away. In that case, one side of the
7689 // first branch will point directly to select.end, and the corresponding PHI
7690 // predecessor block will be the start block.
7691 // The CFG is altered here and we update the DominatorTree and the LoopInfo,
7692 // but we don't set a ModifiedDT flag to avoid restarting the function walk in
7693 // runOnFunction for each select optimized.
7694
7695 // Collect values that go on the true side and the values that go on the false
7696 // side.
7697 SmallVector<Instruction *> TrueInstrs, FalseInstrs;
7698 for (SelectInst *SI : ASI) {
7699 if (Value *V = SI->getTrueValue(); sinkSelectOperand(TTI, V))
7700 TrueInstrs.push_back(cast<Instruction>(V));
7701 if (Value *V = SI->getFalseValue(); sinkSelectOperand(TTI, V))
7702 FalseInstrs.push_back(cast<Instruction>(V));
7703 }
7704
7705 // Split the select block, according to how many (if any) values go on each
7706 // side.
7707 BasicBlock *StartBlock = SI->getParent();
7708 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(LastSI));
7709 // We should split before any debug-info.
7710 SplitPt.setHeadBit(true);
7711
7712 IRBuilder<> IB(SI);
7713 auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen");
7714
7715 BasicBlock *TrueBlock = nullptr;
7716 BasicBlock *FalseBlock = nullptr;
7717 BasicBlock *EndBlock = nullptr;
7718 UncondBrInst *TrueBranch = nullptr;
7719 UncondBrInst *FalseBranch = nullptr;
7720 if (TrueInstrs.size() == 0) {
7721 FalseBranch = cast<UncondBrInst>(
7722 SplitBlockAndInsertIfElse(CondFr, SplitPt, false, nullptr, DTU, LI));
7723 FalseBlock = FalseBranch->getParent();
7724 EndBlock = cast<BasicBlock>(FalseBranch->getOperand(0));
7725 } else if (FalseInstrs.size() == 0) {
7726 TrueBranch = cast<UncondBrInst>(
7727 SplitBlockAndInsertIfThen(CondFr, SplitPt, false, nullptr, DTU, LI));
7728 TrueBlock = TrueBranch->getParent();
7729 EndBlock = TrueBranch->getSuccessor();
7730 } else {
7731 Instruction *ThenTerm = nullptr;
7732 Instruction *ElseTerm = nullptr;
7733 SplitBlockAndInsertIfThenElse(CondFr, SplitPt, &ThenTerm, &ElseTerm,
7734 nullptr, DTU, LI);
7735 TrueBranch = cast<UncondBrInst>(ThenTerm);
7736 FalseBranch = cast<UncondBrInst>(ElseTerm);
7737 TrueBlock = TrueBranch->getParent();
7738 FalseBlock = FalseBranch->getParent();
7739 EndBlock = TrueBranch->getSuccessor();
7740 }
7741
7742 EndBlock->setName("select.end");
7743 if (TrueBlock)
7744 TrueBlock->setName("select.true.sink");
7745 if (FalseBlock)
7746 FalseBlock->setName(FalseInstrs.size() == 0 ? "select.false"
7747 : "select.false.sink");
7748
7749 if (IsHugeFunc) {
7750 if (TrueBlock)
7751 FreshBBs.insert(TrueBlock);
7752 if (FalseBlock)
7753 FreshBBs.insert(FalseBlock);
7754 FreshBBs.insert(EndBlock);
7755 }
7756
7757 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
7758
7759 static const unsigned MD[] = {
7760 LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
7761 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
7762 StartBlock->getTerminator()->copyMetadata(*SI, MD);
7763
7764 // Sink expensive instructions into the conditional blocks to avoid executing
7765 // them speculatively.
7766 for (Instruction *I : TrueInstrs)
7767 I->moveBefore(TrueBranch->getIterator());
7768 for (Instruction *I : FalseInstrs)
7769 I->moveBefore(FalseBranch->getIterator());
7770
7771 // If we did not create a new block for one of the 'true' or 'false' paths
7772 // of the condition, it means that side of the branch goes to the end block
7773 // directly and the path originates from the start block from the point of
7774 // view of the new PHI.
7775 if (TrueBlock == nullptr)
7776 TrueBlock = StartBlock;
7777 else if (FalseBlock == nullptr)
7778 FalseBlock = StartBlock;
7779
7780 SmallPtrSet<const Instruction *, 2> INS(llvm::from_range, ASI);
7781 // Use reverse iterator because later select may use the value of the
7782 // earlier select, and we need to propagate value through earlier select
7783 // to get the PHI operand.
7784 for (SelectInst *SI : llvm::reverse(ASI)) {
7785 // The select itself is replaced with a PHI Node.
7786 PHINode *PN = PHINode::Create(SI->getType(), 2, "");
7787 PN->insertBefore(EndBlock->begin());
7788 PN->takeName(SI);
7789 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
7790 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
7791 PN->setDebugLoc(SI->getDebugLoc());
7792
7793 replaceAllUsesWith(SI, PN, FreshBBs, IsHugeFunc);
7794 SI->eraseFromParent();
7795 INS.erase(SI);
7796 ++NumSelectsExpanded;
7797 }
7798
7799 // Instruct OptimizeBlock to skip to the next block.
7800 CurInstIterator = StartBlock->end();
7801 return true;
7802}
7803
7804/// Some targets only accept certain types for splat inputs. For example a VDUP
7805/// in MVE takes a GPR (integer) register, and the instruction that incorporate
7806/// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
7807bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
7808 // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
7810 m_Undef(), m_ZeroMask())))
7811 return false;
7812 Type *NewType = TLI->shouldConvertSplatType(SVI);
7813 if (!NewType)
7814 return false;
7815
7816 auto *SVIVecType = cast<FixedVectorType>(SVI->getType());
7817 assert(!NewType->isVectorTy() && "Expected a scalar type!");
7818 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&
7819 "Expected a type of the same size!");
7820 auto *NewVecType =
7821 FixedVectorType::get(NewType, SVIVecType->getNumElements());
7822
7823 // Create a bitcast (shuffle (insert (bitcast(..))))
7824 IRBuilder<> Builder(SVI);
7825 Value *BC1 = Builder.CreateBitCast(
7826 cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType);
7827 Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1);
7828 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType);
7829
7830 replaceAllUsesWith(SVI, BC2, FreshBBs, IsHugeFunc);
7832 SVI, TLInfo, nullptr,
7833 [&](Value *V) { removeAllAssertingVHReferences(V); });
7834
7835 // Also hoist the bitcast up to its operand if it they are not in the same
7836 // block.
7837 if (auto *BCI = dyn_cast<Instruction>(BC1))
7838 if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0)))
7839 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) &&
7840 !Op->isTerminator() && !Op->isEHPad())
7841 BCI->moveAfter(Op);
7842
7843 return true;
7844}
7845
7846bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
7847 // If the operands of I can be folded into a target instruction together with
7848 // I, duplicate and sink them.
7849 SmallVector<Use *, 4> OpsToSink;
7850 if (!TTI->isProfitableToSinkOperands(I, OpsToSink))
7851 return false;
7852
7853 // OpsToSink can contain multiple uses in a use chain (e.g.
7854 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
7855 // uses must come first, so we process the ops in reverse order so as to not
7856 // create invalid IR.
7857 BasicBlock *TargetBB = I->getParent();
7858 bool Changed = false;
7859 SmallVector<Use *, 4> ToReplace;
7860 Instruction *InsertPoint = I;
7861 for (Use *U : reverse(OpsToSink)) {
7862 auto *UI = cast<Instruction>(U->get());
7863 if (isa<PHINode>(UI) || UI->mayHaveSideEffects() || UI->mayReadFromMemory())
7864 continue;
7865 if (UI->getParent() == TargetBB) {
7866 if (UI->comesBefore(InsertPoint))
7867 InsertPoint = UI;
7868 continue;
7869 }
7870 ToReplace.push_back(U);
7871 }
7872
7873 SetVector<Instruction *> MaybeDead;
7874 DenseMap<Instruction *, Instruction *> NewInstructions;
7875 for (Use *U : ToReplace) {
7876 auto *UI = cast<Instruction>(U->get());
7877 Instruction *NI = UI->clone();
7878
7879 if (IsHugeFunc) {
7880 // Now we clone an instruction, its operands' defs may sink to this BB
7881 // now. So we put the operands defs' BBs into FreshBBs to do optimization.
7882 for (Value *Op : NI->operands())
7883 if (auto *OpDef = dyn_cast<Instruction>(Op))
7884 FreshBBs.insert(OpDef->getParent());
7885 }
7886
7887 NewInstructions[UI] = NI;
7888 MaybeDead.insert(UI);
7889 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
7890 NI->insertBefore(InsertPoint->getIterator());
7891 InsertPoint = NI;
7892 InsertedInsts.insert(NI);
7893
7894 // Update the use for the new instruction, making sure that we update the
7895 // sunk instruction uses, if it is part of a chain that has already been
7896 // sunk.
7897 Instruction *OldI = cast<Instruction>(U->getUser());
7898 if (auto It = NewInstructions.find(OldI); It != NewInstructions.end())
7899 It->second->setOperand(U->getOperandNo(), NI);
7900 else
7901 U->set(NI);
7902 Changed = true;
7903 }
7904
7905 // Remove instructions that are dead after sinking.
7906 for (auto *I : MaybeDead) {
7907 if (!I->hasNUsesOrMore(1)) {
7908 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
7909 I->eraseFromParent();
7910 }
7911 }
7912
7913 return Changed;
7914}
7915
7916bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
7917 Value *Cond = SI->getCondition();
7918 Type *OldType = Cond->getType();
7919 LLVMContext &Context = Cond->getContext();
7920 EVT OldVT = TLI->getValueType(*DL, OldType);
7922 unsigned RegWidth = RegType.getSizeInBits();
7923
7924 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
7925 return false;
7926
7927 // If the register width is greater than the type width, expand the condition
7928 // of the switch instruction and each case constant to the width of the
7929 // register. By widening the type of the switch condition, subsequent
7930 // comparisons (for case comparisons) will not need to be extended to the
7931 // preferred register width, so we will potentially eliminate N-1 extends,
7932 // where N is the number of cases in the switch.
7933 auto *NewType = Type::getIntNTy(Context, RegWidth);
7934
7935 // Extend the switch condition and case constants using the target preferred
7936 // extend unless the switch condition is a function argument with an extend
7937 // attribute. In that case, we can avoid an unnecessary mask/extension by
7938 // matching the argument extension instead.
7939 Instruction::CastOps ExtType = Instruction::ZExt;
7940 // Some targets prefer SExt over ZExt.
7941 if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
7942 ExtType = Instruction::SExt;
7943
7944 if (auto *Arg = dyn_cast<Argument>(Cond)) {
7945 if (Arg->hasSExtAttr())
7946 ExtType = Instruction::SExt;
7947 if (Arg->hasZExtAttr())
7948 ExtType = Instruction::ZExt;
7949 }
7950
7951 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
7952 ExtInst->insertBefore(SI->getIterator());
7953 ExtInst->setDebugLoc(SI->getDebugLoc());
7954 SI->setCondition(ExtInst);
7955 for (auto Case : SI->cases()) {
7956 const APInt &NarrowConst = Case.getCaseValue()->getValue();
7957 APInt WideConst = (ExtType == Instruction::ZExt)
7958 ? NarrowConst.zext(RegWidth)
7959 : NarrowConst.sext(RegWidth);
7960 Case.setValue(ConstantInt::get(Context, WideConst));
7961 }
7962
7963 return true;
7964}
7965
7966bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
7967 // The SCCP optimization tends to produce code like this:
7968 // switch(x) { case 42: phi(42, ...) }
7969 // Materializing the constant for the phi-argument needs instructions; So we
7970 // change the code to:
7971 // switch(x) { case 42: phi(x, ...) }
7972
7973 Value *Condition = SI->getCondition();
7974 // Avoid endless loop in degenerate case.
7975 if (isa<ConstantInt>(*Condition))
7976 return false;
7977
7978 bool Changed = false;
7979 BasicBlock *SwitchBB = SI->getParent();
7980 Type *ConditionType = Condition->getType();
7981
7982 for (const SwitchInst::CaseHandle &Case : SI->cases()) {
7983 ConstantInt *CaseValue = Case.getCaseValue();
7984 BasicBlock *CaseBB = Case.getCaseSuccessor();
7985 // Set to true if we previously checked that `CaseBB` is only reached by
7986 // a single case from this switch.
7987 bool CheckedForSinglePred = false;
7988 for (PHINode &PHI : CaseBB->phis()) {
7989 Type *PHIType = PHI.getType();
7990 // If ZExt is free then we can also catch patterns like this:
7991 // switch((i32)x) { case 42: phi((i64)42, ...); }
7992 // and replace `(i64)42` with `zext i32 %x to i64`.
7993 bool TryZExt =
7994 PHIType->isIntegerTy() &&
7995 PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
7996 TLI->isZExtFree(ConditionType, PHIType);
7997 if (PHIType == ConditionType || TryZExt) {
7998 // Set to true to skip this case because of multiple preds.
7999 bool SkipCase = false;
8000 Value *Replacement = nullptr;
8001 for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
8002 Value *PHIValue = PHI.getIncomingValue(I);
8003 if (PHIValue != CaseValue) {
8004 if (!TryZExt)
8005 continue;
8006 ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(PHIValue);
8007 if (!PHIValueInt ||
8008 PHIValueInt->getValue() !=
8009 CaseValue->getValue().zext(PHIType->getIntegerBitWidth()))
8010 continue;
8011 }
8012 if (PHI.getIncomingBlock(I) != SwitchBB)
8013 continue;
8014 // We cannot optimize if there are multiple case labels jumping to
8015 // this block. This check may get expensive when there are many
8016 // case labels so we test for it last.
8017 if (!CheckedForSinglePred) {
8018 CheckedForSinglePred = true;
8019 if (SI->findCaseDest(CaseBB) == nullptr) {
8020 SkipCase = true;
8021 break;
8022 }
8023 }
8024
8025 if (Replacement == nullptr) {
8026 if (PHIValue == CaseValue) {
8027 Replacement = Condition;
8028 } else {
8029 IRBuilder<> Builder(SI);
8030 Replacement = Builder.CreateZExt(Condition, PHIType);
8031 }
8032 }
8033 PHI.setIncomingValue(I, Replacement);
8034 Changed = true;
8035 }
8036 if (SkipCase)
8037 break;
8038 }
8039 }
8040 }
8041 return Changed;
8042}
8043
8044bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
8045 bool Changed = optimizeSwitchType(SI);
8046 Changed |= optimizeSwitchPhiConstants(SI);
8047 return Changed;
8048}
8049
8050namespace {
8051
8052/// Helper class to promote a scalar operation to a vector one.
8053/// This class is used to move downward extractelement transition.
8054/// E.g.,
8055/// a = vector_op <2 x i32>
8056/// b = extractelement <2 x i32> a, i32 0
8057/// c = scalar_op b
8058/// store c
8059///
8060/// =>
8061/// a = vector_op <2 x i32>
8062/// c = vector_op a (equivalent to scalar_op on the related lane)
8063/// * d = extractelement <2 x i32> c, i32 0
8064/// * store d
8065/// Assuming both extractelement and store can be combine, we get rid of the
8066/// transition.
8067class VectorPromoteHelper {
8068 /// DataLayout associated with the current module.
8069 const DataLayout &DL;
8070
8071 /// Used to perform some checks on the legality of vector operations.
8072 const TargetLowering &TLI;
8073
8074 /// Used to estimated the cost of the promoted chain.
8075 const TargetTransformInfo &TTI;
8076
8077 /// The transition being moved downwards.
8078 Instruction *Transition;
8079
8080 /// The sequence of instructions to be promoted.
8081 SmallVector<Instruction *, 4> InstsToBePromoted;
8082
8083 /// Cost of combining a store and an extract.
8084 unsigned StoreExtractCombineCost;
8085
8086 bool StressStoreExtract;
8087
8088 /// Instruction that will be combined with the transition.
8089 Instruction *CombineInst = nullptr;
8090
8091 /// The instruction that represents the current end of the transition.
8092 /// Since we are faking the promotion until we reach the end of the chain
8093 /// of computation, we need a way to get the current end of the transition.
8094 Instruction *getEndOfTransition() const {
8095 if (InstsToBePromoted.empty())
8096 return Transition;
8097 return InstsToBePromoted.back();
8098 }
8099
8100 /// Return the index of the original value in the transition.
8101 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
8102 /// c, is at index 0.
8103 unsigned getTransitionOriginalValueIdx() const {
8104 assert(isa<ExtractElementInst>(Transition) &&
8105 "Other kind of transitions are not supported yet");
8106 return 0;
8107 }
8108
8109 /// Return the index of the index in the transition.
8110 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
8111 /// is at index 1.
8112 unsigned getTransitionIdx() const {
8113 assert(isa<ExtractElementInst>(Transition) &&
8114 "Other kind of transitions are not supported yet");
8115 return 1;
8116 }
8117
8118 /// Get the type of the transition.
8119 /// This is the type of the original value.
8120 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
8121 /// transition is <2 x i32>.
8122 Type *getTransitionType() const {
8123 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
8124 }
8125
8126 /// Promote \p ToBePromoted by moving \p Def downward through.
8127 /// I.e., we have the following sequence:
8128 /// Def = Transition <ty1> a to <ty2>
8129 /// b = ToBePromoted <ty2> Def, ...
8130 /// =>
8131 /// b = ToBePromoted <ty1> a, ...
8132 /// Def = Transition <ty1> ToBePromoted to <ty2>
8133 void promoteImpl(Instruction *ToBePromoted);
8134
8135 /// Check whether or not it is profitable to promote all the
8136 /// instructions enqueued to be promoted.
8137 bool isProfitableToPromote() {
8138 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
8139 unsigned Index = isa<ConstantInt>(ValIdx)
8140 ? cast<ConstantInt>(ValIdx)->getZExtValue()
8141 : -1;
8142 Type *PromotedType = getTransitionType();
8143
8144 StoreInst *ST = cast<StoreInst>(CombineInst);
8145 unsigned AS = ST->getPointerAddressSpace();
8146 // Check if this store is supported.
8148 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
8149 ST->getAlign())) {
8150 // If this is not supported, there is no way we can combine
8151 // the extract with the store.
8152 return false;
8153 }
8154
8155 // The scalar chain of computation has to pay for the transition
8156 // scalar to vector.
8157 // The vector chain has to account for the combining cost.
8160 InstructionCost ScalarCost =
8161 TTI.getVectorInstrCost(*Transition, PromotedType, CostKind, Index);
8162 InstructionCost VectorCost = StoreExtractCombineCost;
8163 for (const auto &Inst : InstsToBePromoted) {
8164 // Compute the cost.
8165 // By construction, all instructions being promoted are arithmetic ones.
8166 // Moreover, one argument is a constant that can be viewed as a splat
8167 // constant.
8168 Value *Arg0 = Inst->getOperand(0);
8169 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
8170 isa<ConstantFP>(Arg0);
8171 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
8172 if (IsArg0Constant)
8174 else
8176
8177 ScalarCost += TTI.getArithmeticInstrCost(
8178 Inst->getOpcode(), Inst->getType(), CostKind, Arg0Info, Arg1Info);
8179 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
8180 CostKind, Arg0Info, Arg1Info);
8181 }
8182 LLVM_DEBUG(
8183 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
8184 << ScalarCost << "\nVector: " << VectorCost << '\n');
8185 return ScalarCost > VectorCost;
8186 }
8187
8188 /// Generate a constant vector with \p Val with the same
8189 /// number of elements as the transition.
8190 /// \p UseSplat defines whether or not \p Val should be replicated
8191 /// across the whole vector.
8192 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
8193 /// otherwise we generate a vector with as many poison as possible:
8194 /// <poison, ..., poison, Val, poison, ..., poison> where \p Val is only
8195 /// used at the index of the extract.
8196 Value *getConstantVector(Constant *Val, bool UseSplat) const {
8197 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
8198 if (!UseSplat) {
8199 // If we cannot determine where the constant must be, we have to
8200 // use a splat constant.
8201 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
8202 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
8203 ExtractIdx = CstVal->getSExtValue();
8204 else
8205 UseSplat = true;
8206 }
8207
8208 ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount();
8209 if (UseSplat)
8210 return ConstantVector::getSplat(EC, Val);
8211
8212 if (!EC.isScalable()) {
8213 SmallVector<Constant *, 4> ConstVec;
8214 PoisonValue *PoisonVal = PoisonValue::get(Val->getType());
8215 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
8216 if (Idx == ExtractIdx)
8217 ConstVec.push_back(Val);
8218 else
8219 ConstVec.push_back(PoisonVal);
8220 }
8221 return ConstantVector::get(ConstVec);
8222 } else
8224 "Generate scalable vector for non-splat is unimplemented");
8225 }
8226
8227 /// Check if promoting to a vector type an operand at \p OperandIdx
8228 /// in \p Use can trigger undefined behavior.
8229 static bool canCauseUndefinedBehavior(const Instruction *Use,
8230 unsigned OperandIdx) {
8231 // This is not safe to introduce undef when the operand is on
8232 // the right hand side of a division-like instruction.
8233 if (OperandIdx != 1)
8234 return false;
8235 switch (Use->getOpcode()) {
8236 default:
8237 return false;
8238 case Instruction::SDiv:
8239 case Instruction::UDiv:
8240 case Instruction::SRem:
8241 case Instruction::URem:
8242 return true;
8243 case Instruction::FDiv:
8244 case Instruction::FRem:
8245 return !Use->hasNoNaNs();
8246 }
8247 llvm_unreachable(nullptr);
8248 }
8249
8250public:
8251 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
8252 const TargetTransformInfo &TTI, Instruction *Transition,
8253 unsigned CombineCost, bool StressStoreExtract)
8254 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
8255 StoreExtractCombineCost(CombineCost),
8256 StressStoreExtract(StressStoreExtract) {
8257 assert(Transition && "Do not know how to promote null");
8258 }
8259
8260 /// Check if we can promote \p ToBePromoted to \p Type.
8261 bool canPromote(const Instruction *ToBePromoted) const {
8262 // We could support CastInst too.
8263 return isa<BinaryOperator>(ToBePromoted);
8264 }
8265
8266 /// Check if it is profitable to promote \p ToBePromoted
8267 /// by moving downward the transition through.
8268 bool shouldPromote(const Instruction *ToBePromoted) const {
8270 return false;
8271 // Promote only if all the operands can be statically expanded.
8272 // Indeed, we do not want to introduce any new kind of transitions.
8273 for (const Use &U : ToBePromoted->operands()) {
8274 const Value *Val = U.get();
8275 if (Val == getEndOfTransition()) {
8276 continue;
8277 }
8278 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
8279 !isa<ConstantFP>(Val))
8280 return false;
8281 }
8282 // Check that the resulting operation is legal.
8283 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
8284 if (!ISDOpcode)
8285 return false;
8286 return StressStoreExtract ||
8288 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
8289 }
8290
8291 /// Check whether or not \p Use can be combined
8292 /// with the transition.
8293 /// I.e., is it possible to do Use(Transition) => AnotherUse?
8294 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
8295
8296 /// Record \p ToBePromoted as part of the chain to be promoted.
8297 void enqueueForPromotion(Instruction *ToBePromoted) {
8298 InstsToBePromoted.push_back(ToBePromoted);
8299 }
8300
8301 /// Set the instruction that will be combined with the transition.
8302 void recordCombineInstruction(Instruction *ToBeCombined) {
8303 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
8304 CombineInst = ToBeCombined;
8305 }
8306
8307 /// Promote all the instructions enqueued for promotion if it is
8308 /// is profitable.
8309 /// \return True if the promotion happened, false otherwise.
8310 bool promote() {
8311 // Check if there is something to promote.
8312 // Right now, if we do not have anything to combine with,
8313 // we assume the promotion is not profitable.
8314 if (InstsToBePromoted.empty() || !CombineInst)
8315 return false;
8316
8317 // Check cost.
8318 if (!StressStoreExtract && !isProfitableToPromote())
8319 return false;
8320
8321 // Promote.
8322 for (auto &ToBePromoted : InstsToBePromoted)
8323 promoteImpl(ToBePromoted);
8324 InstsToBePromoted.clear();
8325 return true;
8326 }
8327};
8328
8329} // end anonymous namespace
8330
8331void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
8332 // At this point, we know that all the operands of ToBePromoted but Def
8333 // can be statically promoted.
8334 // For Def, we need to use its parameter in ToBePromoted:
8335 // b = ToBePromoted ty1 a
8336 // Def = Transition ty1 b to ty2
8337 // Move the transition down.
8338 // 1. Replace all uses of the promoted operation by the transition.
8339 // = ... b => = ... Def.
8340 assert(ToBePromoted->getType() == Transition->getType() &&
8341 "The type of the result of the transition does not match "
8342 "the final type");
8343 ToBePromoted->replaceAllUsesWith(Transition);
8344 // 2. Update the type of the uses.
8345 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
8346 Type *TransitionTy = getTransitionType();
8347 ToBePromoted->mutateType(TransitionTy);
8348 // 3. Update all the operands of the promoted operation with promoted
8349 // operands.
8350 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
8351 for (Use &U : ToBePromoted->operands()) {
8352 Value *Val = U.get();
8353 Value *NewVal = nullptr;
8354 if (Val == Transition)
8355 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
8356 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
8357 isa<ConstantFP>(Val)) {
8358 // Use a splat constant if it is not safe to use undef.
8359 NewVal = getConstantVector(
8360 cast<Constant>(Val),
8361 isa<UndefValue>(Val) ||
8362 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
8363 } else
8364 llvm_unreachable("Did you modified shouldPromote and forgot to update "
8365 "this?");
8366 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
8367 }
8368 Transition->moveAfter(ToBePromoted);
8369 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
8370}
8371
8372/// Some targets can do store(extractelement) with one instruction.
8373/// Try to push the extractelement towards the stores when the target
8374/// has this feature and this is profitable.
8375bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
8376 unsigned CombineCost = std::numeric_limits<unsigned>::max();
8377 if (!Opts.cgp_store_extract ||
8378 (!Opts.cgp_stress_store_extract &&
8380 Inst->getOperand(1), CombineCost)))
8381 return false;
8382
8383 // At this point we know that Inst is a vector to scalar transition.
8384 // Try to move it down the def-use chain, until:
8385 // - We can combine the transition with its single use
8386 // => we got rid of the transition.
8387 // - We escape the current basic block
8388 // => we would need to check that we are moving it at a cheaper place and
8389 // we do not do that for now.
8390 BasicBlock *Parent = Inst->getParent();
8391 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
8392 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost,
8393 Opts.cgp_stress_store_extract);
8394 // If the transition has more than one use, assume this is not going to be
8395 // beneficial.
8396 while (Inst->hasOneUse()) {
8397 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
8398 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
8399
8400 if (ToBePromoted->getParent() != Parent) {
8401 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
8402 << ToBePromoted->getParent()->getName()
8403 << ") than the transition (" << Parent->getName()
8404 << ").\n");
8405 return false;
8406 }
8407
8408 if (VPH.canCombine(ToBePromoted)) {
8409 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
8410 << "will be combined with: " << *ToBePromoted << '\n');
8411 VPH.recordCombineInstruction(ToBePromoted);
8412 bool Changed = VPH.promote();
8413 NumStoreExtractExposed += Changed;
8414 return Changed;
8415 }
8416
8417 LLVM_DEBUG(dbgs() << "Try promoting.\n");
8418 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
8419 return false;
8420
8421 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
8422
8423 VPH.enqueueForPromotion(ToBePromoted);
8424 Inst = ToBePromoted;
8425 }
8426 return false;
8427}
8428
8429/// For the instruction sequence of store below, F and I values
8430/// are bundled together as an i64 value before being stored into memory.
8431/// Sometimes it is more efficient to generate separate stores for F and I,
8432/// which can remove the bitwise instructions or sink them to colder places.
8433///
8434/// (store (or (zext (bitcast F to i32) to i64),
8435/// (shl (zext I to i64), 32)), addr) -->
8436/// (store F, addr) and (store I, addr+4)
8437///
8438/// Similarly, splitting for other merged store can also be beneficial, like:
8439/// For pair of {i32, i32}, i64 store --> two i32 stores.
8440/// For pair of {i32, i16}, i64 store --> two i32 stores.
8441/// For pair of {i16, i16}, i32 store --> two i16 stores.
8442/// For pair of {i16, i8}, i32 store --> two i16 stores.
8443/// For pair of {i8, i8}, i16 store --> two i8 stores.
8444///
8445/// We allow each target to determine specifically which kind of splitting is
8446/// supported.
8447///
8448/// The store patterns are commonly seen from the simple code snippet below
8449/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
8450/// void goo(const std::pair<int, float> &);
8451/// hoo() {
8452/// ...
8453/// goo(std::make_pair(tmp, ftmp));
8454/// ...
8455/// }
8456///
8457/// Although we already have similar splitting in DAG Combine, we duplicate
8458/// it in CodeGenPrepare to catch the case in which pattern is across
8459/// multiple BBs. The logic in DAG Combine is kept to catch case generated
8460/// during code expansion.
8462 const TargetLowering &TLI,
8463 bool ForceSplitStore) {
8464 // Handle simple but common cases only.
8465 Type *StoreType = SI.getValueOperand()->getType();
8466
8467 // The code below assumes shifting a value by <number of bits>,
8468 // whereas scalable vectors would have to be shifted by
8469 // <2log(vscale) + number of bits> in order to store the
8470 // low/high parts. Bailing out for now.
8471 if (StoreType->isScalableTy())
8472 return false;
8473
8474 if (!DL.typeSizeEqualsStoreSize(StoreType) ||
8475 DL.getTypeSizeInBits(StoreType) == 0)
8476 return false;
8477
8478 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
8479 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
8480 if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
8481 return false;
8482
8483 // Don't split the store if it is volatile or atomic.
8484 if (!SI.isSimple())
8485 return false;
8486
8487 // Match the following patterns:
8488 // (store (or (zext LValue to i64),
8489 // (shl (zext HValue to i64), 32)), HalfValBitSize)
8490 // or
8491 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
8492 // (zext LValue to i64),
8493 // Expect both operands of OR and the first operand of SHL have only
8494 // one use.
8495 Value *LValue, *HValue;
8496 if (!match(SI.getValueOperand(),
8499 m_SpecificInt(HalfValBitSize))))))
8500 return false;
8501
8502 // Check LValue and HValue are int with size less or equal than 32.
8503 if (!LValue->getType()->isIntegerTy() ||
8504 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
8505 !HValue->getType()->isIntegerTy() ||
8506 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
8507 return false;
8508
8509 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
8510 // as the input of target query.
8511 auto *LBC = dyn_cast<BitCastInst>(LValue);
8512 auto *HBC = dyn_cast<BitCastInst>(HValue);
8513 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
8514 : EVT::getEVT(LValue->getType());
8515 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
8516 : EVT::getEVT(HValue->getType());
8517 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
8518 return false;
8519
8520 // Start to split store.
8521 IRBuilder<> Builder(&SI);
8522
8523 // If LValue/HValue is a bitcast in another BB, create a new one in current
8524 // BB so it may be merged with the splitted stores by dag combiner.
8525 if (LBC && LBC->getParent() != SI.getParent())
8526 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
8527 if (HBC && HBC->getParent() != SI.getParent())
8528 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
8529
8530 bool IsLE = SI.getDataLayout().isLittleEndian();
8531 auto CreateSplitStore = [&](Value *V, bool Upper) {
8532 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
8533 Value *Addr = SI.getPointerOperand();
8534 Align Alignment = SI.getAlign();
8535 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
8536 if (IsOffsetStore) {
8537 Addr = Builder.CreateGEP(
8538 SplitStoreType, Addr,
8539 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
8540
8541 // When splitting the store in half, naturally one half will retain the
8542 // alignment of the original wider store, regardless of whether it was
8543 // over-aligned or not, while the other will require adjustment.
8544 Alignment = commonAlignment(Alignment, HalfValBitSize / 8);
8545 }
8546 Builder.CreateAlignedStore(V, Addr, Alignment);
8547 };
8548
8549 CreateSplitStore(LValue, false);
8550 CreateSplitStore(HValue, true);
8551
8552 // Delete the old store.
8553 SI.eraseFromParent();
8554 return true;
8555}
8556
8557// Return true if the GEP has two operands, the first operand is of a sequential
8558// type, and the second operand is a constant.
8561 return GEP->getNumOperands() == 2 && I.isSequential() &&
8562 isa<ConstantInt>(GEP->getOperand(1));
8563}
8564
8565// Try unmerging GEPs to reduce liveness interference (register pressure) across
8566// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
8567// reducing liveness interference across those edges benefits global register
8568// allocation. Currently handles only certain cases.
8569//
8570// For example, unmerge %GEPI and %UGEPI as below.
8571//
8572// ---------- BEFORE ----------
8573// SrcBlock:
8574// ...
8575// %GEPIOp = ...
8576// ...
8577// %GEPI = gep %GEPIOp, Idx
8578// ...
8579// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
8580// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
8581// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
8582// %UGEPI)
8583//
8584// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
8585// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
8586// ...
8587//
8588// DstBi:
8589// ...
8590// %UGEPI = gep %GEPIOp, UIdx
8591// ...
8592// ---------------------------
8593//
8594// ---------- AFTER ----------
8595// SrcBlock:
8596// ... (same as above)
8597// (* %GEPI is still alive on the indirectbr edges)
8598// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
8599// unmerging)
8600// ...
8601//
8602// DstBi:
8603// ...
8604// %UGEPI = gep %GEPI, (UIdx-Idx)
8605// ...
8606// ---------------------------
8607//
8608// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
8609// no longer alive on them.
8610//
8611// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
8612// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
8613// not to disable further simplications and optimizations as a result of GEP
8614// merging.
8615//
8616// Note this unmerging may increase the length of the data flow critical path
8617// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
8618// between the register pressure and the length of data-flow critical
8619// path. Restricting this to the uncommon IndirectBr case would minimize the
8620// impact of potentially longer critical path, if any, and the impact on compile
8621// time.
8623 const TargetTransformInfo *TTI) {
8624 BasicBlock *SrcBlock = GEPI->getParent();
8625 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
8626 // (non-IndirectBr) cases exit early here.
8627 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
8628 return false;
8629 // Check that GEPI is a simple gep with a single constant index.
8630 if (!GEPSequentialConstIndexed(GEPI))
8631 return false;
8632 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
8633 // Check that GEPI is a cheap one.
8634 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(),
8637 return false;
8638 Value *GEPIOp = GEPI->getOperand(0);
8639 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
8640 if (!isa<Instruction>(GEPIOp))
8641 return false;
8642 auto *GEPIOpI = cast<Instruction>(GEPIOp);
8643 if (GEPIOpI->getParent() != SrcBlock)
8644 return false;
8645 // Check that GEP is used outside the block, meaning it's alive on the
8646 // IndirectBr edge(s).
8647 if (llvm::none_of(GEPI->users(), [&](User *Usr) {
8648 if (auto *I = dyn_cast<Instruction>(Usr)) {
8649 if (I->getParent() != SrcBlock) {
8650 return true;
8651 }
8652 }
8653 return false;
8654 }))
8655 return false;
8656 // The second elements of the GEP chains to be unmerged.
8657 std::vector<GetElementPtrInst *> UGEPIs;
8658 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
8659 // on IndirectBr edges.
8660 for (User *Usr : GEPIOp->users()) {
8661 if (Usr == GEPI)
8662 continue;
8663 // Check if Usr is an Instruction. If not, give up.
8664 if (!isa<Instruction>(Usr))
8665 return false;
8666 auto *UI = cast<Instruction>(Usr);
8667 // Check if Usr in the same block as GEPIOp, which is fine, skip.
8668 if (UI->getParent() == SrcBlock)
8669 continue;
8670 // Check if Usr is a GEP. If not, give up.
8671 if (!isa<GetElementPtrInst>(Usr))
8672 return false;
8673 auto *UGEPI = cast<GetElementPtrInst>(Usr);
8674 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
8675 // the pointer operand to it. If so, record it in the vector. If not, give
8676 // up.
8677 if (!GEPSequentialConstIndexed(UGEPI))
8678 return false;
8679 if (UGEPI->getOperand(0) != GEPIOp)
8680 return false;
8681 if (UGEPI->getSourceElementType() != GEPI->getSourceElementType())
8682 return false;
8683 if (GEPIIdx->getType() !=
8684 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
8685 return false;
8686 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8687 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(),
8690 return false;
8691 UGEPIs.push_back(UGEPI);
8692 }
8693 if (UGEPIs.size() == 0)
8694 return false;
8695 // Check the materializing cost of (Uidx-Idx).
8696 for (GetElementPtrInst *UGEPI : UGEPIs) {
8697 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8698 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8700 NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency);
8701 if (ImmCost > TargetTransformInfo::TCC_Basic)
8702 return false;
8703 }
8704 // Now unmerge between GEPI and UGEPIs.
8705 for (GetElementPtrInst *UGEPI : UGEPIs) {
8706 UGEPI->setOperand(0, GEPI);
8707 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8708 auto NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8709 Constant *NewUGEPIIdx = ConstantInt::get(GEPIIdx->getType(), NewIdx);
8710 UGEPI->setOperand(1, NewUGEPIIdx);
8711
8712 auto SourceFlags = GEPI->getNoWrapFlags();
8713 // Intersect flags to avoid UB in updated GEP.
8714 auto TargetFlags =
8715 UGEPI->getNoWrapFlags().intersectForOffsetAdd(SourceFlags);
8716 // If UGEPI now has a negative index, drop the nuw flag.
8717 if (NewIdx.isNegative() && TargetFlags.hasNoUnsignedWrap())
8718 TargetFlags = TargetFlags.withoutNoUnsignedWrap();
8719 UGEPI->setNoWrapFlags(TargetFlags);
8720 }
8721 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
8722 // alive on IndirectBr edges).
8723 assert(llvm::none_of(GEPIOp->users(),
8724 [&](User *Usr) {
8725 return cast<Instruction>(Usr)->getParent() != SrcBlock;
8726 }) &&
8727 "GEPIOp is used outside SrcBlock");
8728 return true;
8729}
8730
8731static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI,
8733 bool IsHugeFunc) {
8734 // Try and convert
8735 // %c = icmp ult %x, 8
8736 // br %c, bla, blb
8737 // %tc = lshr %x, 3
8738 // to
8739 // %tc = lshr %x, 3
8740 // %c = icmp eq %tc, 0
8741 // br %c, bla, blb
8742 // Creating the cmp to zero can be better for the backend, especially if the
8743 // lshr produces flags that can be used automatically.
8744 if (!TLI.preferZeroCompareBranch())
8745 return false;
8746
8747 ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition());
8748 if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse())
8749 return false;
8750
8751 Value *X = Cmp->getOperand(0);
8752 if (!X->hasUseList())
8753 return false;
8754
8755 APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue();
8756
8757 for (auto *U : X->users()) {
8759 // A quick dominance check
8760 if (!UI ||
8761 (UI->getParent() != Branch->getParent() &&
8762 UI->getParent() != Branch->getSuccessor(0) &&
8763 UI->getParent() != Branch->getSuccessor(1)) ||
8764 (UI->getParent() != Branch->getParent() &&
8765 !UI->getParent()->getSinglePredecessor()))
8766 continue;
8767
8768 if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
8769 match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) {
8770 IRBuilder<> Builder(Branch);
8771 if (UI->getParent() != Branch->getParent())
8772 UI->moveBefore(Branch->getIterator());
8774 Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI,
8775 ConstantInt::get(UI->getType(), 0));
8776 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8777 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8778 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8779 return true;
8780 }
8781 if (Cmp->isEquality() &&
8782 (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) ||
8783 match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))) ||
8784 match(UI, m_Xor(m_Specific(X), m_SpecificInt(CmpC))))) {
8785 IRBuilder<> Builder(Branch);
8786 if (UI->getParent() != Branch->getParent())
8787 UI->moveBefore(Branch->getIterator());
8789 Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI,
8790 ConstantInt::get(UI->getType(), 0));
8791 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8792 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8793 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8794 return true;
8795 }
8796 }
8797 return false;
8798}
8799
8800bool CodeGenPrepare::optimizeInst(Instruction *I, ModifyDT &ModifiedDT) {
8801 bool AnyChange = false;
8802 AnyChange = fixupDbgVariableRecordsOnInst(*I);
8803
8804 // Bail out if we inserted the instruction to prevent optimizations from
8805 // stepping on each other's toes.
8806 if (InsertedInsts.count(I))
8807 return AnyChange;
8808
8809 // TODO: Move into the switch on opcode below here.
8810 if (PHINode *P = dyn_cast<PHINode>(I)) {
8811 // It is possible for very late stage optimizations (such as SimplifyCFG)
8812 // to introduce PHI nodes too late to be cleaned up. If we detect such a
8813 // trivial PHI, go ahead and zap it here.
8814 if (Value *V = simplifyInstruction(P, {*DL, TLInfo})) {
8815 LargeOffsetGEPMap.erase(P);
8816 replaceAllUsesWith(P, V, FreshBBs, IsHugeFunc);
8817 P->eraseFromParent();
8818 ++NumPHIsElim;
8819 return true;
8820 }
8821 return AnyChange;
8822 }
8823
8824 if (CastInst *CI = dyn_cast<CastInst>(I)) {
8825 // If the source of the cast is a constant, then this should have
8826 // already been constant folded. The only reason NOT to constant fold
8827 // it is if something (e.g. LSR) was careful to place the constant
8828 // evaluation in a block other than then one that uses it (e.g. to hoist
8829 // the address of globals out of a loop). If this is the case, we don't
8830 // want to forward-subst the cast.
8831 if (auto *BCI = dyn_cast<BitCastInst>(CI)) {
8832 // Hoist bitcasts of illegal types to reduce cross-block register pressure
8833 // and prevent register splitting.
8834 if (optimizeBitCast(BCI, *TLI, *DL)) {
8835 return true;
8836 }
8837 }
8838
8839 if (isa<Constant>(CI->getOperand(0)))
8840 return AnyChange;
8841
8842 if (OptimizeNoopCopyExpression(CI, *TLI, *DL))
8843 return true;
8844
8846 isa<TruncInst>(I)) &&
8848 I, LI->getLoopFor(I->getParent()), *TTI))
8849 return true;
8850
8851 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8852 /// Sink a zext or sext into its user blocks if the target type doesn't
8853 /// fit in one register
8854 if (TLI->getTypeAction(CI->getContext(),
8855 TLI->getValueType(*DL, CI->getType())) ==
8856 TargetLowering::TypeExpandInteger) {
8857 return SinkCast(CI);
8858 } else {
8860 I, LI->getLoopFor(I->getParent()), *TTI))
8861 return true;
8862
8863 bool MadeChange = optimizeExt(I);
8864 return MadeChange | optimizeExtUses(I);
8865 }
8866 }
8867 return AnyChange;
8868 }
8869
8870 if (auto *Cmp = dyn_cast<CmpInst>(I))
8871 if (optimizeCmp(Cmp, ModifiedDT))
8872 return true;
8873
8874 if (match(I, m_URem(m_Value(), m_Value())))
8875 if (optimizeURem(I))
8876 return true;
8877
8878 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8879 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
8880 bool Modified = optimizeLoadExt(LI);
8881 unsigned AS = LI->getPointerAddressSpace();
8882 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
8883 return Modified;
8884 }
8885
8886 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
8887 if (splitMergedValStore(*SI, *DL, *TLI, Opts.cgp_force_split_store))
8888 return true;
8889 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
8890 unsigned AS = SI->getPointerAddressSpace();
8891 return optimizeMemoryInst(I, SI->getOperand(1),
8892 SI->getOperand(0)->getType(), AS);
8893 }
8894
8895 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
8896 unsigned AS = RMW->getPointerAddressSpace();
8897 return optimizeMemoryInst(I, RMW->getPointerOperand(), RMW->getType(), AS);
8898 }
8899
8900 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
8901 unsigned AS = CmpX->getPointerAddressSpace();
8902 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
8903 CmpX->getCompareOperand()->getType(), AS);
8904 }
8905
8906 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
8907
8908 if (BinOp && BinOp->getOpcode() == Instruction::And &&
8909 Opts.cgp_andcmp_sinking &&
8910 sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts))
8911 return true;
8912
8913 // TODO: Move this into the switch on opcode - it handles shifts already.
8914 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
8915 BinOp->getOpcode() == Instruction::LShr)) {
8916 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
8917 if (CI && TLI->hasExtractBitsInsn())
8918 if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
8919 return true;
8920 }
8921
8922 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
8923 if (GEPI->hasAllZeroIndices()) {
8924 /// The GEP operand must be a pointer, so must its result -> BitCast
8925 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
8926 GEPI->getName(), GEPI->getIterator());
8927 NC->setDebugLoc(GEPI->getDebugLoc());
8928 replaceAllUsesWith(GEPI, NC, FreshBBs, IsHugeFunc);
8930 GEPI, TLInfo, nullptr,
8931 [&](Value *V) { removeAllAssertingVHReferences(V); });
8932 ++NumGEPsElim;
8933 optimizeInst(NC, ModifiedDT);
8934 return true;
8935 }
8937 return true;
8938 }
8939 }
8940
8941 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
8942 // freeze(icmp a, const)) -> icmp (freeze a), const
8943 // This helps generate efficient conditional jumps.
8944 CmpInst *CmpI = dyn_cast<CmpInst>(FI->getOperand(0));
8945 if (CmpI && CmpI->hasOneUse()) {
8946 auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1);
8947 bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) ||
8949 bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) ||
8951 if (Const0 || Const1) {
8952 if (!Const0 || !Const1) {
8953 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI->getIterator());
8954 F->takeName(FI);
8955 CmpI->setOperand(Const0 ? 1 : 0, F);
8956 }
8958 replaceAllUsesWith(FI, CmpI, FreshBBs, IsHugeFunc);
8959 FI->eraseFromParent();
8960 return true;
8961 }
8962 }
8963 return AnyChange;
8964 }
8965
8966 // Try to fold some cross-lane vector operations if in a loop.
8967 if (I->getType()->isVectorTy() &&
8968 TLI->optimizeVectorCrossLaneOperation(I, LI->getLoopFor(I->getParent())))
8969 return true;
8970
8971 if (tryToSinkFreeOperands(I))
8972 return true;
8973
8974 switch (I->getOpcode()) {
8975 case Instruction::Shl:
8976 case Instruction::LShr:
8977 case Instruction::AShr:
8978 return optimizeShiftInst(cast<BinaryOperator>(I));
8979 case Instruction::Call:
8980 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
8981 case Instruction::Select:
8982 return optimizeSelectInst(cast<SelectInst>(I));
8983 case Instruction::ShuffleVector:
8984 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
8985 case Instruction::Switch:
8986 return optimizeSwitchInst(cast<SwitchInst>(I));
8987 case Instruction::ExtractElement:
8988 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
8989 case Instruction::CondBr:
8990 return optimizeBranch(cast<CondBrInst>(I), *TLI, FreshBBs, IsHugeFunc);
8991 }
8992
8993 return AnyChange;
8994}
8995
8996/// Given an OR instruction, check to see if this is a bitreverse
8997/// idiom. If so, insert the new intrinsic and return true.
8998bool CodeGenPrepare::makeBitReverse(Instruction &I) {
8999 if (!I.getType()->isIntegerTy() ||
9001 TLI->getValueType(*DL, I.getType(), true)))
9002 return false;
9003
9004 SmallVector<Instruction *, 4> Insts;
9005 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
9006 return false;
9007 Instruction *LastInst = Insts.back();
9008 replaceAllUsesWith(&I, LastInst, FreshBBs, IsHugeFunc);
9010 &I, TLInfo, nullptr,
9011 [&](Value *V) { removeAllAssertingVHReferences(V); });
9012 return true;
9013}
9014
9015// In this pass we look for GEP and cast instructions that are used
9016// across basic blocks and rewrite them to improve basic-block-at-a-time
9017// selection.
9018bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
9019 SunkAddrs.clear();
9020 bool MadeChange = false;
9021
9022 do {
9023 CurInstIterator = BB.begin();
9024 ModifiedDT = ModifyDT::NotModifyDT;
9025 while (CurInstIterator != BB.end()) {
9026 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
9027 if (ModifiedDT != ModifyDT::NotModifyDT) {
9028 // For huge function we tend to quickly go though the inner optmization
9029 // opportunities in the BB. So we go back to the BB head to re-optimize
9030 // each instruction instead of go back to the function head.
9031 if (IsHugeFunc)
9032 break;
9033 return true;
9034 }
9035 }
9036 } while (ModifiedDT == ModifyDT::ModifyInstDT);
9037
9038 bool MadeBitReverse = true;
9039 while (MadeBitReverse) {
9040 MadeBitReverse = false;
9041 for (auto &I : reverse(BB)) {
9042 if (makeBitReverse(I)) {
9043 MadeBitReverse = MadeChange = true;
9044 break;
9045 }
9046 }
9047 }
9048 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
9049
9050 return MadeChange;
9051}
9052
9053bool CodeGenPrepare::fixupDbgVariableRecordsOnInst(Instruction &I) {
9054 bool AnyChange = false;
9055 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
9056 AnyChange |= fixupDbgVariableRecord(DVR);
9057 return AnyChange;
9058}
9059
9060// FIXME: should updating debug-info really cause the "changed" flag to fire,
9061// which can cause a function to be reprocessed?
9062bool CodeGenPrepare::fixupDbgVariableRecord(DbgVariableRecord &DVR) {
9063 if (DVR.Type != DbgVariableRecord::LocationType::Value &&
9064 DVR.Type != DbgVariableRecord::LocationType::Assign)
9065 return false;
9066
9067 // Does this DbgVariableRecord refer to a sunk address calculation?
9068 bool AnyChange = false;
9069 SmallDenseSet<Value *> LocationOps(DVR.location_ops().begin(),
9070 DVR.location_ops().end());
9071 for (Value *Location : LocationOps) {
9072 WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
9073 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
9074 if (SunkAddr) {
9075 // Point dbg.value at locally computed address, which should give the best
9076 // opportunity to be accurately lowered. This update may change the type
9077 // of pointer being referred to; however this makes no difference to
9078 // debugging information, and we can't generate bitcasts that may affect
9079 // codegen.
9080 DVR.replaceVariableLocationOp(Location, SunkAddr);
9081 AnyChange = true;
9082 }
9083 }
9084 return AnyChange;
9085}
9086
9088 DVR->removeFromParent();
9089 BasicBlock *VIBB = VI->getParent();
9090 if (isa<PHINode>(VI))
9091 VIBB->insertDbgRecordBefore(DVR, VIBB->getFirstInsertionPt());
9092 else
9093 VIBB->insertDbgRecordAfter(DVR, &*VI);
9094}
9095
9096// A llvm.dbg.value may be using a value before its definition, due to
9097// optimizations in this pass and others. Scan for such dbg.values, and rescue
9098// them by moving the dbg.value to immediately after the value definition.
9099// FIXME: Ideally this should never be necessary, and this has the potential
9100// to re-order dbg.value intrinsics.
9101bool CodeGenPrepare::placeDbgValues(Function &F) {
9102 bool MadeChange = false;
9103 DominatorTree &DT = getDT();
9104
9105 auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
9106 SmallVector<Instruction *, 4> VIs;
9107 for (Value *V : DbgItem->location_ops())
9108 if (Instruction *VI = dyn_cast_or_null<Instruction>(V))
9109 VIs.push_back(VI);
9110
9111 // This item may depend on multiple instructions, complicating any
9112 // potential sink. This block takes the defensive approach, opting to
9113 // "undef" the item if it has more than one instruction and any of them do
9114 // not dominate iem.
9115 for (Instruction *VI : VIs) {
9116 if (VI->isTerminator())
9117 continue;
9118
9119 // If VI is a phi in a block with an EHPad terminator, we can't insert
9120 // after it.
9121 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
9122 continue;
9123
9124 // If the defining instruction dominates the dbg.value, we do not need
9125 // to move the dbg.value.
9126 if (DT.dominates(VI, Position))
9127 continue;
9128
9129 // If we depend on multiple instructions and any of them doesn't
9130 // dominate this DVI, we probably can't salvage it: moving it to
9131 // after any of the instructions could cause us to lose the others.
9132 if (VIs.size() > 1) {
9133 LLVM_DEBUG(
9134 dbgs()
9135 << "Unable to find valid location for Debug Value, undefing:\n"
9136 << *DbgItem);
9137 DbgItem->setKillLocation();
9138 break;
9139 }
9140
9141 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
9142 << *DbgItem << ' ' << *VI);
9143 DbgInserterHelper(DbgItem, VI->getIterator());
9144 MadeChange = true;
9145 ++NumDbgValueMoved;
9146 }
9147 };
9148
9149 for (BasicBlock &BB : F) {
9150 for (Instruction &Insn : llvm::make_early_inc_range(BB)) {
9151 // Process any DbgVariableRecord records attached to this
9152 // instruction.
9153 for (DbgVariableRecord &DVR : llvm::make_early_inc_range(
9154 filterDbgVars(Insn.getDbgRecordRange()))) {
9155 if (DVR.Type != DbgVariableRecord::LocationType::Value)
9156 continue;
9157 DbgProcessor(&DVR, &Insn);
9158 }
9159 }
9160 }
9161
9162 return MadeChange;
9163}
9164
9165// Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
9166// probes can be chained dependencies of other regular DAG nodes and block DAG
9167// combine optimizations.
9168bool CodeGenPrepare::placePseudoProbes(Function &F) {
9169 bool MadeChange = false;
9170 for (auto &Block : F) {
9171 // Move the rest probes to the beginning of the block.
9172 auto FirstInst = Block.getFirstInsertionPt();
9173 while (FirstInst != Block.end() && isa<PseudoProbeInst>(FirstInst))
9174 ++FirstInst;
9175 BasicBlock::iterator I(FirstInst);
9176 I++;
9177 while (I != Block.end()) {
9178 if (auto *II = dyn_cast<PseudoProbeInst>(I++)) {
9179 II->moveBefore(FirstInst);
9180 MadeChange = true;
9181 }
9182 }
9183 }
9184 return MadeChange;
9185}
9186
9187/// Some targets prefer to split a conditional branch like:
9188/// \code
9189/// %0 = icmp ne i32 %a, 0
9190/// %1 = icmp ne i32 %b, 0
9191/// %or.cond = or i1 %0, %1
9192/// br i1 %or.cond, label %TrueBB, label %FalseBB
9193/// \endcode
9194/// into multiple branch instructions like:
9195/// \code
9196/// bb1:
9197/// %0 = icmp ne i32 %a, 0
9198/// br i1 %0, label %TrueBB, label %bb2
9199/// bb2:
9200/// %1 = icmp ne i32 %b, 0
9201/// br i1 %1, label %TrueBB, label %FalseBB
9202/// \endcode
9203/// This usually allows instruction selection to do even further optimizations
9204/// and combine the compare with the branch instruction. Currently this is
9205/// applied for targets which have "cheap" jump instructions.
9206///
9207/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
9208///
9209bool CodeGenPrepare::splitBranchCondition(Function &F) {
9210 if (!TM->Options.EnableFastISel || TLI->isJumpExpensive())
9211 return false;
9212
9213 bool MadeChange = false;
9214 for (auto &BB : F) {
9215 // Does this BB end with the following?
9216 // %cond1 = icmp|fcmp|binary instruction ...
9217 // %cond2 = icmp|fcmp|binary instruction ...
9218 // %cond.or = or|and i1 %cond1, cond2
9219 // br i1 %cond.or label %dest1, label %dest2"
9220 Instruction *LogicOp;
9221 BasicBlock *TBB, *FBB;
9222 if (!match(BB.getTerminator(),
9223 m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB)))
9224 continue;
9225
9226 auto *Br1 = cast<CondBrInst>(BB.getTerminator());
9227 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
9228 continue;
9229
9230 // The merging of mostly empty BB can cause a degenerate branch.
9231 if (TBB == FBB)
9232 continue;
9233
9234 unsigned Opc;
9235 Value *Cond1, *Cond2;
9236 if (match(LogicOp,
9237 m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2)))))
9238 Opc = Instruction::And;
9239 else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)),
9240 m_OneUse(m_Value(Cond2)))))
9241 Opc = Instruction::Or;
9242 else
9243 continue;
9244
9245 auto IsGoodCond = [](Value *Cond) {
9246 return match(
9247 Cond,
9249 m_LogicalOr(m_Value(), m_Value()))));
9250 };
9251 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
9252 continue;
9253
9254 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
9255
9256 // Create a new BB.
9257 auto *TmpBB =
9258 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
9259 BB.getParent(), BB.getNextNode());
9260 if (IsHugeFunc)
9261 FreshBBs.insert(TmpBB);
9262
9263 // Update original basic block by using the first condition directly by the
9264 // branch instruction and removing the no longer needed and/or instruction.
9265 Br1->setCondition(Cond1);
9266 LogicOp->eraseFromParent();
9267
9268 // Depending on the condition we have to either replace the true or the
9269 // false successor of the original branch instruction.
9270 if (Opc == Instruction::And)
9271 Br1->setSuccessor(0, TmpBB);
9272 else
9273 Br1->setSuccessor(1, TmpBB);
9274
9275 // Fill in the new basic block.
9276 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
9277 if (auto *I = dyn_cast<Instruction>(Cond2)) {
9278 I->removeFromParent();
9279 I->insertBefore(Br2->getIterator());
9280 }
9281
9282 // Update PHI nodes in both successors. The original BB needs to be
9283 // replaced in one successor's PHI nodes, because the branch comes now from
9284 // the newly generated BB (NewBB). In the other successor we need to add one
9285 // incoming edge to the PHI nodes, because both branch instructions target
9286 // now the same successor. Depending on the original branch condition
9287 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
9288 // we perform the correct update for the PHI nodes.
9289 // This doesn't change the successor order of the just created branch
9290 // instruction (or any other instruction).
9291 if (Opc == Instruction::Or)
9292 std::swap(TBB, FBB);
9293
9294 // Replace the old BB with the new BB.
9295 TBB->replacePhiUsesWith(&BB, TmpBB);
9296
9297 // Add another incoming edge from the new BB.
9298 for (PHINode &PN : FBB->phis()) {
9299 auto *Val = PN.getIncomingValueForBlock(&BB);
9300 PN.addIncoming(Val, TmpBB);
9301 }
9302
9303 if (Loop *L = LI->getLoopFor(&BB))
9304 L->addBasicBlockToLoop(TmpBB, *LI);
9305
9306 // The edge we need to delete starts at BB and ends at whatever TBB ends
9307 // up pointing to.
9308 DTU->applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
9309 {DominatorTree::Insert, TmpBB, TBB},
9310 {DominatorTree::Insert, TmpBB, FBB},
9311 {DominatorTree::Delete, &BB, TBB}});
9312
9313 // Update the branch weights (from SelectionDAGBuilder::
9314 // FindMergedConditions).
9315 if (Opc == Instruction::Or) {
9316 // Codegen X | Y as:
9317 // BB1:
9318 // jmp_if_X TBB
9319 // jmp TmpBB
9320 // TmpBB:
9321 // jmp_if_Y TBB
9322 // jmp FBB
9323 //
9324
9325 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
9326 // The requirement is that
9327 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
9328 // = TrueProb for original BB.
9329 // Assuming the original weights are A and B, one choice is to set BB1's
9330 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
9331 // assumes that
9332 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
9333 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
9334 // TmpBB, but the math is more complicated.
9335 uint64_t TrueWeight, FalseWeight;
9336 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9337 uint64_t NewTrueWeight = TrueWeight;
9338 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
9339 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9340 hasBranchWeightOrigin(*Br1));
9341
9342 NewTrueWeight = TrueWeight;
9343 NewFalseWeight = 2 * FalseWeight;
9344 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9345 /*IsExpected=*/false);
9346 }
9347 } else {
9348 // Codegen X & Y as:
9349 // BB1:
9350 // jmp_if_X TmpBB
9351 // jmp FBB
9352 // TmpBB:
9353 // jmp_if_Y TBB
9354 // jmp FBB
9355 //
9356 // This requires creation of TmpBB after CurBB.
9357
9358 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
9359 // The requirement is that
9360 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
9361 // = FalseProb for original BB.
9362 // Assuming the original weights are A and B, one choice is to set BB1's
9363 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
9364 // assumes that
9365 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
9366 uint64_t TrueWeight, FalseWeight;
9367 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9368 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
9369 uint64_t NewFalseWeight = FalseWeight;
9370 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9371 /*IsExpected=*/false);
9372
9373 NewTrueWeight = 2 * TrueWeight;
9374 NewFalseWeight = FalseWeight;
9375 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9376 /*IsExpected=*/false);
9377 }
9378 }
9379
9380 MadeChange = true;
9381
9382 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
9383 TmpBB->dump());
9384 }
9385 return MadeChange;
9386}
#define Success
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI, SetOfInstrs &InsertedInsts)
Duplicate and sink the given 'and' instruction into user blocks where it is used in a compare to allo...
static bool SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, DenseMap< BasicBlock *, BinaryOperator * > &InsertedShifts, const TargetLowering &TLI, const DataLayout &DL)
Sink both shift and truncate instruction to the use of truncate's BB.
static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, SmallVectorImpl< Value * > &OffsetV)
static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V)
Check if V (an operand of a select instruction) is an expensive instruction that is only used once.
static bool isExtractBitsCandidateUse(Instruction *User)
Check if the candidates could be combined with a shift instruction, which includes:
static bool optimizeBitCast(BitCastInst *BCI, const TargetLowering &TLI, const DataLayout &DL)
Hoists bitcasts to the source block to reduce register pressure.
static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, const TargetLowering &TLI, const DataLayout &DL)
Sink the shift right instruction into user blocks if the uses could potentially be combined with this...
static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, const DataLayout &DL)
If the specified cast instruction is a noop copy (e.g.
static bool SinkCast(CastInst *CI)
Sink the specified cast instruction into its user blocks.
static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, const TargetLowering &TLI, bool ForceSplitStore)
For the instruction sequence of store below, F and I values are bundled together as an i64 value befo...
static bool swapICmpOperandsToExposeCSEOpportunities(CmpInst *Cmp)
Many architectures use the same instruction for both subtract and cmp.
static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, const TargetLowering *TLI, SelectInst *SI)
Returns true if a SelectInst should be turned into an explicit branch.
static bool FindAllMemoryUses(Instruction *I, SmallVectorImpl< std::pair< Use *, Type * > > &MemoryUses, SmallPtrSetImpl< Instruction * > &ConsideredInsts, const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, unsigned &SeenInsts, unsigned MaxUsersToScan)
Recursively walk all the uses of I until we find a memory use.
static std::optional< std::pair< Instruction *, Constant * > > getIVIncrement(const PHINode *PN, const LoopInfo *LI)
If given PN is an inductive variable with value IVInc coming from the backedge, and on each iteration...
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
static bool foldICmpWithDominatingICmp(CmpInst *Cmp, const TargetLowering &TLI, bool EnableICmpEqToICmpSt)
For pattern like:
static bool foldURemOfLoopIncrement(Instruction *Rem, const DataLayout *DL, const LoopInfo *LI, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, const TargetTransformInfo *TTI)
static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, const TargetLowering &TLI, const TargetRegisterInfo &TRI)
Check to see if all uses of OpVal by the specified inline asm call are due to memory operands.
static bool isIntrinsicOrLFToBeTailCalled(const TargetLibraryInfo *TLInfo, const CallInst *CI)
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
static bool matchOverflowPattern(Instruction *&I, ExtractValueInst *&MulExtract, ExtractValueInst *&OverflowExtract)
static void computeBaseDerivedRelocateMap(const SmallVectorImpl< GCRelocateInst * > &AllRelocateCalls, MapVector< GCRelocateInst *, SmallVector< GCRelocateInst *, 0 > > &RelocateInstMap)
static bool simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, const SmallVectorImpl< GCRelocateInst * > &Targets)
static bool MightBeFoldableInst(Instruction *I)
This is a little filter, which returns true if an addressing computation involving I might be folded ...
static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS, Constant *&Step)
static bool isRemOfLoopIncrementWithLoopInvariant(Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut, Value *&AddOffsetOut, PHINode *&LoopIncrPNOut)
static bool isIVIncrement(const Value *V, const LoopInfo *LI)
static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP)
static void DbgInserterHelper(DbgVariableRecord *DVR, BasicBlock::iterator VI)
static bool isPromotedInstructionLegal(const TargetLowering &TLI, const DataLayout &DL, Value *Val)
Check whether or not Val is a legal instruction for TLI.
static BasicBlock::iterator findInsertPos(Value *Addr, Instruction *MemoryInst, Value *SunkAddr)
static bool IsNonLocalValue(Value *V, BasicBlock *BB)
Return true if the specified values are defined in a different basic block than BB.
static bool despeculateCountZeros(IntrinsicInst *CountZeros, DomTreeUpdater *DTU, LoopInfo *LI, const TargetLowering *TLI, const DataLayout *DL, ModifyDT &ModifiedDT, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
If counting leading or trailing zeros is an expensive operation and a zero input is defined,...
static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
Sink the given CmpInst into user blocks to reduce the number of virtual registers that must be create...
static bool hasSameExtUse(Value *Val, const TargetLowering &TLI)
Check if all the uses of Val are equivalent (or free) zero or sign extensions.
static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, BinaryOperator *&Add)
Match special-case patterns that check for unsigned add overflow.
Defines an IR pass for CodeGen Prepare.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:682
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
This file declares the LLVM IR specialization of the GenericCycle templates.
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
static Value * getCondition(Instruction *I)
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
iv users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1213
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define P(N)
ppc ctr loops verify
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the PointerIntPair class.
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
static bool optimizeCallInst(CallInst *CI, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, unsigned CombineOpc=0)
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static Constant * getConstantVector(MVT VT, ArrayRef< APInt > Bits, const APInt &Undefs, LLVMContext &C)
Value * RHS
Value * LHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:431
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
unsigned logBase2() const
Definition APInt.h:1781
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
An instruction that atomically checks whether a specified value is in a memory location,...
static unsigned getPointerOperandIndex()
an instruction that atomically reads a memory location, combines it with another value,...
static unsigned getPointerOperandIndex()
Analysis pass providing the BasicBlockSectionsProfileReader.
LLVM_ABI bool isFunctionHot(StringRef FuncName) const
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
LLVM_ABI void insertDbgRecordAfter(DbgRecord *DR, Instruction *I)
Insert a DbgRecord into a block at the position given by I.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a no-op cast from one type to another.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Analysis pass which computes BranchProbabilityInfo.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
bool isInlineAsm() const
Check if this call is an inline asm statement.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Conditional Branch instruction.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI void removeFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType Type
Classification of the debug-info record that this DbgVariableRecord represents.
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
iterator_range< idx_iterator > indices() const
This instruction compares its operands according to the predicate given to the constructor.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const BasicBlock & getEntryBlock() const
Definition Function.h:794
LLVM_ABI const Value * getStatepoint() const
The statepoint with which this gc.relocate is associated.
Represents calls to the gc.relocate intrinsic.
unsigned getBasePtrIndex() const
The index into the associate statepoint's argument list which contains the base pointer of the pointe...
void compute(FunctionT &F)
Compute the cycle info for a function.
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
bool isBBPendingDeletion(BasicBlockT *DelBB) const
Returns true if DelBB is awaiting deletion.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
LLVM_ABI bool canIncreaseAlignment() const
Returns true if the alignment of the value can be unilaterally increased.
Definition Globals.cpp:422
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This instruction compares its operands according to the predicate given to the constructor.
bool isEquality() const
Return true if this predicate is either EQ or NE.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
user_iterator_impl< Instruction > user_iterator
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
user_iterator user_end()
bool isShift() const
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
LLVM_ABI std::optional< simple_ilist< DbgRecord >::iterator > getDbgReinsertionPosition()
Return an iterator to the position of the "Next" DbgRecord after this instruction,...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
static MVT getIntegerVT(unsigned BitWidth)
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition MapVector.h:210
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
value_type pop_back_val()
Definition SetVector.h:285
VectorType * getType() const
Overload to return most specific vector type.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
typename SuperClass::iterator iterator
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
int InstructionOpcodeToISD(unsigned Opcode) const
Get the ISD node that corresponds to the Instruction class opcode.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool isSelectSupported(SelectSupportKind) const
virtual bool isEqualityCmpFoldedWithSignedCmp() const
Return true if instruction generated for equality comparison is folded with instruction generated for...
virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT, bool MathUsed) const
Try to convert math with an overflow comparison into the corresponding DAG node operation.
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
virtual bool shouldOptimizeMulOverflowWithZeroHighBits(LLVMContext &Context, EVT VT) const
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
const TargetMachine & getTargetMachine() const
virtual bool isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual bool isFreeAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(....
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
virtual bool isCheapToSpeculateCttz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic cttz.
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isSlowDivBypassed() const
Returns true if target has indicated at least one type should be bypassed.
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual bool hasMultipleConditionRegisters(EVT VT) const
Does the target have multiple (allocatable) condition registers that can be used to store the results...
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
virtual MVT getPreferredSwitchConditionType(LLVMContext &Context, EVT ConditionVT) const
Returns preferred type for switch condition.
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy,Idx).
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual bool shouldConsiderGEPOffsetSplit() const
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
virtual bool getAddrModeArguments(const IntrinsicInst *, SmallVectorImpl< Value * > &, Type *&) const
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
const DenseMap< unsigned int, unsigned int > & getBypassSlowDivWidths() const
Returns map of slow types for division or remainder with corresponding fast types.
virtual bool isCheapToSpeculateCtlz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic ctlz.
virtual bool useSoftFloat() const
virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset, int64_t MaxOffset) const
Return the prefered common base offset.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool optimizeVectorCrossLaneOperation(Instruction *I, Loop *L) const
virtual bool shouldAlignPointerArgs(CallInst *, unsigned &, Align &) const
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
virtual Type * shouldConvertSplatType(ShuffleVectorInst *SVI) const
Given a shuffle vector SVI representing a vector splat, return a new scalar type of size equal to SVI...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
virtual bool addressingModeSupportsTLS(const GlobalValue &) const
Returns true if the targets addressing mode can target thread local storage (TLS).
virtual bool shouldConvertPhiType(Type *From, Type *To) const
Given a set in interconnected phis of type 'From' that are loaded/stored or bitcast to type 'To',...
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
virtual bool preferZeroCompareBranch() const
Return true if the heuristic to prefer icmp eq zero should be used in code gen prepare.
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
virtual bool optimizeExtendOrTruncateConversion(Instruction *I, Loop *L, const TargetTransformInfo &TTI) const
Try to optimize extending or truncating conversion instructions (like zext, trunc,...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
std::vector< AsmOperandInfo > AsmOperandInfoVector
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual bool mayBeEmittedAsTailCall(const CallInst *) const
Return true if the target may be able emit the call instruction as a tail call.
virtual bool isNoopAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
TargetOptions Options
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
virtual bool addrSinkUsingGEPs() const
Sink addresses into blocks using GEP instructions rather than pointer casts and arithmetic.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
Return the expected cost of materializing for the given integer immediate of the specified type.
LLVM_ABI bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
@ TCC_Basic
The cost of a typical 'add' instruction.
LLVM_ABI bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it's significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
LLVM_ABI bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops) const
Return true if sinking I's operands to the same basic block as I is profitable, e....
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
BasicBlock * getSuccessor(unsigned i=0) const
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:1000
LLVM_ABI bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
Definition Value.cpp:235
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:708
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
bool pointsToAliveValue() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isNonZero() const
Definition TypeSize.h:156
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
unsigned getAddrMode(MCInstrInfo const &MCII, MCInst const &MCI)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
SmallVector< Node, 4 > NodeList
Definition RDFGraph.h:550
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:520
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
LLVM_ABI bool bypassSlowDivision(BasicBlock *BB, const DenseMap< unsigned int, unsigned int > &BypassWidth, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BranchProbabilityInfo *BPI=nullptr)
This optimization identifies DIV instructions in a BB that can be profitably bypassed and carried out...
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APInt operator*(APInt a, uint64_t RHS)
Definition APInt.h:2261
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1678
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2139
constexpr from_range_t from_range
LLVM_ABI BasicBlock * splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
LLVM_ABI Instruction * SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ElseBlock=nullptr)
Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false path of the branch.
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
Definition MathExtras.h:698
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition Local.cpp:3796
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI FunctionPass * createCodeGenPrepareLegacyPass()
createCodeGenPrepareLegacyPass - Transform the code to expose more pattern matching during instructio...
LLVM_ABI ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred)
getFCmpCondCode - Return the ISD condition code corresponding to the given LLVM IR floating-point con...
Definition Analysis.cpp:214
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:54
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI bool attributesPermitTailCall(const Function *F, const Instruction *I, const ReturnInst *Ret, const TargetLoweringBase &TLI, bool *AllowDifferingSizes=nullptr)
Test if given that the input instruction is in the tail call position, if there is an attribute misma...
Definition Analysis.cpp:704
TargetTransformInfo TTI
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
constexpr unsigned BitWidth
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:240
constexpr bool valueOr(BoolOrDefault X, bool Default)
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > MulOverflow(T X, T Y)
Multiply two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:772
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
std::pair< Value *, FPClassTest > fcmpToClassTest(FCmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Returns a pair of values, which if passed to llvm.is.fpclass, returns the same result as an fcmp with...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI Value * simplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a URem, fold the result or return null.
DenseMap< const Value *, Value * > ValueToValueMap
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:271
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
This contains information for each constraint that we are lowering.