Skip to content

Commit cfbc178

Browse files
committedNov 26, 2018
Support for inserting profile-directed cache prefetches
Summary: Support for profile-driven cache prefetching (X86) This change is part of a larger system, consisting of a cache prefetches recommender, create_llvm_prof (https://github.com/google/autofdo), and LLVM. A proof of concept recommender is DynamoRIO's cache miss analyzer. It processes memory access traces obtained from a running binary and identifies patterns in cache misses. Based on them, it produces a csv file with recommendations. The expectation is that, by leveraging such recommendations, we can reduce the amount of clock cycles spent waiting for data from memory. A microbenchmark based on the DynamoRIO analyzer is available as a proof of concept: https://goo.gl/6TM2Xp. The recommender makes prefetch recommendations in terms of: * the binary offset of an instruction with a memory operand; * a delta; * and a type (nta, t0, t1, t2) meaning: a prefetch of that type should be inserted right before the instrution at that binary offset, and the prefetch should be for an address delta away from the memory address the instruction will access. For example: 0x400ab2,64,nta and assuming the instruction at 0x400ab2 is: movzbl (%rbx,%rdx,1),%edx means that the recommender determined it would be beneficial for a prefetchnta instruction to be inserted right before this instruction, as such: prefetchnta 0x40(%rbx,%rdx,1) movzbl (%rbx, %rdx, 1), %edx The workflow for prefetch cache instrumentation is as follows (the proof of concept script details these steps as well): 1. build binary, making sure -gmlt -fdebug-info-for-profiling is passed. The latter option will enable the X86DiscriminateMemOps pass, which ensures instructions with memory operands are uniquely identifiable (this causes ~2% size increase in total binary size due to the additional debug information). 2. collect memory traces, run analysis to obtain recommendations (see above-referenced DynamoRIO demo as a proof of concept). 3. use create_llvm_prof to convert recommendations to reference insertion locations in terms of debug info locations. 4. rebuild binary, using the exact same set of arguments used initially, to which -mllvm -prefetch-hints-file=<file> needs to be added, using the afdo file obtained at step 3. Note that if sample profiling feedback-driven optimization is also desired, that happens before step 1 above. In this case, the sample profile afdo file that was used to produce the binary at step 1 must also be included in step 4. The data needed by the compiler in order to identify prefetch insertion points is very similar to what is needed for sample profiles. For this reason, and given that the overall approach (memory tracing-based cache recommendation mechanisms) is under active development, we use the afdo format as a syntax for capturing this information. We avoid confusing semantics with sample profile afdo data by feeding the two types of information to the compiler through separate files and compiler flags. Should the approach prove successful, we can investigate improvements to this encoding mechanism. Reviewers: davidxl, wmi, craig.topper Reviewed By: davidxl, wmi, craig.topper Subscribers: davide, danielcdh, mgorny, aprantl, eraman, JDevlieghere, llvm-commits Differential Revision: https://reviews.llvm.org/D54052 llvm-svn: 347596
1 parent 88ce3dc commit cfbc178

13 files changed

+662
-0
lines changed
 

‎llvm/lib/Target/X86/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ set(sources
3030
X86CmovConversion.cpp
3131
X86CondBrFolding.cpp
3232
X86DomainReassignment.cpp
33+
X86DiscriminateMemOps.cpp
3334
X86ExpandPseudo.cpp
3435
X86FastISel.cpp
3536
X86FixupBWInsts.cpp
@@ -44,6 +45,7 @@ set(sources
4445
X86ISelLowering.cpp
4546
X86IndirectBranchTracking.cpp
4647
X86InterleavedAccess.cpp
48+
X86InsertPrefetch.cpp
4749
X86InstrFMA3Info.cpp
4850
X86InstrFoldTables.cpp
4951
X86InstrInfo.cpp

‎llvm/lib/Target/X86/X86.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,13 @@ FunctionPass *createX86EvexToVexInsts();
122122
/// This pass creates the thunks for the retpoline feature.
123123
FunctionPass *createX86RetpolineThunksPass();
124124

125+
/// This pass ensures instructions featuring a memory operand
126+
/// have distinctive <LineNumber, Discriminator> (with respect to eachother)
127+
FunctionPass *createX86DiscriminateMemOpsPass();
128+
129+
/// This pass applies profiling information to insert cache prefetches.
130+
FunctionPass *createX86InsertPrefetchPass();
131+
125132
InstructionSelector *createX86InstructionSelector(const X86TargetMachine &TM,
126133
X86Subtarget &,
127134
X86RegisterBankInfo &);
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
//===- X86DiscriminateMemOps.cpp - Unique IDs for Mem Ops -----------------===//
2+
//
3+
// The LLVM Compiler Infrastructure
4+
//
5+
// This file is distributed under the University of Illinois Open Source
6+
// License. See LICENSE.TXT for details.
7+
//
8+
//===----------------------------------------------------------------------===//
9+
///
10+
/// This pass aids profile-driven cache prefetch insertion by ensuring all
11+
/// instructions that have a memory operand are distinguishible from each other.
12+
///
13+
//===----------------------------------------------------------------------===//
14+
15+
#include "X86.h"
16+
#include "X86InstrBuilder.h"
17+
#include "X86InstrInfo.h"
18+
#include "X86MachineFunctionInfo.h"
19+
#include "X86Subtarget.h"
20+
#include "llvm/CodeGen/MachineModuleInfo.h"
21+
#include "llvm/IR/DebugInfoMetadata.h"
22+
#include "llvm/ProfileData/SampleProf.h"
23+
#include "llvm/ProfileData/SampleProfReader.h"
24+
#include "llvm/Transforms/IPO/SampleProfile.h"
25+
using namespace llvm;
26+
27+
namespace {
28+
29+
using Location = std::pair<StringRef, unsigned>;
30+
31+
Location diToLocation(const DILocation *Loc) {
32+
return std::make_pair(Loc->getFilename(), Loc->getLine());
33+
}
34+
35+
/// Ensure each instruction having a memory operand has a distinct <LineNumber,
36+
/// Discriminator> pair.
37+
void updateDebugInfo(MachineInstr *MI, const DILocation *Loc) {
38+
DebugLoc DL(Loc);
39+
MI->setDebugLoc(DL);
40+
}
41+
42+
class X86DiscriminateMemOps : public MachineFunctionPass {
43+
bool runOnMachineFunction(MachineFunction &MF) override;
44+
45+
public:
46+
static char ID;
47+
48+
/// Default construct and initialize the pass.
49+
X86DiscriminateMemOps();
50+
};
51+
52+
} // end anonymous namespace
53+
54+
//===----------------------------------------------------------------------===//
55+
// Implementation
56+
//===----------------------------------------------------------------------===//
57+
58+
char X86DiscriminateMemOps::ID = 0;
59+
60+
/// Default construct and initialize the pass.
61+
X86DiscriminateMemOps::X86DiscriminateMemOps() : MachineFunctionPass(ID) {}
62+
63+
bool X86DiscriminateMemOps::runOnMachineFunction(MachineFunction &MF) {
64+
DISubprogram *FDI = MF.getFunction().getSubprogram();
65+
if (!FDI || !FDI->getUnit()->getDebugInfoForProfiling())
66+
return false;
67+
68+
// Have a default DILocation, if we find instructions with memops that don't
69+
// have any debug info.
70+
const DILocation *ReferenceDI =
71+
DILocation::get(FDI->getContext(), FDI->getLine(), 0, FDI);
72+
73+
DenseMap<Location, unsigned> MemOpDiscriminators;
74+
MemOpDiscriminators[diToLocation(ReferenceDI)] = 0;
75+
76+
// Figure out the largest discriminator issued for each Location. When we
77+
// issue new discriminators, we can thus avoid issuing discriminators
78+
// belonging to instructions that don't have memops. This isn't a requirement
79+
// for the goals of this pass, however, it avoids unnecessary ambiguity.
80+
for (auto &MBB : MF) {
81+
for (auto &MI : MBB) {
82+
const auto &DI = MI.getDebugLoc();
83+
if (!DI)
84+
continue;
85+
Location Loc = diToLocation(DI);
86+
MemOpDiscriminators[Loc] =
87+
std::max(MemOpDiscriminators[Loc], DI->getBaseDiscriminator());
88+
}
89+
}
90+
91+
// Keep track of the discriminators seen at each Location. If an instruction's
92+
// DebugInfo has a Location and discriminator we've already seen, replace its
93+
// discriminator with a new one, to guarantee uniqueness.
94+
DenseMap<Location, DenseSet<unsigned>> Seen;
95+
96+
bool Changed = false;
97+
for (auto &MBB : MF) {
98+
for (auto &MI : MBB) {
99+
if (X86II::getMemoryOperandNo(MI.getDesc().TSFlags) < 0)
100+
continue;
101+
const DILocation *DI = MI.getDebugLoc();
102+
if (!DI) {
103+
DI = ReferenceDI;
104+
}
105+
DenseSet<unsigned> &Set = Seen[diToLocation(DI)];
106+
std::pair<DenseSet<unsigned>::iterator, bool> P =
107+
Set.insert(DI->getBaseDiscriminator());
108+
if (!P.second) {
109+
DI = DI->setBaseDiscriminator(++MemOpDiscriminators[diToLocation(DI)]);
110+
updateDebugInfo(&MI, DI);
111+
Changed = true;
112+
*P.first = DI->getBaseDiscriminator();
113+
}
114+
115+
// Bump the reference DI to avoid cramming discriminators on line 0.
116+
// FIXME(mtrofin): pin ReferenceDI on blocks or first instruction with DI
117+
// in a block. It's more consistent than just relying on the last memop
118+
// instruction we happened to see.
119+
ReferenceDI = DI;
120+
}
121+
}
122+
return Changed;
123+
}
124+
125+
FunctionPass *llvm::createX86DiscriminateMemOpsPass() {
126+
return new X86DiscriminateMemOps();
127+
}
Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
//===------- X86InsertPrefetch.cpp - Insert cache prefetch hints ----------===//
2+
//
3+
// The LLVM Compiler Infrastructure
4+
//
5+
// This file is distributed under the University of Illinois Open Source
6+
// License. See LICENSE.TXT for details.
7+
//
8+
//===----------------------------------------------------------------------===//
9+
//
10+
// This pass applies cache prefetch instructions based on a profile. The pass
11+
// assumes DiscriminateMemOps ran immediately before, to ensure debug info
12+
// matches the one used at profile generation time. The profile is encoded in
13+
// afdo format (text or binary). It contains prefetch hints recommendations.
14+
// Each recommendation is made in terms of debug info locations, a type (i.e.
15+
// nta, t{0|1|2}) and a delta. The debug info identifies an instruction with a
16+
// memory operand (see X86DiscriminateMemOps). The prefetch will be made for
17+
// a location at that memory operand + the delta specified in the
18+
// recommendation.
19+
//
20+
//===----------------------------------------------------------------------===//
21+
22+
#include "X86.h"
23+
#include "X86InstrBuilder.h"
24+
#include "X86InstrInfo.h"
25+
#include "X86MachineFunctionInfo.h"
26+
#include "X86Subtarget.h"
27+
#include "llvm/CodeGen/MachineModuleInfo.h"
28+
#include "llvm/IR/DebugInfoMetadata.h"
29+
#include "llvm/ProfileData/SampleProf.h"
30+
#include "llvm/ProfileData/SampleProfReader.h"
31+
#include "llvm/Transforms/IPO/SampleProfile.h"
32+
using namespace llvm;
33+
using namespace sampleprof;
34+
35+
static cl::opt<std::string>
36+
PrefetchHintsFile("prefetch-hints-file",
37+
cl::desc("Path to the prefetch hints profile."),
38+
cl::Hidden);
39+
namespace {
40+
41+
class X86InsertPrefetch : public MachineFunctionPass {
42+
void getAnalysisUsage(AnalysisUsage &AU) const override;
43+
bool doInitialization(Module &) override;
44+
45+
bool runOnMachineFunction(MachineFunction &MF) override;
46+
struct PrefetchInfo {
47+
unsigned InstructionID;
48+
int64_t Delta;
49+
};
50+
typedef SmallVectorImpl<PrefetchInfo> Prefetches;
51+
bool findPrefetchInfo(const FunctionSamples *Samples, const MachineInstr &MI,
52+
Prefetches &prefetches) const;
53+
54+
public:
55+
static char ID;
56+
X86InsertPrefetch(const std::string &PrefetchHintsFilename);
57+
58+
private:
59+
std::string Filename;
60+
std::unique_ptr<SampleProfileReader> Reader;
61+
};
62+
63+
using PrefetchHints = SampleRecord::CallTargetMap;
64+
65+
// Return any prefetching hints for the specified MachineInstruction. The hints
66+
// are returned as pairs (name, delta).
67+
ErrorOr<PrefetchHints> getPrefetchHints(const FunctionSamples *TopSamples,
68+
const MachineInstr &MI) {
69+
if (const auto &Loc = MI.getDebugLoc())
70+
if (const auto *Samples = TopSamples->findFunctionSamples(Loc))
71+
return Samples->findCallTargetMapAt(FunctionSamples::getOffset(Loc),
72+
Loc->getBaseDiscriminator());
73+
return std::error_code();
74+
}
75+
76+
} // end anonymous namespace
77+
78+
//===----------------------------------------------------------------------===//
79+
// Implementation
80+
//===----------------------------------------------------------------------===//
81+
82+
char X86InsertPrefetch::ID = 0;
83+
84+
X86InsertPrefetch::X86InsertPrefetch(const std::string &PrefetchHintsFilename)
85+
: MachineFunctionPass(ID), Filename(PrefetchHintsFilename) {}
86+
87+
/// Return true if the provided MachineInstruction has cache prefetch hints. In
88+
/// that case, the prefetch hints are stored, in order, in the Prefetches
89+
/// vector.
90+
bool X86InsertPrefetch::findPrefetchInfo(const FunctionSamples *TopSamples,
91+
const MachineInstr &MI,
92+
Prefetches &Prefetches) const {
93+
assert(Prefetches.empty() &&
94+
"Expected caller passed empty PrefetchInfo vector.");
95+
static const std::pair<const StringRef, unsigned> HintTypes[] = {
96+
{"_nta_", X86::PREFETCHNTA},
97+
{"_t0_", X86::PREFETCHT0},
98+
{"_t1_", X86::PREFETCHT1},
99+
{"_t2_", X86::PREFETCHT2},
100+
};
101+
static const char *SerializedPrefetchPrefix = "__prefetch";
102+
103+
const ErrorOr<PrefetchHints> T = getPrefetchHints(TopSamples, MI);
104+
if (!T)
105+
return false;
106+
int16_t max_index = -1;
107+
// Convert serialized prefetch hints into PrefetchInfo objects, and populate
108+
// the Prefetches vector.
109+
for (const auto &S_V : *T) {
110+
StringRef Name = S_V.getKey();
111+
if (Name.consume_front(SerializedPrefetchPrefix)) {
112+
int64_t D = static_cast<int64_t>(S_V.second);
113+
unsigned IID = 0;
114+
for (const auto &HintType : HintTypes) {
115+
if (Name.startswith(HintType.first)) {
116+
Name = Name.drop_front(HintType.first.size());
117+
IID = HintType.second;
118+
break;
119+
}
120+
}
121+
if (IID == 0)
122+
return false;
123+
uint8_t index = 0;
124+
Name.consumeInteger(10, index);
125+
126+
if (index >= Prefetches.size())
127+
Prefetches.resize(index + 1);
128+
Prefetches[index] = {IID, D};
129+
max_index = std::max(max_index, static_cast<int16_t>(index));
130+
}
131+
}
132+
assert(max_index + 1 >= 0 &&
133+
"Possible overflow: max_index + 1 should be positive.");
134+
assert(static_cast<size_t>(max_index + 1) == Prefetches.size() &&
135+
"The number of prefetch hints received should match the number of "
136+
"PrefetchInfo objects returned");
137+
return !Prefetches.empty();
138+
}
139+
140+
bool X86InsertPrefetch::doInitialization(Module &M) {
141+
if (Filename.empty())
142+
return false;
143+
144+
LLVMContext &Ctx = M.getContext();
145+
ErrorOr<std::unique_ptr<SampleProfileReader>> ReaderOrErr =
146+
SampleProfileReader::create(Filename, Ctx);
147+
if (std::error_code EC = ReaderOrErr.getError()) {
148+
std::string Msg = "Could not open profile: " + EC.message();
149+
Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg,
150+
DiagnosticSeverity::DS_Warning));
151+
return false;
152+
}
153+
Reader = std::move(ReaderOrErr.get());
154+
Reader->read();
155+
return true;
156+
}
157+
158+
void X86InsertPrefetch::getAnalysisUsage(AnalysisUsage &AU) const {
159+
AU.setPreservesAll();
160+
AU.addRequired<MachineModuleInfo>();
161+
}
162+
163+
bool X86InsertPrefetch::runOnMachineFunction(MachineFunction &MF) {
164+
if (!Reader)
165+
return false;
166+
const FunctionSamples *Samples = Reader->getSamplesFor(MF.getFunction());
167+
if (!Samples)
168+
return false;
169+
170+
bool Changed = false;
171+
172+
const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
173+
SmallVector<PrefetchInfo, 4> Prefetches;
174+
for (auto &MBB : MF) {
175+
for (auto MI = MBB.instr_begin(); MI != MBB.instr_end();) {
176+
auto Current = MI;
177+
++MI;
178+
179+
int Offset = X86II::getMemoryOperandNo(Current->getDesc().TSFlags);
180+
if (Offset < 0)
181+
continue;
182+
Prefetches.clear();
183+
if (!findPrefetchInfo(Samples, *Current, Prefetches))
184+
continue;
185+
assert(!Prefetches.empty() &&
186+
"The Prefetches vector should contain at least a value if "
187+
"findPrefetchInfo returned true.");
188+
for (auto &PrefInfo : Prefetches) {
189+
unsigned PFetchInstrID = PrefInfo.InstructionID;
190+
int64_t Delta = PrefInfo.Delta;
191+
const MCInstrDesc &Desc = TII->get(PFetchInstrID);
192+
MachineInstr *PFetch =
193+
MF.CreateMachineInstr(Desc, Current->getDebugLoc(), true);
194+
MachineInstrBuilder MIB(MF, PFetch);
195+
unsigned Bias = X86II::getOperandBias(Current->getDesc());
196+
int MemOpOffset = Offset + Bias;
197+
198+
assert(X86::AddrBaseReg == 0 && X86::AddrScaleAmt == 1 &&
199+
X86::AddrIndexReg == 2 && X86::AddrDisp == 3 &&
200+
X86::AddrSegmentReg == 4 &&
201+
"Unexpected change in X86 operand offset order.");
202+
203+
// This assumes X86::AddBaseReg = 0, {...}ScaleAmt = 1, etc.
204+
// FIXME(mtrofin): consider adding a:
205+
// MachineInstrBuilder::set(unsigned offset, op).
206+
MIB.addReg(Current->getOperand(MemOpOffset + X86::AddrBaseReg).getReg())
207+
.addImm(
208+
Current->getOperand(MemOpOffset + X86::AddrScaleAmt).getImm())
209+
.addReg(
210+
Current->getOperand(MemOpOffset + X86::AddrIndexReg).getReg())
211+
.addImm(Current->getOperand(MemOpOffset + X86::AddrDisp).getImm() +
212+
Delta)
213+
.addReg(Current->getOperand(MemOpOffset + X86::AddrSegmentReg)
214+
.getReg());
215+
216+
if (!Current->memoperands_empty()) {
217+
MachineMemOperand *CurrentOp = *(Current->memoperands_begin());
218+
MIB.addMemOperand(MF.getMachineMemOperand(
219+
CurrentOp, CurrentOp->getOffset() + Delta, CurrentOp->getSize()));
220+
}
221+
222+
// Insert before Current. This is because Current may clobber some of
223+
// the registers used to describe the input memory operand.
224+
MBB.insert(Current, PFetch);
225+
Changed = true;
226+
}
227+
}
228+
}
229+
return Changed;
230+
}
231+
232+
FunctionPass *llvm::createX86InsertPrefetchPass() {
233+
return new X86InsertPrefetch(PrefetchHintsFile);
234+
}

‎llvm/lib/Target/X86/X86TargetMachine.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,8 @@ void X86PassConfig::addPreEmitPass() {
497497
addPass(createX86FixupLEAs());
498498
addPass(createX86EvexToVexInsts());
499499
}
500+
addPass(createX86DiscriminateMemOpsPass());
501+
addPass(createX86InsertPrefetchPass());
500502
}
501503

502504
void X86PassConfig::addPreEmitPass2() {
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
; RUN: llc < %s | FileCheck %s
2+
;
3+
; original source, compiled with -O3 -gmlt -fdebug-info-for-profiling:
4+
; int sum(int* arr, int pos1, int pos2) {
5+
; return arr[pos1] + arr[pos2];
6+
; }
7+
;
8+
; ModuleID = 'test.cc'
9+
source_filename = "test.cc"
10+
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
11+
target triple = "x86_64-unknown-linux-gnu"
12+
13+
; Function Attrs: norecurse nounwind readonly uwtable
14+
define i32 @sum(i32* %arr, i32 %pos1, i32 %pos2) !dbg !7 {
15+
entry:
16+
%idxprom = sext i32 %pos1 to i64, !dbg !9
17+
%arrayidx = getelementptr inbounds i32, i32* %arr, i64 %idxprom, !dbg !9
18+
%0 = load i32, i32* %arrayidx, align 4, !dbg !9, !tbaa !10
19+
%idxprom1 = sext i32 %pos2 to i64, !dbg !14
20+
%arrayidx2 = getelementptr inbounds i32, i32* %arr, i64 %idxprom1, !dbg !14
21+
%1 = load i32, i32* %arrayidx2, align 4, !dbg !14, !tbaa !10
22+
%add = add nsw i32 %1, %0, !dbg !15
23+
ret i32 %add, !dbg !16
24+
}
25+
26+
attributes #0 = { "target-cpu"="x86-64" }
27+
28+
!llvm.dbg.cu = !{!0}
29+
!llvm.module.flags = !{!3, !4, !5}
30+
!llvm.ident = !{!6}
31+
32+
!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, isOptimized: true, runtimeVersion: 0, emissionKind: LineTablesOnly, enums: !2, debugInfoForProfiling: true)
33+
!1 = !DIFile(filename: "test.cc", directory: "/tmp")
34+
!2 = !{}
35+
!3 = !{i32 2, !"Dwarf Version", i32 4}
36+
!4 = !{i32 2, !"Debug Info Version", i32 3}
37+
!5 = !{i32 1, !"wchar_size", i32 4}
38+
!6 = !{!"clang version 7.0.0 (trunk 322155) (llvm/trunk 322159)"}
39+
!7 = distinct !DISubprogram(name: "sum", linkageName: "sum", scope: !1, file: !1, line: 1, type: !8, isLocal: false, isDefinition: true, scopeLine: 1, flags: DIFlagPrototyped, isOptimized: true, unit: !0)
40+
!8 = !DISubroutineType(types: !2)
41+
!9 = !DILocation(line: 2, column: 10, scope: !7)
42+
!10 = !{!11, !11, i64 0}
43+
!11 = !{!"int", !12, i64 0}
44+
!12 = !{!"omnipotent char", !13, i64 0}
45+
!13 = !{!"Simple C++ TBAA"}
46+
!14 = !DILocation(line: 2, column: 22, scope: !7)
47+
!15 = !DILocation(line: 2, column: 20, scope: !7)
48+
!16 = !DILocation(line: 2, column: 3, scope: !7)
49+
50+
;CHECK-LABEL: sum:
51+
;CHECK: # %bb.0:
52+
;CHECK: movl (%rdi,%rax,4), %eax
53+
;CHECK-NEXT: .loc 1 2 20 discriminator 2 # test.cc:2:20
54+
;CHECK-NEXT: addl (%rdi,%rcx,4), %eax
55+
;CHECK-NEXT: .loc 1 2 3 # test.cc:2:3
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
caller:0:0
2+
2:sum:0
3+
3: 0 __prefetch_nta_0:23456
4+
3.1: 0 __prefetch_nta_0:8764 __prefetch_nta_1:64
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
; RUN: llc < %s -prefetch-hints-file=%S/insert-prefetch-inline.afdo | FileCheck %s
2+
;
3+
; Verify we can insert prefetch instructions in code belonging to inlined
4+
; functions.
5+
;
6+
; ModuleID = 'test.cc'
7+
8+
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
9+
target triple = "x86_64-unknown-linux-gnu"
10+
11+
; Function Attrs: norecurse nounwind readonly uwtable
12+
define dso_local i32 @sum(i32* nocapture readonly %arr, i32 %pos1, i32 %pos2) local_unnamed_addr #0 !dbg !7 {
13+
entry:
14+
%idxprom = sext i32 %pos1 to i64, !dbg !10
15+
%arrayidx = getelementptr inbounds i32, i32* %arr, i64 %idxprom, !dbg !10
16+
%0 = load i32, i32* %arrayidx, align 4, !dbg !10, !tbaa !11
17+
%idxprom1 = sext i32 %pos2 to i64, !dbg !15
18+
%arrayidx2 = getelementptr inbounds i32, i32* %arr, i64 %idxprom1, !dbg !15
19+
%1 = load i32, i32* %arrayidx2, align 4, !dbg !15, !tbaa !11
20+
%add = add nsw i32 %1, %0, !dbg !16
21+
ret i32 %add, !dbg !17
22+
}
23+
24+
; "caller" inlines "sum". The associated .afdo file references instructions
25+
; in "caller" that came from "sum"'s inlining.
26+
;
27+
; Function Attrs: norecurse nounwind readonly uwtable
28+
define dso_local i32 @caller(i32* nocapture readonly %arr) local_unnamed_addr #0 !dbg !18 {
29+
entry:
30+
%0 = load i32, i32* %arr, align 4, !dbg !19, !tbaa !11
31+
%arrayidx2.i = getelementptr inbounds i32, i32* %arr, i64 2, !dbg !21
32+
%1 = load i32, i32* %arrayidx2.i, align 4, !dbg !21, !tbaa !11
33+
%add.i = add nsw i32 %1, %0, !dbg !22
34+
ret i32 %add.i, !dbg !23
35+
}
36+
37+
attributes #0 = { "target-cpu"="x86-64" }
38+
39+
!llvm.dbg.cu = !{!0}
40+
!llvm.module.flags = !{!3, !4, !5}
41+
!llvm.ident = !{!6}
42+
43+
!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 7.0.0 (trunk 324940) (llvm/trunk 324941)", isOptimized: true, runtimeVersion: 0, emissionKind: LineTablesOnly, enums: !2, debugInfoForProfiling: true)
44+
!1 = !DIFile(filename: "test.cc", directory: "/tmp")
45+
!2 = !{}
46+
!3 = !{i32 2, !"Dwarf Version", i32 4}
47+
!4 = !{i32 2, !"Debug Info Version", i32 3}
48+
!5 = !{i32 1, !"wchar_size", i32 4}
49+
!6 = !{!"clang version 7.0.0 (trunk 324940) (llvm/trunk 324941)"}
50+
!7 = distinct !DISubprogram(name: "sum", linkageName: "sum", scope: !8, file: !8, line: 3, type: !9, isLocal: false, isDefinition: true, scopeLine: 3, flags: DIFlagPrototyped, isOptimized: true, unit: !0)
51+
!8 = !DIFile(filename: "./test.h", directory: "/tmp")
52+
!9 = !DISubroutineType(types: !2)
53+
!10 = !DILocation(line: 6, column: 10, scope: !7)
54+
!11 = !{!12, !12, i64 0}
55+
!12 = !{!"int", !13, i64 0}
56+
!13 = !{!"omnipotent char", !14, i64 0}
57+
!14 = !{!"Simple C++ TBAA"}
58+
!15 = !DILocation(line: 6, column: 22, scope: !7)
59+
!16 = !DILocation(line: 6, column: 20, scope: !7)
60+
!17 = !DILocation(line: 6, column: 3, scope: !7)
61+
!18 = distinct !DISubprogram(name: "caller", linkageName: "caller", scope: !1, file: !1, line: 4, type: !9, isLocal: false, isDefinition: true, scopeLine: 4, flags: DIFlagPrototyped, isOptimized: true, unit: !0)
62+
!19 = !DILocation(line: 6, column: 10, scope: !7, inlinedAt: !20)
63+
!20 = distinct !DILocation(line: 6, column: 10, scope: !18)
64+
!21 = !DILocation(line: 6, column: 22, scope: !7, inlinedAt: !20)
65+
!22 = !DILocation(line: 6, column: 20, scope: !7, inlinedAt: !20)
66+
!23 = !DILocation(line: 6, column: 3, scope: !18)
67+
68+
; CHECK-LABEL: caller:
69+
; CHECK-LABEL: # %bb.0:
70+
; CHECK-NEXT: .loc 1 6 22 prologue_end
71+
; CHECK-NEXT: prefetchnta 23464(%rdi)
72+
; CHECK-NEXT: movl 8(%rdi), %eax
73+
; CHECK-NEXT: .loc 1 6 20 is_stmt 0 discriminator 2
74+
; CHECK-NEXT: prefetchnta 8764(%rdi)
75+
; CHECK-NEXT: prefetchnta 64(%rdi)
76+
; CHECK-NEXT: addl (%rdi), %eax
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
; RUN: llc < %s -prefetch-hints-file=%S/insert-prefetch-nomemop.afdo | FileCheck %s
2+
; ModuleID = 'prefetch.cc'
3+
source_filename = "prefetch.cc"
4+
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
5+
target triple = "x86_64-unknown-linux-gnu"
6+
7+
; Function Attrs: norecurse nounwind uwtable
8+
define dso_local i32 @main() local_unnamed_addr #0 !dbg !7 {
9+
entry:
10+
tail call void @llvm.prefetch(i8* inttoptr (i64 291 to i8*), i32 0, i32 0, i32 1), !dbg !9
11+
tail call void @llvm.x86.avx512.gatherpf.dpd.512(i8 97, <8 x i32> undef, i8* null, i32 1, i32 2), !dbg !10
12+
ret i32 291, !dbg !11
13+
}
14+
15+
; Function Attrs: inaccessiblemem_or_argmemonly nounwind
16+
declare void @llvm.prefetch(i8* nocapture readonly, i32, i32, i32) #1
17+
18+
; Function Attrs: argmemonly nounwind
19+
declare void @llvm.x86.avx512.gatherpf.dpd.512(i8, <8 x i32>, i8*, i32, i32) #2
20+
21+
attributes #0 = {"target-cpu"="x86-64" "target-features"="+avx512pf,+sse4.2,+ssse3"}
22+
attributes #1 = { inaccessiblemem_or_argmemonly nounwind }
23+
attributes #2 = { argmemonly nounwind }
24+
25+
!llvm.dbg.cu = !{!0}
26+
!llvm.module.flags = !{!3, !4, !5}
27+
!llvm.ident = !{!6}
28+
29+
!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, isOptimized: true, runtimeVersion: 0, emissionKind: LineTablesOnly, enums: !2, debugInfoForProfiling: true)
30+
!1 = !DIFile(filename: "prefetch.cc", directory: "/tmp")
31+
!2 = !{}
32+
!3 = !{i32 2, !"Dwarf Version", i32 4}
33+
!4 = !{i32 2, !"Debug Info Version", i32 3}
34+
!5 = !{i32 1, !"wchar_size", i32 4}
35+
!6 = !{!"clang version 7.0.0 (trunk 327078) (llvm/trunk 327086)"}
36+
!7 = distinct !DISubprogram(name: "main", scope: !1, file: !1, line: 8, type: !8, isLocal: false, isDefinition: true, scopeLine: 8, flags: DIFlagPrototyped, isOptimized: true, unit: !0)
37+
!8 = !DISubroutineType(types: !2)
38+
!9 = !DILocation(line: 12, column: 3, scope: !7)
39+
!10 = !DILocation(line: 14, column: 3, scope: !7)
40+
!11 = !DILocation(line: 15, column: 3, scope: !7)
41+
42+
;CHECK-LABEL: main:
43+
;CHECK: # %bb.0:
44+
;CHECK: prefetchnta 291
45+
;CHECK: prefetchnta 42(%rax,%ymm0)
46+
;CHECK-NEXT: vgatherpf1dpd (%rax,%ymm0) {%k1}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
main:0:0
2+
6: 0 __prefetch_nta_0:42
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
sum:0:0
2+
1: 0 __prefetch_t0_1:0 __prefetch_t2_0:42
3+
1.1: 0 __prefetch_t1_0:18446744073709551615
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
sum:0:0
2+
1: 0 __prefetch_nta_1:0 __prefetch_nta_0:42
3+
1.1: 0 __prefetch_nta_0:18446744073709551615
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
; RUN: llc < %s -prefetch-hints-file=%S/insert-prefetch.afdo | FileCheck %s
2+
; RUN: llc < %s -prefetch-hints-file=%S/insert-prefetch-other.afdo | FileCheck %s -check-prefix=OTHERS
3+
;
4+
; original source, compiled with -O3 -gmlt -fdebug-info-for-profiling:
5+
; int sum(int* arr, int pos1, int pos2) {
6+
; return arr[pos1] + arr[pos2];
7+
; }
8+
;
9+
; NOTE: debug line numbers were adjusted such that the function would start
10+
; at line 15 (an arbitrary number). The sample profile file format uses
11+
; offsets from the start of the symbol instead of file-relative line numbers.
12+
; The .afdo file reflects that - the instructions are offset '1'.
13+
;
14+
; ModuleID = 'test.cc'
15+
source_filename = "test.cc"
16+
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
17+
target triple = "x86_64-unknown-linux-gnu"
18+
19+
define i32 @sum(i32* %arr, i32 %pos1, i32 %pos2) !dbg !35 !prof !37 {
20+
entry:
21+
%idxprom = sext i32 %pos1 to i64, !dbg !38
22+
%arrayidx = getelementptr inbounds i32, i32* %arr, i64 %idxprom, !dbg !38
23+
%0 = load i32, i32* %arrayidx, align 4, !dbg !38, !tbaa !39
24+
%idxprom1 = sext i32 %pos2 to i64, !dbg !43
25+
%arrayidx2 = getelementptr inbounds i32, i32* %arr, i64 %idxprom1, !dbg !43
26+
%1 = load i32, i32* %arrayidx2, align 4, !dbg !43, !tbaa !39
27+
%add = add nsw i32 %1, %0, !dbg !44
28+
ret i32 %add, !dbg !45
29+
}
30+
31+
attributes #0 = { "target-cpu"="x86-64" }
32+
33+
!llvm.dbg.cu = !{!0}
34+
!llvm.module.flags = !{!3, !4, !5, !6}
35+
!llvm.ident = !{!33}
36+
37+
!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, isOptimized: true, runtimeVersion: 0, emissionKind: LineTablesOnly, enums: !2, debugInfoForProfiling: true)
38+
!1 = !DIFile(filename: "test.cc", directory: "/tmp")
39+
!2 = !{}
40+
!3 = !{i32 2, !"Dwarf Version", i32 4}
41+
!4 = !{i32 2, !"Debug Info Version", i32 3}
42+
!5 = !{i32 1, !"wchar_size", i32 4}
43+
!6 = !{i32 1, !"ProfileSummary", !7}
44+
!7 = !{!8, !9, !10, !11, !12, !13, !14, !15}
45+
!8 = !{!"ProfileFormat", !"SampleProfile"}
46+
!9 = !{!"TotalCount", i64 0}
47+
!10 = !{!"MaxCount", i64 0}
48+
!11 = !{!"MaxInternalCount", i64 0}
49+
!12 = !{!"MaxFunctionCount", i64 0}
50+
!13 = !{!"NumCounts", i64 2}
51+
!14 = !{!"NumFunctions", i64 1}
52+
!15 = !{!"DetailedSummary", !16}
53+
!16 = !{!17, !18, !19, !20, !21, !22, !22, !23, !23, !24, !25, !26, !27, !28, !29, !30, !31, !32}
54+
!17 = !{i32 10000, i64 0, i32 0}
55+
!18 = !{i32 100000, i64 0, i32 0}
56+
!19 = !{i32 200000, i64 0, i32 0}
57+
!20 = !{i32 300000, i64 0, i32 0}
58+
!21 = !{i32 400000, i64 0, i32 0}
59+
!22 = !{i32 500000, i64 0, i32 0}
60+
!23 = !{i32 600000, i64 0, i32 0}
61+
!24 = !{i32 700000, i64 0, i32 0}
62+
!25 = !{i32 800000, i64 0, i32 0}
63+
!26 = !{i32 900000, i64 0, i32 0}
64+
!27 = !{i32 950000, i64 0, i32 0}
65+
!28 = !{i32 990000, i64 0, i32 0}
66+
!29 = !{i32 999000, i64 0, i32 0}
67+
!30 = !{i32 999900, i64 0, i32 0}
68+
!31 = !{i32 999990, i64 0, i32 0}
69+
!32 = !{i32 999999, i64 0, i32 0}
70+
!33 = !{!"clang version 7.0.0 (trunk 322593) (llvm/trunk 322526)"}
71+
!35 = distinct !DISubprogram(name: "sum", linkageName: "sum", scope: !1, file: !1, line: 15, type: !36, isLocal: false, isDefinition: true, scopeLine: 15, flags: DIFlagPrototyped, isOptimized: true, unit: !0)
72+
!36 = !DISubroutineType(types: !2)
73+
!37 = !{!"function_entry_count", i64 -1}
74+
!38 = !DILocation(line: 16, column: 10, scope: !35)
75+
!39 = !{!40, !40, i64 0}
76+
!40 = !{!"int", !41, i64 0}
77+
!41 = !{!"omnipotent char", !42, i64 0}
78+
!42 = !{!"Simple C++ TBAA"}
79+
!43 = !DILocation(line: 16, column: 22, scope: !35)
80+
!44 = !DILocation(line: 16, column: 20, scope: !35)
81+
!45 = !DILocation(line: 16, column: 3, scope: !35)
82+
83+
;CHECK-LABEL: sum:
84+
;CHECK: # %bb.0:
85+
;CHECK: prefetchnta 42(%rdi,%rax,4)
86+
;CHECK-NEXT: prefetchnta (%rdi,%rax,4)
87+
;CHECK-NEXT: movl (%rdi,%rax,4), %eax
88+
;CHECK-NEXT: .loc 1 16 20 discriminator 2 # test.cc:16:20
89+
;CHECK-NEXT: prefetchnta -1(%rdi,%rcx,4)
90+
;CHECK-NEXT: addl (%rdi,%rcx,4), %eax
91+
;CHECK-NEXT: .loc 1 16 3 # test.cc:16:3
92+
93+
;OTHERS-LABEL: sum:
94+
;OTHERS: # %bb.0:
95+
;OTHERS: prefetcht2 42(%rdi,%rax,4)
96+
;OTHERS-NEXT: prefetcht0 (%rdi,%rax,4)
97+
;OTHERS-NEXT: movl (%rdi,%rax,4), %eax
98+
;OTHERS-NEXT: .loc 1 16 20 discriminator 2 # test.cc:16:20
99+
;OTHERS-NEXT: prefetcht1 -1(%rdi,%rcx,4)
100+
;OTHERS-NEXT: addl (%rdi,%rcx,4), %eax
101+
;OTHERS-NEXT: .loc 1 16 3 # test.cc:16:3

1 commit comments

Comments
 (1)

pinskia commented on Jul 18, 2024

@pinskia
Please sign in to comment.