-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArithInt.cpp
More file actions
293 lines (245 loc) · 11 KB
/
Copy pathArithInt.cpp
File metadata and controls
293 lines (245 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*******************************************************************************
* @file ArithInt.cpp
* @brief PinTool para el cálculo de la Intensidad Aritmética en los NPB.
* @author Lluís Castelló Vicent (lcastellovic@uoc.edu)
* @date 24 de Mayo de 2026
* @version 1.0
* @see Adaptado a partir del modelo 'inscount_tls.cpp' de Intel PIN TOOLS
* para la Universitat Oberta de Catalunya (UOC).
* @details Herramienta diseñada para clasificar si un benchmark HPC
* es Compute-bound o Memory-bound según su Intensidad Aritmética basada en el Modelo Roofline.
*******************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include "pin.H"
string targetProgramName = "desconocido";
string DefaultOutputFileName = "ArithInt.out";
// Knob para configurar el nombre del archivo de salida
KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool",
"o", DefaultOutputFileName, "Especificar el nombre del archivo de salida");
// Knobs para configurar las características de la máquina (pico teórico de cómputo y ancho de banda)
KNOB<double> KnobPeakGFlops(KNOB_MODE_WRITEONCE, "pintool",
"peak_gflops", "100.0", "Pico teórico de cómputo en GFLOPs/s");
KNOB<double> KnobPeakBandwidth(KNOB_MODE_WRITEONCE, "pintool",
"peak_bw", "50.0", "Ancho de banda de memoria en GB/s");
// Estructura con las características de la máquina
struct MachineRoofline {
double peak_gflops;
double peak_bandwidth;
double ridge_point;
};
PIN_LOCK lock;
INT32 numThreads = 0;
ofstream OutFile;
MachineRoofline cluster_node;
// Tamaño de alineación para evitar el problema de "False Sharing" en la caché L1.
// 3 variables de tipo UINT64 ocupan 24 bytes (8x3). Línea de caché = 64 bytes.
// 64 - 24 = 40 bytes de padding.
#define PADSIZE 40
// Estructura de datos local para cada hilo (Métricas Roofline)
class thread_data_t
{
public:
thread_data_t() : _ins_count(0), _flops_count(0), _bytes_transferred(0) {}
UINT64 _ins_count; // Instrucciones totales ejecutadas
UINT64 _flops_count; // Operaciones de Coma Flotante (FLOPs)
UINT64 _bytes_transferred; // Volumen total de datos en Bytes
UINT8 _pad[PADSIZE];
};
static TLS_KEY tls_key;
VOID CaptureTargetProgramName(INT32 argc, CHAR *argv[])
{
for (INT32 i = 0; i < argc - 1; ++i)
{
if (string(argv[i]) == "--" && (i + 1) < argc)
{
string programPath = argv[i + 1];
size_t lastSlash = programPath.find_last_of("\\/");
targetProgramName = (lastSlash == string::npos) ? programPath : programPath.substr(lastSlash + 1);
return;
}
}
}
thread_data_t* get_tls(THREADID threadid)
{
return static_cast<thread_data_t*>(PIN_GetThreadData(tls_key, threadid));
}
// Función para identificar instrucciones de coma flotante (FLOPs) por categoría y su contribución al
// conteo total de FLOPs.
BOOL IsFloatingPointArithmeticIns(INS ins, UINT32 &flop_count)
{
xed_category_enum_t category = static_cast<xed_category_enum_t>(INS_Category(ins));
flop_count = 0;
// Categorías FLOPs base
bool isFpCategory = (
category == XED_CATEGORY_X87_ALU ||
category == XED_CATEGORY_SSE ||
category == XED_CATEGORY_AVX ||
category == XED_CATEGORY_AVX2
);
// FMA: 2 FLOPs por instrucción
bool isFmaCategory = (
category == XED_CATEGORY_VFMA ||
category == XED_CATEGORY_FMA4
);
if (!isFpCategory && !isFmaCategory) return FALSE;
if (INS_IsMov(ins)) return FALSE;
flop_count = isFmaCategory ? 2 : 1;
return TRUE;
}
// Función para identificar instrucciones que generan tráfico de memoria relevante
// para el análisis Roofline según modelo de Intel Advisor.
BOOL IsMemoryTraffic(INS ins)
{
// Si la instrucción no interactúa con la memoria, no genera tráfico bus/DRAM
if (!INS_IsMemoryRead(ins) && !INS_IsMemoryWrite(ins)) return FALSE;
// FILTRO CRÍTICO: Si el acceso a memoria usa como base el puntero de pila (RSP o RBP),
// lo ignoramos porque se resuelve enteramente en la caché L1 y distorsiona el Roofline de memoria.
for (UINT32 i = 0; i < INS_OperandCount(ins); i++)
{
if (INS_OperandIsMemory(ins, i))
{
REG baseReg = INS_OperandMemoryBaseReg(ins, i);
if (baseReg == REG_RSP || baseReg == REG_RBP)
{
return FALSE;
}
}
}
if (INS_IsMov(ins)) return TRUE;
xed_category_enum_t category = static_cast<xed_category_enum_t>(INS_Category(ins));
if (category == XED_CATEGORY_DATAXFER ||
category == XED_CATEGORY_AVX2GATHER)
{
return TRUE;
}
return FALSE;
}
// Función de análisis invocada por cada ejecución de un bloque básico (BBL)
VOID UpdateThreadStats(UINT32 insCount, UINT32 flopsCount, UINT32 bytesInBbl, THREADID threadid)
{
thread_data_t* tdata = get_tls(threadid);
tdata->_ins_count += insCount;
tdata->_flops_count += flopsCount;
tdata->_bytes_transferred += bytesInBbl;
}
VOID ThreadStart(THREADID threadid, CONTEXT *ctxt, INT32 flags, VOID *v)
{
GetLock(&lock, threadid + 1);
numThreads++;
ReleaseLock(&lock);
thread_data_t* tdata = new thread_data_t;
PIN_SetThreadData(tls_key, tdata, threadid);
}
VOID Trace(TRACE trace, VOID *v)
{
for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl))
{
UINT32 insInBbl = BBL_NumIns(bbl);
UINT32 flopsInBbl = 0;
UINT32 bytesInBbl = 0;
// Inspección estática del bloque básico
for (INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins = INS_Next(ins))
{
// Detecta si es una instrucción de coma flotante (FLOP)
UINT32 flopContrib = 0;
bool isFp = IsFloatingPointArithmeticIns(ins, flopContrib);
if (isFp)
flopsInBbl += flopContrib;
if (IsMemoryTraffic(ins))
{
UINT32 memOps = INS_MemoryOperandCount(ins);
for (UINT32 op = 0; op < memOps; op++)
bytesInBbl += INS_MemoryOperandSize(ins, op);
}
}
BBL_InsertCall(bbl, IPOINT_ANYWHERE, (AFUNPTR)UpdateThreadStats,
IARG_UINT32, insInBbl,
IARG_UINT32, flopsInBbl,
IARG_UINT32, bytesInBbl,
IARG_THREAD_ID, IARG_END);
}
}
// Función para emitir la conclusión del análisis Roofline según la intensidad aritmética calculada
string GetRooflineConclusion(double intensity, const MachineRoofline& machine)
{
if (intensity == 0.0)
return "MEMORY-BOUND (Sin operaciones FP detectadas)";
if (intensity < machine.ridge_point)
return "MEMORY-BOUND (I < ridge point: limitado por ancho de banda)";
return "COMPUTE-BOUND (I >= ridge point: limitado por capacidad de computo)";
}
VOID Fini(INT32 code, VOID *v)
{
OutFile.setf(ios::showbase);
OutFile << "=================================================" << endl;
OutFile << " ANALIZADOR DE INTENSIDAD ARITMÉTICA (ArithInt)" << endl;
OutFile << "=================================================" << endl;
OutFile << "PROGRAMA: " << targetProgramName << endl;
OutFile << "Hilos totales detectados: " << numThreads << endl << endl;
OutFile << "Características de la máquina (Roofline):" << endl;
OutFile << " Pico de Cómputo: " << cluster_node.peak_gflops << " GFLOPs/s" << endl;
OutFile << " Ancho de Banda: " << cluster_node.peak_bandwidth << " GB/s" << endl;
OutFile << " Ridge Point: " << cluster_node.ridge_point << " FLOPs/Byte" << endl;
OutFile << "=================================================" << endl;
UINT64 global_ins = 0;
UINT64 global_flops = 0;
UINT64 global_bytes = 0;
// Emitimos el análisis por hilo con diagnóstico Roofline
for (INT32 t = 0; t < numThreads; t++)
{
thread_data_t* tdata = get_tls(t);
double thread_intensity = (tdata->_bytes_transferred > 0) ?
((double)tdata->_flops_count / tdata->_bytes_transferred) : 0.0;
OutFile << ">>> HILO [" << t << "]" << endl;
OutFile << " Instrucciones Totales: " << tdata->_ins_count << endl;
OutFile << " Operaciones FLOPs: " << tdata->_flops_count << endl;
OutFile << " Tráfico de Memoria: " << tdata->_bytes_transferred << " Bytes" << endl;
OutFile << " Intensidad Aritmética: " << thread_intensity << " FLOPs/Byte" << endl;
OutFile << " Diagnóstico: " << GetRooflineConclusion(thread_intensity, cluster_node) << endl << endl;
global_ins += tdata->_ins_count;
global_flops += tdata->_flops_count;
global_bytes += tdata->_bytes_transferred;
}
// Cálculo de la intensidad aritmética global y diagnóstico final
double global_intensity = (global_bytes > 0) ? ((double)global_flops / global_bytes) : 0.0;
OutFile << "=================================================" << endl;
OutFile << " RESUMEN GLOBAL DEL BENCHMARK (ROOFLINE) " << endl;
OutFile << "=================================================" << endl;
OutFile << "Total Instrucciones Globales: " << global_ins << endl;
OutFile << "Total FLOPs Globales: " << global_flops << endl;
OutFile << "Total Bytes Transferidos: " << global_bytes << " Bytes" << endl;
OutFile << "Intensidad Aritmética Global: " << global_intensity << " FLOPs/Byte" << endl;
OutFile << "DIAGNÓSTICO FINAL: " << GetRooflineConclusion(global_intensity, cluster_node) << endl;
OutFile << "=================================================" << endl;
OutFile.close();
}
int main(int argc, char * argv[])
{
PIN_InitSymbols();
CaptureTargetProgramName(argc, argv);
if (PIN_Init(argc, argv)) return -1;
cluster_node.peak_gflops = KnobPeakGFlops.Value();
cluster_node.peak_bandwidth = KnobPeakBandwidth.Value();
cluster_node.ridge_point = cluster_node.peak_gflops / cluster_node.peak_bandwidth;
string knobVal = KnobOutputFile.Value();
const string knobDefault = "ArithInt.out";
string outputFileName;
if (knobVal != knobDefault) {
outputFileName = knobVal;
} else {
if (targetProgramName != "desconocido")
outputFileName = "ArithInt_" + targetProgramName + ".out";
else
outputFileName = knobDefault;
}
OutFile.open(outputFileName.c_str());
InitLock(&lock);
tls_key = PIN_CreateThreadDataKey(0);
PIN_AddThreadStartFunction(ThreadStart, 0);
TRACE_AddInstrumentFunction(Trace, 0);
PIN_AddFiniFunction(Fini, 0);
PIN_StartProgram();
return 0;
}