-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp3.cpp
executable file
·422 lines (345 loc) · 11.8 KB
/
p3.cpp
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#include <fstream>
#include <memory>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "llvm-c/Core.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Dominators.h"
using namespace llvm;
static void LoopInvariantCodeMotion(Module *);
static void summarize(Module *M);
static void print_csv_file(std::string outputfile);
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::Required, cl::init("-"));
static cl::opt<std::string>
OutputFilename(cl::Positional, cl::desc("<output bitcode>"), cl::Required, cl::init("out.bc"));
static cl::opt<bool>
Mem2Reg("mem2reg",
cl::desc("Perform memory to register promotion before LICM."),
cl::init(false));
static cl::opt<bool>
CSE("cse",
cl::desc("Perform CSE before LICM."),
cl::init(false));
static cl::opt<bool>
NoLICM("no-licm",
cl::desc("Do not perform LICM optimization."),
cl::init(false));
static cl::opt<bool>
Verbose("verbose",
cl::desc("Verbose stats."),
cl::init(false));
static cl::opt<bool>
NoCheck("no",
cl::desc("Do not check for valid IR."),
cl::init(false));
int main(int argc, char **argv) {
// Parse command line arguments
cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
// Handle creating output files and shutting down properly
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
LLVMContext Context;
// LLVM idiom for constructing output file.
std::unique_ptr<ToolOutputFile> Out;
std::string ErrorInfo;
std::error_code EC;
Out.reset(new ToolOutputFile(OutputFilename.c_str(), EC,
sys::fs::OF_None));
EnableStatistics();
// Read in module
SMDiagnostic Err;
std::unique_ptr<Module> M;
M = parseIRFile(InputFilename, Err, Context);
// If errors, fail
if (M.get() == 0)
{
Err.print(argv[0], errs());
//FIXME: there is a segmentation fault
return 1;
}
// If requested, do some early optimizations
if (Mem2Reg || CSE)
{
legacy::PassManager Passes;
if (Mem2Reg)
Passes.add(createPromoteMemoryToRegisterPass());
if (CSE)
Passes.add(createEarlyCSEPass());
Passes.run(*M.get());
}
if (!NoLICM) {
LoopInvariantCodeMotion(M.get());
}
// Collect statistics on Module
summarize(M.get());
print_csv_file(OutputFilename);
if (Verbose)
PrintStatistics(errs());
// Verify integrity of Module, do this by default
if (!NoCheck)
{
legacy::PassManager Passes;
Passes.add(createVerifierPass());
Passes.run(*M.get());
}
// Write final bitcode
WriteBitcodeToFile(*M.get(), Out->os());
Out->keep();
return 0;
}
static llvm::Statistic nFunctions = {"", "Functions", "number of functions"};
static llvm::Statistic nInstructions = {"", "Instructions", "number of instructions"};
static llvm::Statistic nLoads = {"", "Loads", "number of loads"};
static llvm::Statistic nStores = {"", "Stores", "number of stores"};
static void summarize(Module *M) {
for (auto i = M->begin(); i != M->end(); i++) {
if (i->begin() != i->end()) {
nFunctions++;
}
for (auto j = i->begin(); j != i->end(); j++) {
for (auto k = j->begin(); k != j->end(); k++) {
Instruction &I = *k;
nInstructions++;
if (isa<LoadInst>(&I)) {
nLoads++;
} else if (isa<StoreInst>(&I)) {
nStores++;
}
}
}
}
}
static void print_csv_file(std::string outputfile)
{
std::ofstream stats(outputfile + ".stats");
auto a = GetStatistics();
for (auto p : a) {
stats << p.first.str() << "," << p.second << std::endl;
}
stats.close();
}
static llvm::Statistic NumLoops = {"", "NumLoops", "number of loops analyzed"};
static llvm::Statistic LICMBasic = {"", "LICMBasic", "basic loop invariant instructions"};
static llvm::Statistic LICMLoadHoist = {"", "LICMLoadHoist", "loop invariant load instructions"};
static llvm::Statistic LICMNoPreheader = {"", "LICMNoPreheader", "absence of preheader prevents optimization"};
static llvm::Statistic NumLoopsNoStore = {"", "NumLoopsNoStore", "subset of loops that has no Store instructions"};
static llvm::Statistic NumLoopsNoLoad = {"", "NumLoopsNoLoad", "subset of loops that has no Load instructions"};
static llvm::Statistic NumLoopsNoStoreWithLoad = {"", "NumLoopsNoStoreWithLoad", "subset of loops with no stores that also have at least one load."};
static llvm::Statistic NumLoopsWithCall = {"", "NumLoopsWithCall", "subset of loops that has a call instructions"};
/* Functionality Implementation */
static void hoistInstructionToPreheader(Instruction* I, BasicBlock* PreHeader){
/* Move an instruction to the PreHeader*/
Instruction *dst = PreHeader->getTerminator();
I->moveBefore(dst);
}
static bool AreAllOperandsLoopInvaraint(Loop* L, Instruction* I){
/* Alternative implementation of hasLoopInvariantOperands */
for (auto &op: I->operands()){
if (!L->isLoopInvariant(op)){
return false;
}
}
return true;
}
static bool dominatesLoopExit(Function *F, Loop *L, Value* V){
/* Checks whether an instruction dominates all the loop exits */
SmallVector<BasicBlock *, 20> ExitBlocks;
L->getExitBlocks(ExitBlocks);
if (ExitBlocks.empty()){
return true;
}
Instruction* i = dyn_cast<Instruction>(V);
DominatorTree *DT=nullptr;
DT = new DominatorTree();
DT->recalculate(*F);
for (auto *bb: ExitBlocks){
bool result = DT->dominates(i->getParent(), bb);
if (!result){
return false;
}
}
return true;
}
static bool NoPossibleStoresToAnyAddressInLoop(Loop *L){
for (auto *bb: L->blocks()){
for (auto &i: *bb){
if (isa<StoreInst>(i) || isa<CallInst>(i)){
return false;
}
}
}
//after all of this - this is a safe load
return true;
}
static bool NoPossibleStoresToAddressInLoop(Loop *L, Value* LoadAddress){
//no possible stores to addr in L
for (auto *bb: L->blocks()){
for (auto &i: *bb){
if (isa<StoreInst>(i)){
Value *addr_of_store = i.getOperand(1);
if (LoadAddress == addr_of_store){
return false;
}
// different address - if it's neither an alloca nor a global
// varible it could be loading to that address
else if (!isa<AllocaInst>(addr_of_store) && !isa<GlobalVariable>(addr_of_store)){
return false;
}
}
if (isa<CallInst>(i)){
return false;
}
}
}
//after all of this - this is a safe load
return true;
}
static bool AllocaNotInLoop(Loop *L, Value *Addr){
Instruction *x = dyn_cast<AllocaInst>(Addr);
BasicBlock *parent = x->getParent();
if (L->contains(parent)){
return false;
}
return true;
}
static bool CanMoveOutofLoop(Function *F, Loop *L, Instruction* I, Value* LoadAddress, bool loopHasStore){
/* Determines whether an instruction can be moved out of a loop
* */
// Case 1: instruction marked volatile - cannot be moved out of the loop
if (I->isVolatile()){
return false;
}
if (isa<GlobalVariable>(LoadAddress) && NoPossibleStoresToAddressInLoop(L, LoadAddress)){
return true;
}
if (isa<AllocaInst>(LoadAddress)
&& AllocaNotInLoop(L, LoadAddress)
&& NoPossibleStoresToAddressInLoop(L, LoadAddress)){
return true;
}
/*
// Worked on this but did not have it fully functioning due to segfaults
if (L->isLoopInvariant(LoadAddress)
&& NoPossibleStoresToAnyAddressInLoop(L)
&& dominatesLoopExit(F, L, LoadAddress)
){
return true;
}
*/
return false;
}
static void updateStats(bool hasLoad, bool hasStore){
if (!hasStore && hasLoad){
NumLoopsNoStoreWithLoad++;
} else if (!hasLoad){
NumLoopsNoLoad++;
} else if (!hasStore){
NumLoopsNoStore++;
}
}
static bool NotALoadOrStore(Instruction* I){
if (isa<LoadInst>(I)){
return false;
}
if (isa<StoreInst>(I)){
return false;
}
return true;
}
static void OptimizeLoop(Function *f, LoopInfoBase<BasicBlock, Loop> *LIBase, Loop *L){
NumLoops++;
BasicBlock *PH = L->getLoopPreheader();
if (PH==NULL){
LICMNoPreheader++;
return;
}
//recursive call to optimize all the subloops
for (auto subloop: L->getSubLoops()){
OptimizeLoop(f, LIBase, subloop);
}
bool changed, hasLoad, hasStore, hasCall, loopContainsStore=false;
std::set<Instruction*> worklist;
hasCall = false;
for (BasicBlock *bb: L->blocks()){
changed = hasLoad = hasStore = false;
for (BasicBlock::iterator i = bb->begin(), e = bb->end(); i != e; ++i){
if (isa<LoadInst>(&*i)){
hasLoad = true;
}
if (isa<StoreInst>(&*i)){
hasStore = true;
loopContainsStore = true;
}
if (isa<CallInst>(&*i)){
hasCall = true;
}
worklist.insert(&*i);
}
updateStats(hasLoad, hasStore);
//work with the worklist;
while (worklist.size() > 0){
changed = false;
Instruction* i = *worklist.begin();
worklist.erase(i);
if (NotALoadOrStore(i)){
if (AreAllOperandsLoopInvaraint(L, i)){
L->makeLoopInvariant(i, changed);
if (changed) {
LICMBasic++;
continue;
}
}
}
else {
if (isa<LoadInst>(i)){
Value* addr = i->getOperand(0); // address for Load instruction
if (CanMoveOutofLoop(f, L, i, addr, loopContainsStore)){
hoistInstructionToPreheader(i, PH);
LICMLoadHoist++;
//Move to PH
}
}
}
}
}
if (hasCall) {NumLoopsWithCall++;}
}
static void RunLICMBasic(Module *M){
for (Module::iterator func = M->begin(); func != M->end(); ++func){
Function &F = *func;
// for empty function, stop considering
if (func->begin() == func->end()){
continue;
}
DominatorTreeBase<BasicBlock,false> *DT=nullptr;
LoopInfoBase<BasicBlock,Loop> *LI = new LoopInfoBase<BasicBlock,Loop>();
DT = new DominatorTreeBase<BasicBlock,false>();
DT->recalculate(F); // dominance for Function, F
LI->analyze(*DT); // calculate loop info
for(auto li: *LI) {
OptimizeLoop(&F, LI, li);
}
}
}
static void LoopInvariantCodeMotion(Module *M) {
RunLICMBasic(M);
}