-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPMRobustness.cpp
More file actions
3400 lines (2921 loc) · 107 KB
/
PMRobustness.cpp
File metadata and controls
3400 lines (2921 loc) · 107 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
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- PMRobustness.cpp - xxx -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a modified version of ThreadSanitizer.cpp, a part of a race detector.
//
// The tool is under development, for the details about previous versions see
// http://code.google.com/p/data-race-test
//
// The instrumentation phase is quite simple:
// - Insert calls to run-time library before every memory access.
// - Optimizations may apply to avoid instrumenting some of the accesses.
// - Insert calls at function entry/exit.
// The rest is handled by the run-time library.
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Constants.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Scalar/SimplifyCFG.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallSet.h"
#include "../../Analysis/CFLTaintAnalysis/CFLAndersTaintAnalysis.h"
#include "FlushUtils.h"
#include "FunctionSummary.h"
#include "PMRobustness.h"
#include "AnnotatedFuncs.h"
#include <cxxabi.h>
//#define PMROBUST_DEBUG
//#define DUMP_CACHED_RESULT
//#define DUMP_INST_STATE
//#define DUMP_BLOCK_STATE
//#define DUMP_BLOCK_DIFF_STATE
#define INTERPROCEDURAL
const std::string DBG_FUNCS[] = {""};
const std::string DBG_BLOCKS[] = {""};
const std::string IGNORE = "ignore";
const std::string FLIT_SHARED_STORE = "flit_shared_store";
const std::string FLIT_LOAD = "flit_load";
const std::string RELEASE_OBJ_FENCE = "release_obj_fence";
const std::string MULTI_OBJ_FENCE = "multi_obj_fence";
const std::string MULTI_FIELD_FENCE = "multi_field_fence";
const std::string PTR_ARITH_FENCE = "ptr_arith_fence";
const std::string FUNC_END_FENCE = "func_end_fence";
const std::string BLOCK_END_FENCE = "block_end_fence";
const std::string SEQ_CST_FENCE = "seq_cst_fence";
inline bool shouldDebug(Function *F) {
return DBG_FUNCS[0]=="" || std::find(std::begin(DBG_FUNCS), std::end(DBG_FUNCS), F->getName().str()) != std::end(DBG_FUNCS);
}
inline bool shouldDebug(BasicBlock *B) {
return DBG_BLOCKS[0]=="" || std::find(std::begin(DBG_BLOCKS), std::end(DBG_BLOCKS), B->getName().str()) != std::end(DBG_BLOCKS);
}
enum FlushInsMode {
NO_FLUSH, OPTIMIZED, NAIVE
};
cl::opt<FlushInsMode> FlushInsertMode("insert-flush", cl::desc("Choose mode of flush insertion:"),
cl::values(
clEnumValN(NO_FLUSH, "none", "no flush insertion"),
clEnumValN(OPTIMIZED, "opt", "optimized flush insertion based on flush state tracking"),
clEnumValN(NAIVE, "naive", "naive flush insertion")
),
cl::init(NO_FLUSH));
cl::opt<bool> Flit("flit", cl::desc("Use flit transformation"));
cl::opt<bool> BlockEndFence("block-end-fence", cl::desc("Insert fence when block a block that needs a fence merges with other blocks that don't"));
int getAtomicOrderIndex(AtomicOrdering order) {
switch (order) {
case AtomicOrdering::Monotonic:
return (int)AtomicOrderingCABI::relaxed;
//case AtomicOrdering::Consume: // not specified yet
// return AtomicOrderingCABI::consume;
case AtomicOrdering::Acquire:
return (int)AtomicOrderingCABI::acquire;
case AtomicOrdering::Release:
return (int)AtomicOrderingCABI::release;
case AtomicOrdering::AcquireRelease:
return (int)AtomicOrderingCABI::acq_rel;
case AtomicOrdering::SequentiallyConsistent:
return (int)AtomicOrderingCABI::seq_cst;
default:
// unordered or Not Atomic
return -1;
}
}
static inline bool isUnsafeState(ob_state_t *state) {
return (state->isDirty() || state->isClwb()) && state->isEscaped();
}
static inline std::string demangle(const StringRef ref) {
char* demangled;
if ((demangled = abi::__cxa_demangle(ref.begin(), 0, 0, NULL))) {
auto s = std::string(demangled);
free(demangled);
return s;
}
return ref.str();
}
namespace {
struct PMRobustness : public ModulePass {
PMRobustness() : ModulePass(ID) {}
StringRef getPassName() const override;
bool doInitialization(Module &M) override;
bool runOnModule(Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
void analyzeFunction(Function &F, CallingContext *Context);
static char ID;
CFLAndersTaintResult *CFL;
private:
void copyState(state_t * src, state_t * dst);
void copyArrayState(addr_set_t &src, addr_set_t &dst);
bool copyStateCheckDiff(state_t * src, state_t * dst);
void copyMergedState(state_map_t *AbsState, SmallSetVector<BasicBlock *, 8> &src_list, state_t * dst);
void copyMergedArrayState(DenseMap<BasicBlock *, addr_set_t> &ArraySets,
SmallSetVector<BasicBlock *, 8> &src_list, addr_set_t &dst);
void processInstruction(state_t * map, Instruction * I);
bool processAtomic(state_t * map, Instruction * I, bool &report_release_error);
bool processMemIntrinsic(state_t * map, Instruction * I);
bool processLoad(state_t * map, Instruction * I);
bool processStore(state_t * map, Instruction * I);
bool processPHI(state_t * map, Instruction * I);
bool processSelect(state_t * map, Instruction * I);
bool processFence(state_t * map, Instruction * I);
void processMutexUnlock(state_t * map, Instruction * I);
void processFlush(state_t *map, Instruction *I, NVMOP op);
void processInFunctionAnnotation(Instruction *I);
bool processAnnotatedFunction(state_t *map, Instruction *I, bool &check_error);
void processFlushWrapperFunction(state_t *map, Instruction * I);
void processFlushParameterFunction(state_t *map, Instruction * I);
void processReturnAnnotation(state_t *map, Instruction *I);
void processPMMemcpy(state_t *map, Instruction *I);
void processCalls(state_t *map, Instruction *I, bool &non_dirty_escaped_before, bool &report_release_error);
void getAnnotatedParamaters(std::string attr, std::vector<StringRef> &annotations, Function *callee);
bool skipAnnotatedInstruction(Instruction *I);
bool skipFunction(Function &F);
// TODO: Address check to be implemented
bool isPMAddr(const Function *F, const Value * Addr, const DataLayout &DL);
bool mayInHeap(const Value * Addr);
ob_state_t * getObjectState(state_t *map, const Value *Addr, bool &updated);
ob_state_t * getObjectState(state_t *map, const Value *Addr);
void removeNVMOp(Instruction *I);
void preprocessDirtyObj(Instruction *I, const DataLayout &DL);
void preprocessInsts(Module &M);
void fenceIfDifferentClwbStates(SmallSetVector<BasicBlock *, 8> &pred_list, state_map_t *AbsState);
CallInst *fenceAndChangeState(Instruction *I, state_t *state);
void checkEndError(state_map_t *AbsState, Function &F);
bool checkUnsafeObj(state_t *map, Instruction *I, bool non_dirty_escaped_before);
void checkMultiObjError(state_t *map, Instruction *I, bool non_dirty_escaped_before);
void checkReleaseError(state_t *map, Instruction *I);
void reportMultipleEscDirtyFieldsError(state_t *map, Instruction *I);
void decomposeAddress(DecomposedGEP &DecompGEP, Value *Addr, const DataLayout &DL);
unsigned getMemoryAccessSize(Value *Addr, const DataLayout &DL);
unsigned getFieldSize(Value *Addr, const DataLayout &DL);
NVMOP whichNVMoperation(Instruction *I);
NVMOP whichNVMoperation(StringRef flushtype);
NVMOP analyzeFlushType(Function &F);
bool isInFunctionAnnotation(Instruction *I);
bool isFunctionAnnotated(Instruction *I);
bool isFunctionAnnotated(Function &F);
bool isFlushWrapperFunction(Instruction *I);
bool isMutexLock(Instruction *I);
bool isMutexUnlock(Instruction *I);
addr_set_t * getUnflushedAddrSet(Function *F, BasicBlock *B);
bool checkUnflushedAddress(Function *F, addr_set_t * AddrSet, Value * Addr, NVMOP op);
bool checkPointerArithmetics(Value *Addr, const DataLayout &DL);
bool compareDecomposedGEP(DecomposedGEP &GEP1, DecomposedGEP &GEP2);
CallingContext * computeContext(state_t *map, Instruction *I);
void lookupFunctionResult(state_t *map, CallBase *CB, CallingContext *Context,
bool &non_dirty_escaped_before, bool &report_release_error);
void computeInitialState(state_t *map, Function &F, CallingContext *Context);
bool computeFinalState(state_map_t *AbsState, Function &F, CallingContext *Context);
FunctionSummary * getOrCreateFunctionSummary(Function *F);
void makeParametersTOP(state_t *map, CallBase *CB);
void modifyReturnState(state_t *map, CallBase *CB, OutputState *out_state);
alias_set_t * getFunctionAliasSet(Function *F);
value_set_t * getValueAliasSet(Function *F, Value *V);
void computeAliasSet(PHINode *PHI);
const Value * GetLinearExpression(
const Value *V, APInt &Scale, APInt &Offset, unsigned &ZExtBits,
unsigned &SExtBits, const DataLayout &DL, unsigned Depth,
AssumptionCache *AC, DominatorTree *DT, bool &NSW, bool &NUW
);
bool DecomposeGEPExpression(const Value *V, DecomposedGEP &Decomposed,
const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT
);
void printMap(state_t * map);
void test();
// object states at the end of each instruction for each function
DenseMap<const Function *, state_map_t> AbstractStates;
// object states at the end of each basic block for each function
DenseMap<const Function *, b_state_map_t> BlockEndAbstractStates;
/* typedef DenseMap<const Value *, ArrayInfo> addr_set_t; */
DenseMap<const Function *, DenseMap<BasicBlock *, addr_set_t>> UnflushedArrays;
DenseMap<const Function *, FunctionSummary> FunctionSummaries;
DenseMap<const Function *, SmallPtrSet<Instruction *, 8>> FunctionRetInstMap;
// atomic RMW (CAS), seq_cst load, concurrency fence, mutex lock
DenseMap<const Function *, DenseMap<const BasicBlock *, bool>> FenceAnalysisMap;
CallingContext *CurrentContext;
// Arguments of the function being analyzed
DenseMap<const Value *, unsigned> FunctionArguments;
// Map a Function to its call sites
DenseMap<Function *, SetVector<std::pair<Function *, CallingContext *>> > FunctionCallerMap;
DenseMap<const Function*, DenseSet<Value *>> PMAddrSets;
std::list<std::pair<Function *, CallingContext *>> FunctionWorklist;
// The set of items in FunctionWorklist; used to avoid insert duplicate items to FunctionWorklist
DenseSet<std::pair<Function *, CallingContext *>> UniqueFunctionSet;
DenseMap<const BasicBlock *, bool> visited_blocks;
std::list<BasicBlock *> BlockWorklist;
DenseMap<const Function *, DenseSet<const Value *>> FunctionEndErrorSets;
DenseMap<const Function *, DenseSet<const Instruction *>> FunctionStmtErrorSets;
DenseSet<const Instruction *> * StmtErrorSet;
bool HasTwoUnsafeParams;
bool InstructionMarksEscDirObj; // Instruction: current instruction
bool FunctionMarksEscDirObj; // Function: this function
// Call: this call instruction marks any object as dirty and escaped when no parameters are dirty and escaped;
bool CallMarksEscDirObj;
std::string MultiUnsafeFieldsPrevPos;
unsigned MaxLookupSearchDepth = 100;
std::vector<StringRef> AnnotationList;
DenseMap<const Function *, alias_set_t *> FunctionAliasSet;
LLVMContext *Ctx;
Function *VarSizedFlush;
Function *GetFlitCounter;
IntegerType *FlitCounterType;
};
}
StringRef PMRobustness::getPassName() const {
return "PMRobustness";
}
static Function *checkPMRobustInterfaceFunction(Value *FuncOrBitcast) {
if (isa<Function>(FuncOrBitcast))
return cast<Function>(FuncOrBitcast);
FuncOrBitcast->print(errs());
errs() << '\n';
std::string Err;
raw_string_ostream Stream(Err);
Stream << "PMRobust interface function redefined: " << *FuncOrBitcast;
report_fatal_error(Err);
}
/* annotations -> myflush:[addr|size|ignore] */
bool PMRobustness::doInitialization (Module &M) {
Ctx = &M.getContext();
PointerType *ptrType = Type::getInt8PtrTy(*Ctx);
IntegerType *int64Type = Type::getInt64Ty(*Ctx);
IntegerType *int32Type = Type::getInt32Ty(*Ctx);
Type *voidType = Type::getVoidTy(*Ctx);
VarSizedFlush = checkPMRobustInterfaceFunction(M.getOrInsertFunction("my_clflush", voidType, ptrType, int32Type));
if (Flit) {
FlitCounterType = int64Type;
GetFlitCounter = checkPMRobustInterfaceFunction(M.getOrInsertFunction("get_flit_counter", FlitCounterType->getPointerTo(), ptrType));
}
AnnotationList = {
"myflush", "flush_parameter", "preprocess_ignore", "ignore", "suppress", "return",
"persist_memcpy"
};
GlobalVariable *global_annos = M.getNamedGlobal("llvm.global.annotations");
if (global_annos) {
ConstantArray *a = cast<ConstantArray>(global_annos->getOperand(0));
for (unsigned i=0; i < a->getNumOperands(); i++) {
ConstantStruct *e = cast<ConstantStruct>(a->getOperand(i));
if (Function *fn = dyn_cast<Function>(e->getOperand(0)->getOperand(0))) {
StringRef anno = cast<ConstantDataArray>(cast<GlobalVariable>(e->getOperand(1)->getOperand(0))->getOperand(0))->getAsCString();
std::pair<StringRef, StringRef> Split = anno.split(":");
fn->addFnAttr(Split.first, Split.second);
}
}
}
for (auto &pair: AnnotatedFuncs) {
if (auto *fn = M.getFunction(pair.first)) {
StringRef anno = pair.second;
std::pair<StringRef, StringRef> Split = anno.split(":");
fn->addFnAttr(Split.first, Split.second);
}
}
return true;
}
void PMRobustness::removeNVMOp(Instruction *I) {
if (I->isTerminator()) {
auto II = cast<InvokeInst>(I); //only invoke instruction should be possible
auto BI = BranchInst::Create(II->getNormalDest(), II);
}
I->eraseFromParent();
}
void PMRobustness::preprocessDirtyObj(Instruction *I, const DataLayout &DL) {
Value *Addr = nullptr;
Value *Size = nullptr;
IRBuilder<> builder(I->getNextNode());
bool shouldFence = FlushInsertMode == NAIVE;
if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
auto atomic_order_index = getAtomicOrderIndex(SI->getOrdering());
//allow flush to be inserted before the seq_cst fence
if (atomic_order_index == (int)AtomicOrderingCABI::seq_cst) {
SI->setOrdering(AtomicOrdering::Release);
if (!Flit)
shouldFence = true;
}
Addr = SI->getPointerOperand();
} else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
Addr = RMWI->getPointerOperand();
} else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
Addr = CASI->getPointerOperand();
} else if (I->isAtomic() && isa<LoadInst>(I)) {
Addr = cast<LoadInst>(I)->getPointerOperand();
} else if (auto MI = dyn_cast<MemIntrinsic>(I)) {
Addr = MI->getRawDest();
Size = MI->getLength();
} else if (auto CB = dyn_cast<CallBase>(I)) {
//PMMemcpy
auto callee = CB->getCalledFunction();
if (!callee || !callee->hasFnAttribute("persist_memcpy"))
return;
std::vector<StringRef> annotations;
getAnnotatedParamaters("persist_memcpy", annotations, callee);
unsigned i = std::find(annotations.begin(), annotations.end(), "addr") - annotations.begin();
unsigned j = std::find(annotations.begin(), annotations.end(), "size") - annotations.begin();
if (i > annotations.size() || j > annotations.size())
return;
Addr = CB->getArgOperand(i);
Size = CB->getArgOperand(j);
} else
return;
if (!Addr->getType()->isPointerTy() || !isPMAddr(I->getFunction(), Addr, DL))
return;
DILocation *loc = I->getDebugLoc();
MDNode *N = MDNode::get(*Ctx, None);
if (I->isAtomic() && isa<LoadInst>(I) && Flit) {
Value *AddrCast = builder.CreatePointerCast(Addr, GetFlitCounter->getFunctionType()->getParamType(0));
CallInst *call = builder.CreateCall(GetFlitCounter, {AddrCast}, "flit_counter");
call->setDebugLoc(loc);
LoadInst *load = builder.CreateLoad(FlitCounterType, call);
load->setOrdering(AtomicOrdering::SequentiallyConsistent);
load->setAlignment(FlitCounterType->getBitWidth());
Value *cond = builder.CreateICmpNE(load, ConstantInt::get(*Ctx, APInt(FlitCounterType->getBitWidth(), 0)), "flit_load_cond");
Instruction *thenTerm = SplitBlockAndInsertIfThen(cond, &*builder.GetInsertPoint(), false);
builder.SetInsertPoint(thenTerm);
I->setMetadata(FLIT_LOAD, N);
} else if (I->isAtomic() && !isa<LoadInst>(I) && Flit) {
builder.SetInsertPoint(I);
Value *AddrCast = builder.CreatePointerCast(Addr, GetFlitCounter->getFunctionType()->getParamType(0));
CallInst *call = builder.CreateCall(GetFlitCounter, {AddrCast}, "flit_counter");
call->setDebugLoc(loc);
ConstantInt *constOne = ConstantInt::get(*Ctx, APInt(FlitCounterType->getBitWidth(), 1));
builder.CreateAtomicRMW(AtomicRMWInst::Add, call, constOne, AtomicOrdering::SequentiallyConsistent);
builder.SetInsertPoint(I->getNextNode());
auto fsub = builder.CreateAtomicRMW(AtomicRMWInst::Sub, call, constOne, AtomicOrdering::SequentiallyConsistent);
builder.SetInsertPoint(fsub);
I->setMetadata(FLIT_SHARED_STORE, N);
}
if (Size && (!isa<ConstantInt>(Size) || cast<ConstantInt>(Size)->getZExtValue() >= MAX_RANGE_FLUSH)) {
Value *cast = builder.CreateIntCast(Size, VarSizedFlush->getFunctionType()->getParamType(1), false);
CallInst *call = builder.CreateCall(VarSizedFlush, {Addr, cast});
call->setDebugLoc(loc);
} else if (Size && isa<ConstantInt>(Size)) {
unsigned size = cast<ConstantInt>(Size)->getZExtValue();
insertFlushRange(builder, Addr, 0, size);
} else {
unsigned size = getMemoryAccessSize(Addr, DL);
insertFlushRange(builder, Addr, 0, size);
}
if (shouldFence) {
MDNode *N = MDNode::get(*Ctx, None);
auto fence = insertSFence(builder);
fence->setMetadata(SEQ_CST_FENCE, N);
}
}
void PMRobustness::preprocessInsts(Module &M) {
const DataLayout &DL = M.getDataLayout();
for (Function &F : M) {
int i = 0;
if (F.hasFnAttribute("preprocess_ignore") || F.hasFnAttribute("ignore"))
continue;
for (auto FItr = F.begin(); FItr != F.end();) {
BasicBlock *BB = &*FItr;
FItr++;
for (auto BItr = BB->begin(); BItr != BB->end();) {
Instruction *I = &*BItr;
BItr++;
//instructions and blocks may be inserted before BItr
if (skipAnnotatedInstruction(I)) {
continue;
} else if (isInFunctionAnnotation(I)) {
processInFunctionAnnotation(I);
} else if (isFlushWrapperFunction(I) || whichNVMoperation(I) != NVM_UNKNOWN) {
removeNVMOp(I);
} else if (!I->isTerminator()) {
preprocessDirtyObj(I, DL);
if (BItr->getParent() != BB)
BB = BItr->getParent();
}
}
}
}
}
void PMRobustness::fenceIfDifferentClwbStates(SmallSetVector<BasicBlock *, 8> &pred_list, state_map_t *AbsState) {
auto hasClwbState = [&](BasicBlock *block){
if (!visited_blocks[block])
return false;
auto itr = AbsState->find(block->getTerminator());
if (itr == AbsState->end())
return false;
for (auto &pair: itr->second) {
if (pair.second->isClwb()) {
return true;
}
}
return false;
};
SmallSetVector<BasicBlock *, 8> clwbBlocks;
for (auto block: pred_list)
if (hasClwbState(block)) {
clwbBlocks.insert(block);
}
if (clwbBlocks.size() < pred_list.size()) {
SmallSetVector<BasicBlock *, 8> succ_list;
for (auto block: clwbBlocks) {
auto terminator = block->getTerminator();
auto state = &(*AbsState)[terminator];
auto fence = fenceAndChangeState(terminator, state);
MDNode *N = MDNode::get(*Ctx, None);
fence->setMetadata(BLOCK_END_FENCE, N);
for (BasicBlock *succ: successors(block)) {
succ_list.insert(succ);
}
}
for (BasicBlock *succ : succ_list) {
BlockWorklist.push_back(succ);
}
}
}
CallInst *PMRobustness::fenceAndChangeState(Instruction *I, state_t *state) {
//errs() << "insert fence before " << *I << "\n";
IRBuilder<> builder(I);
auto fence = insertSFence(builder);
processFence(state, fence);
return fence;
}
bool PMRobustness::runOnModule(Module &M) {
const DataLayout &DL = M.getDataLayout();
CFL = &getAnalysis<CFLAndersTaintWrapperPass>().getResult();
if (FlushInsertMode == NAIVE) {
preprocessInsts(M);
return true;
}
if (FlushInsertMode == OPTIMIZED) {
}
for (Function &F : M) {
#ifdef INTERPROCEDURAL
if (F.getName() == "main") {
// Function has parameters
CallingContext *Context = new CallingContext();
for (unsigned i = 0; i < F.arg_size(); i++)
Context->addAbsInput(ParamStateType::NON_PMEM);
FunctionWorklist.emplace_back(&F, Context);
UniqueFunctionSet.insert(std::make_pair(&F, Context));
} else if (!F.isDeclaration()) {
// Assume parameters have states TOP or do not push them to worklist?
CallingContext *Context = new CallingContext();
for (Function::arg_iterator it = F.arg_begin(); it != F.arg_end(); it++) {
Argument *Arg = &*it;
if (Arg->getType()->isPointerTy())
Context->addAbsInput(ParamStateType::TOP);
else
Context->addAbsInput(ParamStateType::NON_PMEM);
}
FunctionWorklist.emplace_back(&F, Context);
UniqueFunctionSet.insert(std::make_pair(&F, Context));
} else {
// F.isDeclaration
//errs() << F.getName() << " isDeclaration ignored in Module " << M.getName() << "\n";
#ifdef PMROBUST_DEBUG
errs() << "{" << F.empty() << "," << !F.isMaterializable() << "}\n";
errs() << F.getName() << " isDeclaration ignored\n";
#endif
}
#else
if (!F.isDeclaration())
FunctionWorklist.emplace_back(&F, new CallingContext());
#endif
}
while (!FunctionWorklist.empty()) {
std::pair<Function *, CallingContext *> &pair = FunctionWorklist.front();
FunctionWorklist.pop_front();
UniqueFunctionSet.erase(pair);
Function *F = pair.first;
CallingContext *context = pair.second;
if (skipFunction(*F)) {
continue;
}
errs() << "processing " << F->getName() << "\n";
analyzeFunction(*F, context);
delete context;
}
return true;
}
void PMRobustness::analyzeFunction(Function &F, CallingContext *Context) {
#ifdef DUMP_INST_STATE
if (shouldDebug(&F)) {
F.dump();
errs() << "Analyzing Function " << F.getName() << " with Context: \n";
Context->dump();
}
#endif
state_map_t *AbsState = &AbstractStates[&F];
b_state_map_t *BlockAbsState = &BlockEndAbstractStates[&F];
DenseMap<BasicBlock *, addr_set_t> &ArraySets = UnflushedArrays[&F];
StmtErrorSet = &FunctionStmtErrorSets[&F];
#ifdef INTERPROCEDURAL
CurrentContext = Context;
FunctionArguments.clear();
unsigned i = 0;
for (Function::arg_iterator it = F.arg_begin(); it != F.arg_end(); it++) {
FunctionArguments[&*it] = i++;
}
// Check if two or more parameters are unsafe (i.e. escaped and dirty/clwb)
HasTwoUnsafeParams = false;
bool has_unsafe_objs = false;
for (unsigned i = 0; i < F.arg_size(); i++) {
ParamState &PS = Context->getState(i);
if (PS.isEscaped() && (PS.isDirty() || PS.isClwb())) {
if (has_unsafe_objs) {
HasTwoUnsafeParams = true;
break;
}
has_unsafe_objs = true;
}
}
#endif
// Collect all return statements of Function F
SmallPtrSet<Instruction *, 8> &RetSet = FunctionRetInstMap[&F];
if (RetSet.empty()) {
for (BasicBlock &BB : F) {
if (!BB.getTerminator())
errs() << "malformed BB: " << BB << "\n";
if (isa<ReturnInst>(BB.getTerminator()))
RetSet.insert(BB.getTerminator());
}
}
DenseMap<const BasicBlock *, bool> &fence_analysis = FenceAnalysisMap[&F];
fence_analysis.clear();
// LLVM allows duplicate predecessors: https://stackoverflow.com/questions/65157239/llvmpredecessors-could-return-duplicate-basic-block-pointers
DenseMap<const BasicBlock *, SmallSetVector<BasicBlock *, 8>> block_predecessors;
DenseMap<const BasicBlock *, SmallSetVector<BasicBlock *, 8>> block_successors;
FunctionMarksEscDirObj = false;
visited_blocks.clear();
// Analyze F
BlockWorklist.push_back(&F.getEntryBlock());
while (!BlockWorklist.empty()) {
BasicBlock *block = BlockWorklist.front();
BlockWorklist.pop_front();
BasicBlock::iterator prev = block->begin(), next = block->begin();
addr_set_t &array_addr_set = ArraySets[block];
for (BasicBlock::iterator it = block->begin(); it != block->end(); it++) {
//keep track of next iterator as instructions could be inserted after the current iterator
state_t * state = &(*AbsState)[&*it];
// Build state from predecessors' states
if (it == block->begin()) {
// First instruction; take the union of predecessors' states
if (block == &F.getEntryBlock()) {
// Entry block: has no precedessors
// Prepare initial state based on parameters
#ifdef INTERPROCEDURAL
computeInitialState(state, F, Context);
#endif
} else if (BasicBlock *pred = block->getUniquePredecessor()) {
// Unique predecessor; copy the state of last instruction and unflushed arrays in the pred block
state_t * prev_s = &(*AbsState)[pred->getTerminator()];
// Safety check
if (!visited_blocks[pred])
assert(false);
copyState(prev_s, state);
copyArrayState(ArraySets[pred], array_addr_set);
fence_analysis[block] = fence_analysis[pred];
} else {
// Multiple predecessors
SmallSetVector<BasicBlock *, 8> &pred_list = block_predecessors[block];
if (pred_list.empty()) {
for (BasicBlock *pred : predecessors(block)) {
pred_list.insert(pred);
}
}
// Safety check
bool visited_any = false;
for (BasicBlock *pred : pred_list) {
if (visited_blocks[pred]) {
visited_any = true;
break;
}
}
if (!visited_any)
assert(false);
if (BlockEndFence && FlushInsertMode == OPTIMIZED)
fenceIfDifferentClwbStates(pred_list, AbsState);
copyMergedState(AbsState, pred_list, state);
copyMergedArrayState(ArraySets, pred_list, array_addr_set);
// Merge the fence_state in predecessors
bool fence_state = true;
for (BasicBlock *pred: pred_list) {
fence_state &= fence_analysis[pred];
}
fence_analysis[block] = fence_state;
}
} else {
// Copy the previous instruction's state
copyState(&(*AbsState)[&*prev], state);
}
processInstruction(state, &*it);
prev = it;
} // End of basic block instruction iteration
// Copy block terminator's state and check if it has changed
state_t *terminator_state = &(*AbsState)[block->getTerminator()];
state_t *block_end_state = &(*BlockAbsState)[block];
#ifdef DUMP_BLOCK_STATE
if (shouldDebug(&F) && shouldDebug(block)) {
errs() << "------ Block " << block->getName() << " end state before------\n";
printMap(block_end_state);
}
#endif
bool block_state_changed = copyStateCheckDiff(terminator_state, block_end_state);
#ifdef DUMP_BLOCK_STATE
if (shouldDebug(&F) && shouldDebug(block)) {
errs() << "------- After ------\n";
printMap(block_end_state);
}
#endif
// Push block successors to BlockWorklist if block state has changed
// or it is the first time we visit this block
if (block_state_changed || !visited_blocks[block]) {
visited_blocks[block] = true;
SmallSetVector<BasicBlock *, 8> &succ_list = block_successors[block];
if (succ_list.empty()) {
for (BasicBlock *succ : successors(block)) {
succ_list.insert(succ);
}
}
for (BasicBlock *succ : succ_list) {
BlockWorklist.push_back(succ);
}
}
}
#ifdef INTERPROCEDURAL
// Only verify if output states have been changed
bool state_changed = computeFinalState(AbsState, F, Context);
if (state_changed) {
// push callers with their contexts
SetVector<std::pair<Function *, CallingContext *>> &Callers = FunctionCallerMap[&F];
for (const std::pair<Function *, CallingContext *> &C : Callers) {
if (UniqueFunctionSet.find(C) == UniqueFunctionSet.end()) {
// Not found in FunctionWorklist
Function *Function = C.first;
CallingContext *CallerContext = new CallingContext(C.second);
FunctionWorklist.emplace_back(Function, CallerContext);
UniqueFunctionSet.insert(std::make_pair(Function, CallerContext));
//errs() << "(LOG4) Function " << Function->getName() << " added to worklist in " << F.getName() << "\n";
}
}
}
#endif
}
// DenseMap<Value *, ob_state_t *> state_t;
void PMRobustness::copyState(state_t * src, state_t * dst) {
// Mark each item in dst as `to delete`; they are unmarked if src contains them
for (state_t::iterator it = dst->begin(); it != dst->end(); it++)
it->second->markDelete();
for (state_t::iterator it = src->begin(); it != src->end(); it++) {
ob_state_t *object_state = dst->lookup(it->first);
if (object_state == NULL) {
object_state = new ob_state_t(it->second);
(*dst)[it->first] = object_state;
} else {
// if (object_state->size != it->second->size) {
// errs() << "dst size: " << object_state->size << "\t";
// errs() << "src size: " << it->second->size << "\n";
// }
object_state->copyFrom(it->second);
object_state->unmarkDelete();
}
}
// Remove items not contained in src
for (state_t::iterator it = dst->begin(); it != dst->end(); it++) {
if (it->second->shouldDelete()) {
delete it->second;
dst->erase(it);
}
}
}
void PMRobustness::copyArrayState(addr_set_t &src, addr_set_t &dst) {
for (addr_set_t::iterator it = src.begin(); it != src.end(); it++) {
ArrayInfo &info = dst[it->first];
info.copyFrom(it->second);
}
}
bool PMRobustness::copyStateCheckDiff(state_t * src, state_t * dst) {
bool updated = false;
// Mark each item in dst as `to delete`; they are unmarked if src contains them
for (state_t::iterator it = dst->begin(); it != dst->end(); it++)
it->second->markDelete();
for (state_t::iterator it = src->begin(); it != src->end(); it++) {
ob_state_t *object_state = dst->lookup(it->first);
if (object_state == NULL) {
// mark_delete is initialized to false;
object_state = new ob_state_t(it->second);
(*dst)[it->first] = object_state;
updated = true;
} else {
#ifdef DUMP_BLOCK_DIFF_STATE
auto before = *object_state;
#endif
bool diff = object_state->copyFromCheckDiff(it->second);
#ifdef DUMP_BLOCK_DIFF_STATE
if (diff) {
errs() << "------ Val " << *it->first << " state before------\n";
object_state->dump();
errs() << "----- After ------\n";
before.dump();
}
#endif
updated |= diff;
object_state->unmarkDelete();
}
}
// Remove items not contained in src
for (state_t::iterator it = dst->begin(); it != dst->end(); it++) {
if (it->second->shouldDelete()) {
delete it->second;
dst->erase(it);
updated = true;
}
}
return updated;
}
void PMRobustness::copyMergedState(state_map_t *AbsState,
SmallSetVector<BasicBlock *, 8> &src_list, state_t * dst) {
for (state_t::iterator it = dst->begin(); it != dst->end(); it++) {
it->second->setSize(0);
it->second->markDelete();
}
for (BasicBlock *pred : src_list) {
if (!visited_blocks[pred]) {
continue;
}
state_t *s = &(*AbsState)[pred->getTerminator()];
//DenseMap<Value *, ob_state_t *> state_t;
for (state_t::iterator it = s->begin(); it != s->end(); it++) {
state_t::iterator item = dst->find(it->first);
if (item != dst->end()) {
// (Loc, vector<VarState>) pair found
ob_state_t *A = item->second;
ob_state_t *B = it->second;
if (A->getSize() == 0) {
A->copyFrom(B);
} else {
A->mergeFrom(B);
}
A->unmarkDelete();
} else {
(*dst)[it->first] = new ob_state_t(it->second);
}
}
}
// Remove items not contained in src
for (state_t::iterator it = dst->begin(); it != dst->end(); it++) {
if (it->second->shouldDelete()) {
delete it->second;
dst->erase(it);
}
}
}
void PMRobustness::copyMergedArrayState(DenseMap<BasicBlock *, addr_set_t> &ArraySets,
SmallSetVector<BasicBlock *, 8> &src_list, addr_set_t &dst) {
for (BasicBlock *pred : src_list) {
if (!visited_blocks[pred]) {
continue;
}
addr_set_t &s = ArraySets[pred];
//DenseMap<const Value *, ArrayInfo> addr_set_t;
for (addr_set_t::iterator it = s.begin(); it != s.end(); it++) {
addr_set_t::iterator item = dst.find(it->first);
if (item != dst.end()) {
// (Loc, vector<VarState>) pair found
ArrayInfo &A = item->second;
A.mergeFrom(it->second);
} else {
ArrayInfo &A = dst[it->first];
A.copyFrom(it->second);
}
}
}
}
void PMRobustness::processInstruction(state_t * map, Instruction * I) {
#ifdef DUMP_INST_STATE
if (shouldDebug(I->getFunction()) && shouldDebug(I->getParent())) {
errs() << "Before " << *I << "\n\n";
printMap(map);
}
#endif
InstructionMarksEscDirObj = false;
CallMarksEscDirObj = false;
MultiUnsafeFieldsPrevPos = "";
bool updated = false;
bool check_error = false;
bool non_dirty_escaped_before_call = true;
bool report_release_error = false;
if (skipAnnotatedInstruction(I)) {
return;
}
if (I->isAtomic()) {
processAtomic(map, I, report_release_error);
check_error = true;
} else if (isa<LoadInst>(I)) {
processLoad(map, I);
//TODO: figure out the performance implication of this
//check_error = true;
} else if (isa<StoreInst>(I)) {
processStore(map, I);
check_error = true;
} else if (isa<PHINode>(I)) {
processPHI(map, I);
} else if (isa<SelectInst>(I)) {
processSelect(map, I);
} else if (isMutexLock(I)) {
// mutex lock is usually implemented with RMW; cite the x86 PM semantics paper
processFence(map, I);
} else if (isMutexUnlock(I)) {
processMutexUnlock(map, I);
report_release_error = true;
} else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
// Ignore Debug info Instrinsics
if (isa<DbgInfoIntrinsic>(I)) {
return;
} else if (isa<MemIntrinsic>(I)) {
processMemIntrinsic(map, I);
check_error = true;
} else if (isInFunctionAnnotation(I)) {
processInFunctionAnnotation(I);
} else if (isFunctionAnnotated(I)) {
processAnnotatedFunction(map, I, check_error);
} else {
NVMOP op = whichNVMoperation(I);
if (op == NVM_FENCE) {
// TODO: fence operations