-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
Attributor.h
2859 lines (2403 loc) · 112 KB
/
Attributor.h
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
//===- Attributor.h --- Module-wide attribute deduction ---------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Attributor: An inter procedural (abstract) "attribute" deduction framework.
//
// The Attributor framework is an inter procedural abstract analysis (fixpoint
// iteration analysis). The goal is to allow easy deduction of new attributes as
// well as information exchange between abstract attributes in-flight.
//
// The Attributor class is the driver and the link between the various abstract
// attributes. The Attributor will iterate until a fixpoint state is reached by
// all abstract attributes in-flight, or until it will enforce a pessimistic fix
// point because an iteration limit is reached.
//
// Abstract attributes, derived from the AbstractAttribute class, actually
// describe properties of the code. They can correspond to actual LLVM-IR
// attributes, or they can be more general, ultimately unrelated to LLVM-IR
// attributes. The latter is useful when an abstract attributes provides
// information to other abstract attributes in-flight but we might not want to
// manifest the information. The Attributor allows to query in-flight abstract
// attributes through the `Attributor::getAAFor` method (see the method
// description for an example). If the method is used by an abstract attribute
// P, and it results in an abstract attribute Q, the Attributor will
// automatically capture a potential dependence from Q to P. This dependence
// will cause P to be reevaluated whenever Q changes in the future.
//
// The Attributor will only reevaluate abstract attributes that might have
// changed since the last iteration. That means that the Attribute will not
// revisit all instructions/blocks/functions in the module but only query
// an update from a subset of the abstract attributes.
//
// The update method `AbstractAttribute::updateImpl` is implemented by the
// specific "abstract attribute" subclasses. The method is invoked whenever the
// currently assumed state (see the AbstractState class) might not be valid
// anymore. This can, for example, happen if the state was dependent on another
// abstract attribute that changed. In every invocation, the update method has
// to adjust the internal state of an abstract attribute to a point that is
// justifiable by the underlying IR and the current state of abstract attributes
// in-flight. Since the IR is given and assumed to be valid, the information
// derived from it can be assumed to hold. However, information derived from
// other abstract attributes is conditional on various things. If the justifying
// state changed, the `updateImpl` has to revisit the situation and potentially
// find another justification or limit the optimistic assumes made.
//
// Change is the key in this framework. Until a state of no-change, thus a
// fixpoint, is reached, the Attributor will query the abstract attributes
// in-flight to re-evaluate their state. If the (current) state is too
// optimistic, hence it cannot be justified anymore through other abstract
// attributes or the state of the IR, the state of the abstract attribute will
// have to change. Generally, we assume abstract attribute state to be a finite
// height lattice and the update function to be monotone. However, these
// conditions are not enforced because the iteration limit will guarantee
// termination. If an optimistic fixpoint is reached, or a pessimistic fix
// point is enforced after a timeout, the abstract attributes are tasked to
// manifest their result in the IR for passes to come.
//
// Attribute manifestation is not mandatory. If desired, there is support to
// generate a single or multiple LLVM-IR attributes already in the helper struct
// IRAttribute. In the simplest case, a subclass inherits from IRAttribute with
// a proper Attribute::AttrKind as template parameter. The Attributor
// manifestation framework will then create and place a new attribute if it is
// allowed to do so (based on the abstract state). Other use cases can be
// achieved by overloading AbstractAttribute or IRAttribute methods.
//
//
// The "mechanics" of adding a new "abstract attribute":
// - Define a class (transitively) inheriting from AbstractAttribute and one
// (which could be the same) that (transitively) inherits from AbstractState.
// For the latter, consider the already available BooleanState and
// {Inc,Dec,Bit}IntegerState if they fit your needs, e.g., you require only a
// number tracking or bit-encoding.
// - Implement all pure methods. Also use overloading if the attribute is not
// conforming with the "default" behavior: A (set of) LLVM-IR attribute(s) for
// an argument, call site argument, function return value, or function. See
// the class and method descriptions for more information on the two
// "Abstract" classes and their respective methods.
// - Register opportunities for the new abstract attribute in the
// `Attributor::identifyDefaultAbstractAttributes` method if it should be
// counted as a 'default' attribute.
// - Add sufficient tests.
// - Add a Statistics object for bookkeeping. If it is a simple (set of)
// attribute(s) manifested through the Attributor manifestation framework, see
// the bookkeeping function in Attributor.cpp.
// - If instructions with a certain opcode are interesting to the attribute, add
// that opcode to the switch in `Attributor::identifyAbstractAttributes`. This
// will make it possible to query all those instructions through the
// `InformationCache::getOpcodeInstMapForFunction` interface and eliminate the
// need to traverse the IR repeatedly.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TRANSFORMS_IPO_ATTRIBUTOR_H
#define LLVM_TRANSFORMS_IPO_ATTRIBUTOR_H
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumeBundleQueries.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/CGSCCPassManager.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/InlineCost.h"
#include "llvm/Analysis/LazyCallGraph.h"
#include "llvm/Analysis/MustExecute.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Transforms/Utils/CallGraphUpdater.h"
namespace llvm {
struct Attributor;
struct AbstractAttribute;
struct InformationCache;
struct AAIsDead;
class Function;
/// Simple enum classes that forces properties to be spelled out explicitly.
///
///{
enum class ChangeStatus {
CHANGED,
UNCHANGED,
};
ChangeStatus operator|(ChangeStatus l, ChangeStatus r);
ChangeStatus operator&(ChangeStatus l, ChangeStatus r);
enum class DepClassTy {
REQUIRED,
OPTIONAL,
};
///}
/// Helper to describe and deal with positions in the LLVM-IR.
///
/// A position in the IR is described by an anchor value and an "offset" that
/// could be the argument number, for call sites and arguments, or an indicator
/// of the "position kind". The kinds, specified in the Kind enum below, include
/// the locations in the attribute list, i.a., function scope and return value,
/// as well as a distinction between call sites and functions. Finally, there
/// are floating values that do not have a corresponding attribute list
/// position.
struct IRPosition {
virtual ~IRPosition() {}
/// The positions we distinguish in the IR.
///
/// The values are chosen such that the KindOrArgNo member has a value >= 0
/// if it is an argument or call site argument while a value < 0 indicates the
/// respective kind of that value.
enum Kind : int {
IRP_INVALID = -6, ///< An invalid position.
IRP_FLOAT = -5, ///< A position that is not associated with a spot suitable
///< for attributes. This could be any value or instruction.
IRP_RETURNED = -4, ///< An attribute for the function return value.
IRP_CALL_SITE_RETURNED = -3, ///< An attribute for a call site return value.
IRP_FUNCTION = -2, ///< An attribute for a function (scope).
IRP_CALL_SITE = -1, ///< An attribute for a call site (function scope).
IRP_ARGUMENT = 0, ///< An attribute for a function argument.
IRP_CALL_SITE_ARGUMENT = 1, ///< An attribute for a call site argument.
};
/// Default constructor available to create invalid positions implicitly. All
/// other positions need to be created explicitly through the appropriate
/// static member function.
IRPosition() : AnchorVal(nullptr), KindOrArgNo(IRP_INVALID) { verify(); }
/// Create a position describing the value of \p V.
static const IRPosition value(const Value &V) {
if (auto *Arg = dyn_cast<Argument>(&V))
return IRPosition::argument(*Arg);
if (auto *CB = dyn_cast<CallBase>(&V))
return IRPosition::callsite_returned(*CB);
return IRPosition(const_cast<Value &>(V), IRP_FLOAT);
}
/// Create a position describing the function scope of \p F.
static const IRPosition function(const Function &F) {
return IRPosition(const_cast<Function &>(F), IRP_FUNCTION);
}
/// Create a position describing the returned value of \p F.
static const IRPosition returned(const Function &F) {
return IRPosition(const_cast<Function &>(F), IRP_RETURNED);
}
/// Create a position describing the argument \p Arg.
static const IRPosition argument(const Argument &Arg) {
return IRPosition(const_cast<Argument &>(Arg), Kind(Arg.getArgNo()));
}
/// Create a position describing the function scope of \p CB.
static const IRPosition callsite_function(const CallBase &CB) {
return IRPosition(const_cast<CallBase &>(CB), IRP_CALL_SITE);
}
/// Create a position describing the returned value of \p CB.
static const IRPosition callsite_returned(const CallBase &CB) {
return IRPosition(const_cast<CallBase &>(CB), IRP_CALL_SITE_RETURNED);
}
/// Create a position describing the argument of \p CB at position \p ArgNo.
static const IRPosition callsite_argument(const CallBase &CB,
unsigned ArgNo) {
return IRPosition(const_cast<CallBase &>(CB), Kind(ArgNo));
}
/// Create a position describing the argument of \p ACS at position \p ArgNo.
static const IRPosition callsite_argument(AbstractCallSite ACS,
unsigned ArgNo) {
if (ACS.getNumArgOperands() <= ArgNo)
return IRPosition();
int CSArgNo = ACS.getCallArgOperandNo(ArgNo);
if (CSArgNo >= 0)
return IRPosition::callsite_argument(
cast<CallBase>(*ACS.getInstruction()), CSArgNo);
return IRPosition();
}
/// Create a position with function scope matching the "context" of \p IRP.
/// If \p IRP is a call site (see isAnyCallSitePosition()) then the result
/// will be a call site position, otherwise the function position of the
/// associated function.
static const IRPosition function_scope(const IRPosition &IRP) {
if (IRP.isAnyCallSitePosition()) {
return IRPosition::callsite_function(
cast<CallBase>(IRP.getAnchorValue()));
}
assert(IRP.getAssociatedFunction());
return IRPosition::function(*IRP.getAssociatedFunction());
}
bool operator==(const IRPosition &RHS) const {
return (AnchorVal == RHS.AnchorVal) && (KindOrArgNo == RHS.KindOrArgNo);
}
bool operator!=(const IRPosition &RHS) const { return !(*this == RHS); }
/// Return the value this abstract attribute is anchored with.
///
/// The anchor value might not be the associated value if the latter is not
/// sufficient to determine where arguments will be manifested. This is, so
/// far, only the case for call site arguments as the value is not sufficient
/// to pinpoint them. Instead, we can use the call site as an anchor.
Value &getAnchorValue() const {
assert(KindOrArgNo != IRP_INVALID &&
"Invalid position does not have an anchor value!");
return *AnchorVal;
}
/// Return the associated function, if any.
Function *getAssociatedFunction() const {
assert(KindOrArgNo != IRP_INVALID &&
"Invalid position does not have an anchor scope!");
if (auto *CB = dyn_cast<CallBase>(AnchorVal))
return CB->getCalledFunction();
return getAnchorScope();
}
/// Return the associated argument, if any.
Argument *getAssociatedArgument() const;
/// Return true if the position refers to a function interface, that is the
/// function scope, the function return, or an argument.
bool isFnInterfaceKind() const {
switch (getPositionKind()) {
case IRPosition::IRP_FUNCTION:
case IRPosition::IRP_RETURNED:
case IRPosition::IRP_ARGUMENT:
return true;
default:
return false;
}
}
/// Return the Function surrounding the anchor value.
Function *getAnchorScope() const {
Value &V = getAnchorValue();
if (isa<Function>(V))
return &cast<Function>(V);
if (isa<Argument>(V))
return cast<Argument>(V).getParent();
if (isa<Instruction>(V))
return cast<Instruction>(V).getFunction();
return nullptr;
}
/// Return the context instruction, if any.
Instruction *getCtxI() const {
Value &V = getAnchorValue();
if (auto *I = dyn_cast<Instruction>(&V))
return I;
if (auto *Arg = dyn_cast<Argument>(&V))
if (!Arg->getParent()->isDeclaration())
return &Arg->getParent()->getEntryBlock().front();
if (auto *F = dyn_cast<Function>(&V))
if (!F->isDeclaration())
return &(F->getEntryBlock().front());
return nullptr;
}
/// Return the value this abstract attribute is associated with.
Value &getAssociatedValue() const {
assert(KindOrArgNo != IRP_INVALID &&
"Invalid position does not have an associated value!");
if (getArgNo() < 0 || isa<Argument>(AnchorVal))
return *AnchorVal;
assert(isa<CallBase>(AnchorVal) && "Expected a call base!");
return *cast<CallBase>(AnchorVal)->getArgOperand(getArgNo());
}
/// Return the type this abstract attribute is associated with.
Type *getAssociatedType() const {
assert(KindOrArgNo != IRP_INVALID &&
"Invalid position does not have an associated type!");
if (getPositionKind() == IRPosition::IRP_RETURNED)
return getAssociatedFunction()->getReturnType();
return getAssociatedValue().getType();
}
/// Return the argument number of the associated value if it is an argument or
/// call site argument, otherwise a negative value.
int getArgNo() const { return KindOrArgNo; }
/// Return the index in the attribute list for this position.
unsigned getAttrIdx() const {
switch (getPositionKind()) {
case IRPosition::IRP_INVALID:
case IRPosition::IRP_FLOAT:
break;
case IRPosition::IRP_FUNCTION:
case IRPosition::IRP_CALL_SITE:
return AttributeList::FunctionIndex;
case IRPosition::IRP_RETURNED:
case IRPosition::IRP_CALL_SITE_RETURNED:
return AttributeList::ReturnIndex;
case IRPosition::IRP_ARGUMENT:
case IRPosition::IRP_CALL_SITE_ARGUMENT:
return KindOrArgNo + AttributeList::FirstArgIndex;
}
llvm_unreachable(
"There is no attribute index for a floating or invalid position!");
}
/// Return the associated position kind.
Kind getPositionKind() const {
if (getArgNo() >= 0) {
assert(((isa<Argument>(getAnchorValue()) &&
isa<Argument>(getAssociatedValue())) ||
isa<CallBase>(getAnchorValue())) &&
"Expected argument or call base due to argument number!");
if (isa<CallBase>(getAnchorValue()))
return IRP_CALL_SITE_ARGUMENT;
return IRP_ARGUMENT;
}
assert(KindOrArgNo < 0 &&
"Expected (call site) arguments to never reach this point!");
return Kind(KindOrArgNo);
}
/// TODO: Figure out if the attribute related helper functions should live
/// here or somewhere else.
/// Return true if any kind in \p AKs existing in the IR at a position that
/// will affect this one. See also getAttrs(...).
/// \param IgnoreSubsumingPositions Flag to determine if subsuming positions,
/// e.g., the function position if this is an
/// argument position, should be ignored.
bool hasAttr(ArrayRef<Attribute::AttrKind> AKs,
bool IgnoreSubsumingPositions = false,
Attributor *A = nullptr) const;
/// Return the attributes of any kind in \p AKs existing in the IR at a
/// position that will affect this one. While each position can only have a
/// single attribute of any kind in \p AKs, there are "subsuming" positions
/// that could have an attribute as well. This method returns all attributes
/// found in \p Attrs.
/// \param IgnoreSubsumingPositions Flag to determine if subsuming positions,
/// e.g., the function position if this is an
/// argument position, should be ignored.
void getAttrs(ArrayRef<Attribute::AttrKind> AKs,
SmallVectorImpl<Attribute> &Attrs,
bool IgnoreSubsumingPositions = false,
Attributor *A = nullptr) const;
/// Remove the attribute of kind \p AKs existing in the IR at this position.
void removeAttrs(ArrayRef<Attribute::AttrKind> AKs) const {
if (getPositionKind() == IRP_INVALID || getPositionKind() == IRP_FLOAT)
return;
AttributeList AttrList;
auto *CB = dyn_cast<CallBase>(&getAnchorValue());
if (CB)
AttrList = CB->getAttributes();
else
AttrList = getAssociatedFunction()->getAttributes();
LLVMContext &Ctx = getAnchorValue().getContext();
for (Attribute::AttrKind AK : AKs)
AttrList = AttrList.removeAttribute(Ctx, getAttrIdx(), AK);
if (CB)
CB->setAttributes(AttrList);
else
getAssociatedFunction()->setAttributes(AttrList);
}
bool isAnyCallSitePosition() const {
switch (getPositionKind()) {
case IRPosition::IRP_CALL_SITE:
case IRPosition::IRP_CALL_SITE_RETURNED:
case IRPosition::IRP_CALL_SITE_ARGUMENT:
return true;
default:
return false;
}
}
/// Special DenseMap key values.
///
///{
static const IRPosition EmptyKey;
static const IRPosition TombstoneKey;
///}
private:
/// Private constructor for special values only!
explicit IRPosition(int KindOrArgNo)
: AnchorVal(0), KindOrArgNo(KindOrArgNo) {}
/// IRPosition anchored at \p AnchorVal with kind/argument numbet \p PK.
explicit IRPosition(Value &AnchorVal, Kind PK)
: AnchorVal(&AnchorVal), KindOrArgNo(PK) {
verify();
}
/// Verify internal invariants.
void verify();
/// Return the attributes of kind \p AK existing in the IR as attribute.
bool getAttrsFromIRAttr(Attribute::AttrKind AK,
SmallVectorImpl<Attribute> &Attrs) const;
/// Return the attributes of kind \p AK existing in the IR as operand bundles
/// of an llvm.assume.
bool getAttrsFromAssumes(Attribute::AttrKind AK,
SmallVectorImpl<Attribute> &Attrs,
Attributor &A) const;
protected:
/// The value this position is anchored at.
Value *AnchorVal;
/// If AnchorVal is Argument or CallBase then this number should be
/// non-negative and it denotes the argument or call site argument index
/// respectively. Otherwise, it denotes the kind of this IRPosition according
/// to Kind above.
int KindOrArgNo;
};
/// Helper that allows IRPosition as a key in a DenseMap.
template <> struct DenseMapInfo<IRPosition> {
static inline IRPosition getEmptyKey() { return IRPosition::EmptyKey; }
static inline IRPosition getTombstoneKey() {
return IRPosition::TombstoneKey;
}
static unsigned getHashValue(const IRPosition &IRP) {
return (DenseMapInfo<Value *>::getHashValue(&IRP.getAnchorValue()) << 4) ^
(unsigned(IRP.getArgNo()));
}
static bool isEqual(const IRPosition &LHS, const IRPosition &RHS) {
return LHS == RHS;
}
};
/// A visitor class for IR positions.
///
/// Given a position P, the SubsumingPositionIterator allows to visit "subsuming
/// positions" wrt. attributes/information. Thus, if a piece of information
/// holds for a subsuming position, it also holds for the position P.
///
/// The subsuming positions always include the initial position and then,
/// depending on the position kind, additionally the following ones:
/// - for IRP_RETURNED:
/// - the function (IRP_FUNCTION)
/// - for IRP_ARGUMENT:
/// - the function (IRP_FUNCTION)
/// - for IRP_CALL_SITE:
/// - the callee (IRP_FUNCTION), if known
/// - for IRP_CALL_SITE_RETURNED:
/// - the callee (IRP_RETURNED), if known
/// - the call site (IRP_FUNCTION)
/// - the callee (IRP_FUNCTION), if known
/// - for IRP_CALL_SITE_ARGUMENT:
/// - the argument of the callee (IRP_ARGUMENT), if known
/// - the callee (IRP_FUNCTION), if known
/// - the position the call site argument is associated with if it is not
/// anchored to the call site, e.g., if it is an argument then the argument
/// (IRP_ARGUMENT)
class SubsumingPositionIterator {
SmallVector<IRPosition, 4> IRPositions;
using iterator = decltype(IRPositions)::iterator;
public:
SubsumingPositionIterator(const IRPosition &IRP);
iterator begin() { return IRPositions.begin(); }
iterator end() { return IRPositions.end(); }
};
/// Wrapper for FunctoinAnalysisManager.
struct AnalysisGetter {
template <typename Analysis>
typename Analysis::Result *getAnalysis(const Function &F) {
if (!FAM || !F.getParent())
return nullptr;
return &FAM->getResult<Analysis>(const_cast<Function &>(F));
}
AnalysisGetter(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
AnalysisGetter() {}
private:
FunctionAnalysisManager *FAM = nullptr;
};
/// Data structure to hold cached (LLVM-IR) information.
///
/// All attributes are given an InformationCache object at creation time to
/// avoid inspection of the IR by all of them individually. This default
/// InformationCache will hold information required by 'default' attributes,
/// thus the ones deduced when Attributor::identifyDefaultAbstractAttributes(..)
/// is called.
///
/// If custom abstract attributes, registered manually through
/// Attributor::registerAA(...), need more information, especially if it is not
/// reusable, it is advised to inherit from the InformationCache and cast the
/// instance down in the abstract attributes.
struct InformationCache {
InformationCache(const Module &M, AnalysisGetter &AG,
BumpPtrAllocator &Allocator, SetVector<Function *> *CGSCC)
: DL(M.getDataLayout()), Allocator(Allocator),
Explorer(
/* ExploreInterBlock */ true, /* ExploreCFGForward */ true,
/* ExploreCFGBackward */ true,
/* LIGetter */
[&](const Function &F) { return AG.getAnalysis<LoopAnalysis>(F); },
/* DTGetter */
[&](const Function &F) {
return AG.getAnalysis<DominatorTreeAnalysis>(F);
},
/* PDTGetter */
[&](const Function &F) {
return AG.getAnalysis<PostDominatorTreeAnalysis>(F);
}),
AG(AG), CGSCC(CGSCC) {}
~InformationCache() {
// The FunctionInfo objects are allocated via a BumpPtrAllocator, we call
// the destructor manually.
for (auto &It : FuncInfoMap)
It.getSecond()->~FunctionInfo();
}
/// A map type from opcodes to instructions with this opcode.
using OpcodeInstMapTy = DenseMap<unsigned, SmallVector<Instruction *, 32>>;
/// Return the map that relates "interesting" opcodes with all instructions
/// with that opcode in \p F.
OpcodeInstMapTy &getOpcodeInstMapForFunction(const Function &F) {
return getFunctionInfo(F).OpcodeInstMap;
}
/// A vector type to hold instructions.
using InstructionVectorTy = SmallVector<Instruction *, 4>;
/// Return the instructions in \p F that may read or write memory.
InstructionVectorTy &getReadOrWriteInstsForFunction(const Function &F) {
return getFunctionInfo(F).RWInsts;
}
/// Return MustBeExecutedContextExplorer
MustBeExecutedContextExplorer &getMustBeExecutedContextExplorer() {
return Explorer;
}
/// Return TargetLibraryInfo for function \p F.
TargetLibraryInfo *getTargetLibraryInfoForFunction(const Function &F) {
return AG.getAnalysis<TargetLibraryAnalysis>(F);
}
/// Return AliasAnalysis Result for function \p F.
AAResults *getAAResultsForFunction(const Function &F) {
return AG.getAnalysis<AAManager>(F);
}
/// Return true if \p Arg is involved in a must-tail call, thus the argument
/// of the caller or callee.
bool isInvolvedInMustTailCall(const Argument &Arg) {
FunctionInfo &FI = getFunctionInfo(*Arg.getParent());
return FI.CalledViaMustTail || FI.ContainsMustTailCall;
}
/// Return the analysis result from a pass \p AP for function \p F.
template <typename AP>
typename AP::Result *getAnalysisResultForFunction(const Function &F) {
return AG.getAnalysis<AP>(F);
}
/// Return SCC size on call graph for function \p F or 0 if unknown.
unsigned getSccSize(const Function &F) {
if (CGSCC && CGSCC->count(const_cast<Function *>(&F)))
return CGSCC->size();
return 0;
}
/// Return datalayout used in the module.
const DataLayout &getDL() { return DL; }
/// Return the map conaining all the knowledge we have from `llvm.assume`s.
const RetainedKnowledgeMap &getKnowledgeMap() const { return KnowledgeMap; }
private:
struct FunctionInfo {
/// A nested map that remembers all instructions in a function with a
/// certain instruction opcode (Instruction::getOpcode()).
OpcodeInstMapTy OpcodeInstMap;
/// A map from functions to their instructions that may read or write
/// memory.
InstructionVectorTy RWInsts;
/// Function is called by a `musttail` call.
bool CalledViaMustTail;
/// Function contains a `musttail` call.
bool ContainsMustTailCall;
};
/// A map type from functions to informatio about it.
DenseMap<const Function *, FunctionInfo *> FuncInfoMap;
/// Return information about the function \p F, potentially by creating it.
FunctionInfo &getFunctionInfo(const Function &F) {
FunctionInfo *&FI = FuncInfoMap[&F];
if (!FI) {
FI = new (Allocator) FunctionInfo();
initializeInformationCache(F, *FI);
}
return *FI;
}
/// Initialize the function information cache \p FI for the function \p F.
///
/// This method needs to be called for all function that might be looked at
/// through the information cache interface *prior* to looking at them.
void initializeInformationCache(const Function &F, FunctionInfo &FI);
/// The datalayout used in the module.
const DataLayout &DL;
/// The allocator used to allocate memory, e.g. for `FunctionInfo`s.
BumpPtrAllocator &Allocator;
/// MustBeExecutedContextExplorer
MustBeExecutedContextExplorer Explorer;
/// A map with knowledge retained in `llvm.assume` instructions.
RetainedKnowledgeMap KnowledgeMap;
/// Getters for analysis.
AnalysisGetter &AG;
/// The underlying CGSCC, or null if not available.
SetVector<Function *> *CGSCC;
/// Set of inlineable functions
SmallPtrSet<const Function *, 8> InlineableFunctions;
/// Give the Attributor access to the members so
/// Attributor::identifyDefaultAbstractAttributes(...) can initialize them.
friend struct Attributor;
};
/// The fixpoint analysis framework that orchestrates the attribute deduction.
///
/// The Attributor provides a general abstract analysis framework (guided
/// fixpoint iteration) as well as helper functions for the deduction of
/// (LLVM-IR) attributes. However, also other code properties can be deduced,
/// propagated, and ultimately manifested through the Attributor framework. This
/// is particularly useful if these properties interact with attributes and a
/// co-scheduled deduction allows to improve the solution. Even if not, thus if
/// attributes/properties are completely isolated, they should use the
/// Attributor framework to reduce the number of fixpoint iteration frameworks
/// in the code base. Note that the Attributor design makes sure that isolated
/// attributes are not impacted, in any way, by others derived at the same time
/// if there is no cross-reasoning performed.
///
/// The public facing interface of the Attributor is kept simple and basically
/// allows abstract attributes to one thing, query abstract attributes
/// in-flight. There are two reasons to do this:
/// a) The optimistic state of one abstract attribute can justify an
/// optimistic state of another, allowing to framework to end up with an
/// optimistic (=best possible) fixpoint instead of one based solely on
/// information in the IR.
/// b) This avoids reimplementing various kinds of lookups, e.g., to check
/// for existing IR attributes, in favor of a single lookups interface
/// provided by an abstract attribute subclass.
///
/// NOTE: The mechanics of adding a new "concrete" abstract attribute are
/// described in the file comment.
struct Attributor {
/// Constructor
///
/// \param Functions The set of functions we are deriving attributes for.
/// \param InfoCache Cache to hold various information accessible for
/// the abstract attributes.
/// \param CGUpdater Helper to update an underlying call graph.
/// \param DepRecomputeInterval Number of iterations until the dependences
/// between abstract attributes are recomputed.
/// \param Whitelist If not null, a set limiting the attribute opportunities.
Attributor(SetVector<Function *> &Functions, InformationCache &InfoCache,
CallGraphUpdater &CGUpdater, unsigned DepRecomputeInterval,
DenseSet<const char *> *Whitelist = nullptr)
: Allocator(InfoCache.Allocator), Functions(Functions),
InfoCache(InfoCache), CGUpdater(CGUpdater),
DepRecomputeInterval(DepRecomputeInterval), Whitelist(Whitelist) {}
~Attributor();
/// Run the analyses until a fixpoint is reached or enforced (timeout).
///
/// The attributes registered with this Attributor can be used after as long
/// as the Attributor is not destroyed (it owns the attributes now).
///
/// \Returns CHANGED if the IR was changed, otherwise UNCHANGED.
ChangeStatus run();
/// Lookup an abstract attribute of type \p AAType at position \p IRP. While
/// no abstract attribute is found equivalent positions are checked, see
/// SubsumingPositionIterator. Thus, the returned abstract attribute
/// might be anchored at a different position, e.g., the callee if \p IRP is a
/// call base.
///
/// This method is the only (supported) way an abstract attribute can retrieve
/// information from another abstract attribute. As an example, take an
/// abstract attribute that determines the memory access behavior for a
/// argument (readnone, readonly, ...). It should use `getAAFor` to get the
/// most optimistic information for other abstract attributes in-flight, e.g.
/// the one reasoning about the "captured" state for the argument or the one
/// reasoning on the memory access behavior of the function as a whole.
///
/// If the flag \p TrackDependence is set to false the dependence from
/// \p QueryingAA to the return abstract attribute is not automatically
/// recorded. This should only be used if the caller will record the
/// dependence explicitly if necessary, thus if it the returned abstract
/// attribute is used for reasoning. To record the dependences explicitly use
/// the `Attributor::recordDependence` method.
template <typename AAType>
const AAType &getAAFor(const AbstractAttribute &QueryingAA,
const IRPosition &IRP, bool TrackDependence = true,
DepClassTy DepClass = DepClassTy::REQUIRED) {
return getOrCreateAAFor<AAType>(IRP, &QueryingAA, TrackDependence,
DepClass);
}
/// Explicitly record a dependence from \p FromAA to \p ToAA, that is if
/// \p FromAA changes \p ToAA should be updated as well.
///
/// This method should be used in conjunction with the `getAAFor` method and
/// with the TrackDependence flag passed to the method set to false. This can
/// be beneficial to avoid false dependences but it requires the users of
/// `getAAFor` to explicitly record true dependences through this method.
/// The \p DepClass flag indicates if the dependence is striclty necessary.
/// That means for required dependences, if \p FromAA changes to an invalid
/// state, \p ToAA can be moved to a pessimistic fixpoint because it required
/// information from \p FromAA but none are available anymore.
void recordDependence(const AbstractAttribute &FromAA,
const AbstractAttribute &ToAA, DepClassTy DepClass);
/// Introduce a new abstract attribute into the fixpoint analysis.
///
/// Note that ownership of the attribute is given to the Attributor. It will
/// invoke delete for the Attributor on destruction of the Attributor.
///
/// Attributes are identified by their IR position (AAType::getIRPosition())
/// and the address of their static member (see AAType::ID).
template <typename AAType> AAType ®isterAA(AAType &AA) {
static_assert(std::is_base_of<AbstractAttribute, AAType>::value,
"Cannot register an attribute with a type not derived from "
"'AbstractAttribute'!");
// Put the attribute in the lookup map structure and the container we use to
// keep track of all attributes.
const IRPosition &IRP = AA.getIRPosition();
Kind2AAMapTy *&Kind2AA = AAMap[IRP];
if (!Kind2AA)
Kind2AA = new (Allocator) Kind2AAMapTy();
assert(!(*Kind2AA)[&AAType::ID] && "Attribute already in map!");
(*Kind2AA)[&AAType::ID] = &AA;
AllAbstractAttributes.push_back(&AA);
return AA;
}
/// Return the internal information cache.
InformationCache &getInfoCache() { return InfoCache; }
/// Return true if this is a module pass, false otherwise.
bool isModulePass() const {
return !Functions.empty() &&
Functions.size() == Functions.front()->getParent()->size();
}
/// Determine opportunities to derive 'default' attributes in \p F and create
/// abstract attribute objects for them.
///
/// \param F The function that is checked for attribute opportunities.
///
/// Note that abstract attribute instances are generally created even if the
/// IR already contains the information they would deduce. The most important
/// reason for this is the single interface, the one of the abstract attribute
/// instance, which can be queried without the need to look at the IR in
/// various places.
void identifyDefaultAbstractAttributes(Function &F);
/// Determine whether the function \p F is IPO amendable
///
/// If a function is exactly defined or it has alwaysinline attribute
/// and is viable to be inlined, we say it is IPO amendable
bool isFunctionIPOAmendable(const Function &F) {
return F.hasExactDefinition() || InfoCache.InlineableFunctions.count(&F);
}
/// Mark the internal function \p F as live.
///
/// This will trigger the identification and initialization of attributes for
/// \p F.
void markLiveInternalFunction(const Function &F) {
assert(F.hasLocalLinkage() &&
"Only local linkage is assumed dead initially.");
identifyDefaultAbstractAttributes(const_cast<Function &>(F));
}
/// Record that \p U is to be replaces with \p NV after information was
/// manifested. This also triggers deletion of trivially dead istructions.
bool changeUseAfterManifest(Use &U, Value &NV) {
Value *&V = ToBeChangedUses[&U];
if (V && (V->stripPointerCasts() == NV.stripPointerCasts() ||
isa_and_nonnull<UndefValue>(V)))
return false;
assert((!V || V == &NV || isa<UndefValue>(NV)) &&
"Use was registered twice for replacement with different values!");
V = &NV;
return true;
}
/// Helper function to replace all uses of \p V with \p NV. Return true if
/// there is any change. The flag \p ChangeDroppable indicates if dropppable
/// uses should be changed too.
bool changeValueAfterManifest(Value &V, Value &NV,
bool ChangeDroppable = true) {
bool Changed = false;
for (auto &U : V.uses())
if (ChangeDroppable || !U.getUser()->isDroppable())
Changed |= changeUseAfterManifest(U, NV);
return Changed;
}
/// Record that \p I is to be replaced with `unreachable` after information
/// was manifested.
void changeToUnreachableAfterManifest(Instruction *I) {
ToBeChangedToUnreachableInsts.insert(I);
}
/// Record that \p II has at least one dead successor block. This information
/// is used, e.g., to replace \p II with a call, after information was
/// manifested.
void registerInvokeWithDeadSuccessor(InvokeInst &II) {
InvokeWithDeadSuccessor.push_back(&II);
}
/// Record that \p I is deleted after information was manifested. This also
/// triggers deletion of trivially dead istructions.
void deleteAfterManifest(Instruction &I) { ToBeDeletedInsts.insert(&I); }
/// Record that \p BB is deleted after information was manifested. This also
/// triggers deletion of trivially dead istructions.
void deleteAfterManifest(BasicBlock &BB) { ToBeDeletedBlocks.insert(&BB); }
/// Record that \p F is deleted after information was manifested.
void deleteAfterManifest(Function &F) { ToBeDeletedFunctions.insert(&F); }
/// If \p V is assumed to be a constant, return it, if it is unclear yet,
/// return None, otherwise return `nullptr`.
Optional<Constant *> getAssumedConstant(const Value &V,
const AbstractAttribute &AA,
bool &UsedAssumedInformation);
/// Return true if \p AA (or its context instruction) is assumed dead.
///
/// If \p LivenessAA is not provided it is queried.
bool isAssumedDead(const AbstractAttribute &AA, const AAIsDead *LivenessAA,
bool CheckBBLivenessOnly = false,
DepClassTy DepClass = DepClassTy::OPTIONAL);
/// Return true if \p I is assumed dead.
///
/// If \p LivenessAA is not provided it is queried.
bool isAssumedDead(const Instruction &I, const AbstractAttribute *QueryingAA,
const AAIsDead *LivenessAA,
bool CheckBBLivenessOnly = false,
DepClassTy DepClass = DepClassTy::OPTIONAL);
/// Return true if \p U is assumed dead.
///
/// If \p FnLivenessAA is not provided it is queried.
bool isAssumedDead(const Use &U, const AbstractAttribute *QueryingAA,
const AAIsDead *FnLivenessAA,
bool CheckBBLivenessOnly = false,
DepClassTy DepClass = DepClassTy::OPTIONAL);
/// Return true if \p IRP is assumed dead.
///
/// If \p FnLivenessAA is not provided it is queried.
bool isAssumedDead(const IRPosition &IRP, const AbstractAttribute *QueryingAA,
const AAIsDead *FnLivenessAA,
bool CheckBBLivenessOnly = false,
DepClassTy DepClass = DepClassTy::OPTIONAL);
/// Check \p Pred on all (transitive) uses of \p V.
///
/// This method will evaluate \p Pred on all (transitive) uses of the
/// associated value and return true if \p Pred holds every time.
bool checkForAllUses(function_ref<bool(const Use &, bool &)> Pred,
const AbstractAttribute &QueryingAA, const Value &V,
DepClassTy LivenessDepClass = DepClassTy::OPTIONAL);
/// Helper struct used in the communication between an abstract attribute (AA)
/// that wants to change the signature of a function and the Attributor which
/// applies the changes. The struct is partially initialized with the
/// information from the AA (see the constructor). All other members are
/// provided by the Attributor prior to invoking any callbacks.
struct ArgumentReplacementInfo {
/// Callee repair callback type
///
/// The function repair callback is invoked once to rewire the replacement
/// arguments in the body of the new function. The argument replacement info
/// is passed, as build from the registerFunctionSignatureRewrite call, as
/// well as the replacement function and an iteratore to the first
/// replacement argument.
using CalleeRepairCBTy = std::function<void(
const ArgumentReplacementInfo &, Function &, Function::arg_iterator)>;
/// Abstract call site (ACS) repair callback type
///
/// The abstract call site repair callback is invoked once on every abstract
/// call site of the replaced function (\see ReplacedFn). The callback needs
/// to provide the operands for the call to the new replacement function.
/// The number and type of the operands appended to the provided vector
/// (second argument) is defined by the number and types determined through
/// the replacement type vector (\see ReplacementTypes). The first argument
/// is the ArgumentReplacementInfo object registered with the Attributor
/// through the registerFunctionSignatureRewrite call.
using ACSRepairCBTy =
std::function<void(const ArgumentReplacementInfo &, AbstractCallSite,
SmallVectorImpl<Value *> &)>;
/// Simple getters, see the corresponding members for details.
///{
Attributor &getAttributor() const { return A; }
const Function &getReplacedFn() const { return ReplacedFn; }
const Argument &getReplacedArg() const { return ReplacedArg; }
unsigned getNumReplacementArgs() const { return ReplacementTypes.size(); }
const SmallVectorImpl<Type *> &getReplacementTypes() const {
return ReplacementTypes;
}
///}
private:
/// Constructor that takes the argument to be replaced, the types of
/// the replacement arguments, as well as callbacks to repair the call sites
/// and new function after the replacement happened.
ArgumentReplacementInfo(Attributor &A, Argument &Arg,
ArrayRef<Type *> ReplacementTypes,