This repository has been archived by the owner on Apr 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathInlineFunction.cpp
2373 lines (2087 loc) · 98.7 KB
/
InlineFunction.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
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
//===- InlineFunction.cpp - Code to perform function inlining -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements inlining of a function into a call site, resolving
// parameters and the return value as appropriate.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/CaptureTracking.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <limits>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
using ProfileCount = Function::ProfileCount;
static cl::opt<bool>
EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
cl::Hidden,
cl::desc("Convert noalias attributes to metadata during inlining."));
static cl::opt<bool>
PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
cl::init(true), cl::Hidden,
cl::desc("Convert align attributes to assumptions during inlining."));
llvm::InlineResult llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
AAResults *CalleeAAR,
bool InsertLifetime) {
return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
}
llvm::InlineResult llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
AAResults *CalleeAAR,
bool InsertLifetime) {
return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
}
namespace {
/// A class for recording information about inlining a landing pad.
class LandingPadInliningInfo {
/// Destination of the invoke's unwind.
BasicBlock *OuterResumeDest;
/// Destination for the callee's resume.
BasicBlock *InnerResumeDest = nullptr;
/// LandingPadInst associated with the invoke.
LandingPadInst *CallerLPad = nullptr;
/// PHI for EH values from landingpad insts.
PHINode *InnerEHValuesPHI = nullptr;
SmallVector<Value*, 8> UnwindDestPHIValues;
public:
LandingPadInliningInfo(InvokeInst *II)
: OuterResumeDest(II->getUnwindDest()) {
// If there are PHI nodes in the unwind destination block, we need to keep
// track of which values came into them from the invoke before removing
// the edge from this block.
BasicBlock *InvokeBB = II->getParent();
BasicBlock::iterator I = OuterResumeDest->begin();
for (; isa<PHINode>(I); ++I) {
// Save the value to use for this edge.
PHINode *PHI = cast<PHINode>(I);
UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
}
CallerLPad = cast<LandingPadInst>(I);
}
/// The outer unwind destination is the target of
/// unwind edges introduced for calls within the inlined function.
BasicBlock *getOuterResumeDest() const {
return OuterResumeDest;
}
BasicBlock *getInnerResumeDest();
LandingPadInst *getLandingPadInst() const { return CallerLPad; }
/// Forward the 'resume' instruction to the caller's landing pad block.
/// When the landing pad block has only one predecessor, this is
/// a simple branch. When there is more than one predecessor, we need to
/// split the landing pad block after the landingpad instruction and jump
/// to there.
void forwardResume(ResumeInst *RI,
SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
/// Add incoming-PHI values to the unwind destination block for the given
/// basic block, using the values for the original invoke's source block.
void addIncomingPHIValuesFor(BasicBlock *BB) const {
addIncomingPHIValuesForInto(BB, OuterResumeDest);
}
void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
BasicBlock::iterator I = dest->begin();
for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
PHINode *phi = cast<PHINode>(I);
phi->addIncoming(UnwindDestPHIValues[i], src);
}
}
};
} // end anonymous namespace
/// Get or create a target for the branch from ResumeInsts.
BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
if (InnerResumeDest) return InnerResumeDest;
// Split the landing pad.
BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
InnerResumeDest =
OuterResumeDest->splitBasicBlock(SplitPoint,
OuterResumeDest->getName() + ".body");
// The number of incoming edges we expect to the inner landing pad.
const unsigned PHICapacity = 2;
// Create corresponding new PHIs for all the PHIs in the outer landing pad.
Instruction *InsertPoint = &InnerResumeDest->front();
BasicBlock::iterator I = OuterResumeDest->begin();
for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
PHINode *OuterPHI = cast<PHINode>(I);
PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
OuterPHI->getName() + ".lpad-body",
InsertPoint);
OuterPHI->replaceAllUsesWith(InnerPHI);
InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
}
// Create a PHI for the exception values.
InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
"eh.lpad-body", InsertPoint);
CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
// All done.
return InnerResumeDest;
}
/// Forward the 'resume' instruction to the caller's landing pad block.
/// When the landing pad block has only one predecessor, this is a simple
/// branch. When there is more than one predecessor, we need to split the
/// landing pad block after the landingpad instruction and jump to there.
void LandingPadInliningInfo::forwardResume(
ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
BasicBlock *Dest = getInnerResumeDest();
BasicBlock *Src = RI->getParent();
BranchInst::Create(Dest, Src);
// Update the PHIs in the destination. They were inserted in an order which
// makes this work.
addIncomingPHIValuesForInto(Src, Dest);
InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
RI->eraseFromParent();
}
/// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
static Value *getParentPad(Value *EHPad) {
if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
return FPI->getParentPad();
return cast<CatchSwitchInst>(EHPad)->getParentPad();
}
using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
/// Helper for getUnwindDestToken that does the descendant-ward part of
/// the search.
static Value *getUnwindDestTokenHelper(Instruction *EHPad,
UnwindDestMemoTy &MemoMap) {
SmallVector<Instruction *, 8> Worklist(1, EHPad);
while (!Worklist.empty()) {
Instruction *CurrentPad = Worklist.pop_back_val();
// We only put pads on the worklist that aren't in the MemoMap. When
// we find an unwind dest for a pad we may update its ancestors, but
// the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
// so they should never get updated while queued on the worklist.
assert(!MemoMap.count(CurrentPad));
Value *UnwindDestToken = nullptr;
if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
if (CatchSwitch->hasUnwindDest()) {
UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
} else {
// Catchswitch doesn't have a 'nounwind' variant, and one might be
// annotated as "unwinds to caller" when really it's nounwind (see
// e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
// parent's unwind dest from this. We can check its catchpads'
// descendants, since they might include a cleanuppad with an
// "unwinds to caller" cleanupret, which can be trusted.
for (auto HI = CatchSwitch->handler_begin(),
HE = CatchSwitch->handler_end();
HI != HE && !UnwindDestToken; ++HI) {
BasicBlock *HandlerBlock = *HI;
auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
for (User *Child : CatchPad->users()) {
// Intentionally ignore invokes here -- since the catchswitch is
// marked "unwind to caller", it would be a verifier error if it
// contained an invoke which unwinds out of it, so any invoke we'd
// encounter must unwind to some child of the catch.
if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
continue;
Instruction *ChildPad = cast<Instruction>(Child);
auto Memo = MemoMap.find(ChildPad);
if (Memo == MemoMap.end()) {
// Haven't figured out this child pad yet; queue it.
Worklist.push_back(ChildPad);
continue;
}
// We've already checked this child, but might have found that
// it offers no proof either way.
Value *ChildUnwindDestToken = Memo->second;
if (!ChildUnwindDestToken)
continue;
// We already know the child's unwind dest, which can either
// be ConstantTokenNone to indicate unwind to caller, or can
// be another child of the catchpad. Only the former indicates
// the unwind dest of the catchswitch.
if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
UnwindDestToken = ChildUnwindDestToken;
break;
}
assert(getParentPad(ChildUnwindDestToken) == CatchPad);
}
}
}
} else {
auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
for (User *U : CleanupPad->users()) {
if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
UnwindDestToken = RetUnwindDest->getFirstNonPHI();
else
UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
break;
}
Value *ChildUnwindDestToken;
if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
} else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
Instruction *ChildPad = cast<Instruction>(U);
auto Memo = MemoMap.find(ChildPad);
if (Memo == MemoMap.end()) {
// Haven't resolved this child yet; queue it and keep searching.
Worklist.push_back(ChildPad);
continue;
}
// We've checked this child, but still need to ignore it if it
// had no proof either way.
ChildUnwindDestToken = Memo->second;
if (!ChildUnwindDestToken)
continue;
} else {
// Not a relevant user of the cleanuppad
continue;
}
// In a well-formed program, the child/invoke must either unwind to
// an(other) child of the cleanup, or exit the cleanup. In the
// first case, continue searching.
if (isa<Instruction>(ChildUnwindDestToken) &&
getParentPad(ChildUnwindDestToken) == CleanupPad)
continue;
UnwindDestToken = ChildUnwindDestToken;
break;
}
}
// If we haven't found an unwind dest for CurrentPad, we may have queued its
// children, so move on to the next in the worklist.
if (!UnwindDestToken)
continue;
// Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
// any ancestors of CurrentPad up to but not including UnwindDestToken's
// parent pad. Record this in the memo map, and check to see if the
// original EHPad being queried is one of the ones exited.
Value *UnwindParent;
if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
UnwindParent = getParentPad(UnwindPad);
else
UnwindParent = nullptr;
bool ExitedOriginalPad = false;
for (Instruction *ExitedPad = CurrentPad;
ExitedPad && ExitedPad != UnwindParent;
ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
// Skip over catchpads since they just follow their catchswitches.
if (isa<CatchPadInst>(ExitedPad))
continue;
MemoMap[ExitedPad] = UnwindDestToken;
ExitedOriginalPad |= (ExitedPad == EHPad);
}
if (ExitedOriginalPad)
return UnwindDestToken;
// Continue the search.
}
// No definitive information is contained within this funclet.
return nullptr;
}
/// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
/// return that pad instruction. If it unwinds to caller, return
/// ConstantTokenNone. If it does not have a definitive unwind destination,
/// return nullptr.
///
/// This routine gets invoked for calls in funclets in inlinees when inlining
/// an invoke. Since many funclets don't have calls inside them, it's queried
/// on-demand rather than building a map of pads to unwind dests up front.
/// Determining a funclet's unwind dest may require recursively searching its
/// descendants, and also ancestors and cousins if the descendants don't provide
/// an answer. Since most funclets will have their unwind dest immediately
/// available as the unwind dest of a catchswitch or cleanupret, this routine
/// searches top-down from the given pad and then up. To avoid worst-case
/// quadratic run-time given that approach, it uses a memo map to avoid
/// re-processing funclet trees. The callers that rewrite the IR as they go
/// take advantage of this, for correctness, by checking/forcing rewritten
/// pads' entries to match the original callee view.
static Value *getUnwindDestToken(Instruction *EHPad,
UnwindDestMemoTy &MemoMap) {
// Catchpads unwind to the same place as their catchswitch;
// redirct any queries on catchpads so the code below can
// deal with just catchswitches and cleanuppads.
if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
EHPad = CPI->getCatchSwitch();
// Check if we've already determined the unwind dest for this pad.
auto Memo = MemoMap.find(EHPad);
if (Memo != MemoMap.end())
return Memo->second;
// Search EHPad and, if necessary, its descendants.
Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
if (UnwindDestToken)
return UnwindDestToken;
// No information is available for this EHPad from itself or any of its
// descendants. An unwind all the way out to a pad in the caller would
// need also to agree with the unwind dest of the parent funclet, so
// search up the chain to try to find a funclet with information. Put
// null entries in the memo map to avoid re-processing as we go up.
MemoMap[EHPad] = nullptr;
#ifndef NDEBUG
SmallPtrSet<Instruction *, 4> TempMemos;
TempMemos.insert(EHPad);
#endif
Instruction *LastUselessPad = EHPad;
Value *AncestorToken;
for (AncestorToken = getParentPad(EHPad);
auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
AncestorToken = getParentPad(AncestorToken)) {
// Skip over catchpads since they just follow their catchswitches.
if (isa<CatchPadInst>(AncestorPad))
continue;
// If the MemoMap had an entry mapping AncestorPad to nullptr, since we
// haven't yet called getUnwindDestTokenHelper for AncestorPad in this
// call to getUnwindDestToken, that would mean that AncestorPad had no
// information in itself, its descendants, or its ancestors. If that
// were the case, then we should also have recorded the lack of information
// for the descendant that we're coming from. So assert that we don't
// find a null entry in the MemoMap for AncestorPad.
assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
auto AncestorMemo = MemoMap.find(AncestorPad);
if (AncestorMemo == MemoMap.end()) {
UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
} else {
UnwindDestToken = AncestorMemo->second;
}
if (UnwindDestToken)
break;
LastUselessPad = AncestorPad;
MemoMap[LastUselessPad] = nullptr;
#ifndef NDEBUG
TempMemos.insert(LastUselessPad);
#endif
}
// We know that getUnwindDestTokenHelper was called on LastUselessPad and
// returned nullptr (and likewise for EHPad and any of its ancestors up to
// LastUselessPad), so LastUselessPad has no information from below. Since
// getUnwindDestTokenHelper must investigate all downward paths through
// no-information nodes to prove that a node has no information like this,
// and since any time it finds information it records it in the MemoMap for
// not just the immediately-containing funclet but also any ancestors also
// exited, it must be the case that, walking downward from LastUselessPad,
// visiting just those nodes which have not been mapped to an unwind dest
// by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
// they are just used to keep getUnwindDestTokenHelper from repeating work),
// any node visited must have been exhaustively searched with no information
// for it found.
SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
while (!Worklist.empty()) {
Instruction *UselessPad = Worklist.pop_back_val();
auto Memo = MemoMap.find(UselessPad);
if (Memo != MemoMap.end() && Memo->second) {
// Here the name 'UselessPad' is a bit of a misnomer, because we've found
// that it is a funclet that does have information about unwinding to
// a particular destination; its parent was a useless pad.
// Since its parent has no information, the unwind edge must not escape
// the parent, and must target a sibling of this pad. This local unwind
// gives us no information about EHPad. Leave it and the subtree rooted
// at it alone.
assert(getParentPad(Memo->second) == getParentPad(UselessPad));
continue;
}
// We know we don't have information for UselesPad. If it has an entry in
// the MemoMap (mapping it to nullptr), it must be one of the TempMemos
// added on this invocation of getUnwindDestToken; if a previous invocation
// recorded nullptr, it would have had to prove that the ancestors of
// UselessPad, which include LastUselessPad, had no information, and that
// in turn would have required proving that the descendants of
// LastUselesPad, which include EHPad, have no information about
// LastUselessPad, which would imply that EHPad was mapped to nullptr in
// the MemoMap on that invocation, which isn't the case if we got here.
assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
// Assert as we enumerate users that 'UselessPad' doesn't have any unwind
// information that we'd be contradicting by making a map entry for it
// (which is something that getUnwindDestTokenHelper must have proved for
// us to get here). Just assert on is direct users here; the checks in
// this downward walk at its descendants will verify that they don't have
// any unwind edges that exit 'UselessPad' either (i.e. they either have no
// unwind edges or unwind to a sibling).
MemoMap[UselessPad] = UnwindDestToken;
if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
auto *CatchPad = HandlerBlock->getFirstNonPHI();
for (User *U : CatchPad->users()) {
assert(
(!isa<InvokeInst>(U) ||
(getParentPad(
cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
CatchPad)) &&
"Expected useless pad");
if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
Worklist.push_back(cast<Instruction>(U));
}
}
} else {
assert(isa<CleanupPadInst>(UselessPad));
for (User *U : UselessPad->users()) {
assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
assert((!isa<InvokeInst>(U) ||
(getParentPad(
cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
UselessPad)) &&
"Expected useless pad");
if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
Worklist.push_back(cast<Instruction>(U));
}
}
}
return UnwindDestToken;
}
/// When we inline a basic block into an invoke,
/// we have to turn all of the calls that can throw into invokes.
/// This function analyze BB to see if there are any calls, and if so,
/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
/// nodes in that block with the values specified in InvokeDestPHIValues.
static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
BasicBlock *BB, BasicBlock *UnwindEdge,
UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Instruction *I = &*BBI++;
// We only need to check for function calls: inlined invoke
// instructions require no special handling.
CallInst *CI = dyn_cast<CallInst>(I);
if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
continue;
// We do not need to (and in fact, cannot) convert possibly throwing calls
// to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
// invokes. The caller's "segment" of the deoptimization continuation
// attached to the newly inlined @llvm.experimental_deoptimize
// (resp. @llvm.experimental.guard) call should contain the exception
// handling logic, if any.
if (auto *F = CI->getCalledFunction())
if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
F->getIntrinsicID() == Intrinsic::experimental_guard)
continue;
if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
// This call is nested inside a funclet. If that funclet has an unwind
// destination within the inlinee, then unwinding out of this call would
// be UB. Rewriting this call to an invoke which targets the inlined
// invoke's unwind dest would give the call's parent funclet multiple
// unwind destinations, which is something that subsequent EH table
// generation can't handle and that the veirifer rejects. So when we
// see such a call, leave it as a call.
auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
Value *UnwindDestToken =
getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
continue;
#ifndef NDEBUG
Instruction *MemoKey;
if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
MemoKey = CatchPad->getCatchSwitch();
else
MemoKey = FuncletPad;
assert(FuncletUnwindMap->count(MemoKey) &&
(*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
"must get memoized to avoid confusing later searches");
#endif // NDEBUG
}
changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
return BB;
}
return nullptr;
}
/// If we inlined an invoke site, we need to convert calls
/// in the body of the inlined function into invokes.
///
/// II is the invoke instruction being inlined. FirstNewBlock is the first
/// block of the inlined code (the last block is the end of the function),
/// and InlineCodeInfo is information about the code that got inlined.
static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
ClonedCodeInfo &InlinedCodeInfo) {
BasicBlock *InvokeDest = II->getUnwindDest();
Function *Caller = FirstNewBlock->getParent();
// The inlined code is currently at the end of the function, scan from the
// start of the inlined code to its end, checking for stuff we need to
// rewrite.
LandingPadInliningInfo Invoke(II);
// Get all of the inlined landing pad instructions.
SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
I != E; ++I)
if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
InlinedLPads.insert(II->getLandingPadInst());
// Append the clauses from the outer landing pad instruction into the inlined
// landing pad instructions.
LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
for (LandingPadInst *InlinedLPad : InlinedLPads) {
unsigned OuterNum = OuterLPad->getNumClauses();
InlinedLPad->reserveClauses(OuterNum);
for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
if (OuterLPad->isCleanup())
InlinedLPad->setCleanup(true);
}
for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
BB != E; ++BB) {
if (InlinedCodeInfo.ContainsCalls)
if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
&*BB, Invoke.getOuterResumeDest()))
// Update any PHI nodes in the exceptional block to indicate that there
// is now a new entry in them.
Invoke.addIncomingPHIValuesFor(NewBB);
// Forward any resumes that are remaining here.
if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
Invoke.forwardResume(RI, InlinedLPads);
}
// Now that everything is happy, we have one final detail. The PHI nodes in
// the exception destination block still have entries due to the original
// invoke instruction. Eliminate these entries (which might even delete the
// PHI node) now.
InvokeDest->removePredecessor(II->getParent());
}
/// If we inlined an invoke site, we need to convert calls
/// in the body of the inlined function into invokes.
///
/// II is the invoke instruction being inlined. FirstNewBlock is the first
/// block of the inlined code (the last block is the end of the function),
/// and InlineCodeInfo is information about the code that got inlined.
static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
ClonedCodeInfo &InlinedCodeInfo) {
BasicBlock *UnwindDest = II->getUnwindDest();
Function *Caller = FirstNewBlock->getParent();
assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
// If there are PHI nodes in the unwind destination block, we need to keep
// track of which values came into them from the invoke before removing the
// edge from this block.
SmallVector<Value *, 8> UnwindDestPHIValues;
BasicBlock *InvokeBB = II->getParent();
for (Instruction &I : *UnwindDest) {
// Save the value to use for this edge.
PHINode *PHI = dyn_cast<PHINode>(&I);
if (!PHI)
break;
UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
}
// Add incoming-PHI values to the unwind destination block for the given basic
// block, using the values for the original invoke's source block.
auto UpdatePHINodes = [&](BasicBlock *Src) {
BasicBlock::iterator I = UnwindDest->begin();
for (Value *V : UnwindDestPHIValues) {
PHINode *PHI = cast<PHINode>(I);
PHI->addIncoming(V, Src);
++I;
}
};
// This connects all the instructions which 'unwind to caller' to the invoke
// destination.
UnwindDestMemoTy FuncletUnwindMap;
for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
BB != E; ++BB) {
if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
if (CRI->unwindsToCaller()) {
auto *CleanupPad = CRI->getCleanupPad();
CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
CRI->eraseFromParent();
UpdatePHINodes(&*BB);
// Finding a cleanupret with an unwind destination would confuse
// subsequent calls to getUnwindDestToken, so map the cleanuppad
// to short-circuit any such calls and recognize this as an "unwind
// to caller" cleanup.
assert(!FuncletUnwindMap.count(CleanupPad) ||
isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
FuncletUnwindMap[CleanupPad] =
ConstantTokenNone::get(Caller->getContext());
}
}
Instruction *I = BB->getFirstNonPHI();
if (!I->isEHPad())
continue;
Instruction *Replacement = nullptr;
if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
if (CatchSwitch->unwindsToCaller()) {
Value *UnwindDestToken;
if (auto *ParentPad =
dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
// This catchswitch is nested inside another funclet. If that
// funclet has an unwind destination within the inlinee, then
// unwinding out of this catchswitch would be UB. Rewriting this
// catchswitch to unwind to the inlined invoke's unwind dest would
// give the parent funclet multiple unwind destinations, which is
// something that subsequent EH table generation can't handle and
// that the veirifer rejects. So when we see such a call, leave it
// as "unwind to caller".
UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
continue;
} else {
// This catchswitch has no parent to inherit constraints from, and
// none of its descendants can have an unwind edge that exits it and
// targets another funclet in the inlinee. It may or may not have a
// descendant that definitively has an unwind to caller. In either
// case, we'll have to assume that any unwinds out of it may need to
// be routed to the caller, so treat it as though it has a definitive
// unwind to caller.
UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
}
auto *NewCatchSwitch = CatchSwitchInst::Create(
CatchSwitch->getParentPad(), UnwindDest,
CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
CatchSwitch);
for (BasicBlock *PadBB : CatchSwitch->handlers())
NewCatchSwitch->addHandler(PadBB);
// Propagate info for the old catchswitch over to the new one in
// the unwind map. This also serves to short-circuit any subsequent
// checks for the unwind dest of this catchswitch, which would get
// confused if they found the outer handler in the callee.
FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
Replacement = NewCatchSwitch;
}
} else if (!isa<FuncletPadInst>(I)) {
llvm_unreachable("unexpected EHPad!");
}
if (Replacement) {
Replacement->takeName(I);
I->replaceAllUsesWith(Replacement);
I->eraseFromParent();
UpdatePHINodes(&*BB);
}
}
if (InlinedCodeInfo.ContainsCalls)
for (Function::iterator BB = FirstNewBlock->getIterator(),
E = Caller->end();
BB != E; ++BB)
if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
&*BB, UnwindDest, &FuncletUnwindMap))
// Update any PHI nodes in the exceptional block to indicate that there
// is now a new entry in them.
UpdatePHINodes(NewBB);
// Now that everything is happy, we have one final detail. The PHI nodes in
// the exception destination block still have entries due to the original
// invoke instruction. Eliminate these entries (which might even delete the
// PHI node) now.
UnwindDest->removePredecessor(InvokeBB);
}
/// When inlining a call site that has !llvm.mem.parallel_loop_access metadata,
/// that metadata should be propagated to all memory-accessing cloned
/// instructions.
static void PropagateParallelLoopAccessMetadata(CallSite CS,
ValueToValueMapTy &VMap) {
MDNode *M =
CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
if (!M)
return;
for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
VMI != VMIE; ++VMI) {
if (!VMI->second)
continue;
Instruction *NI = dyn_cast<Instruction>(VMI->second);
if (!NI)
continue;
if (MDNode *PM = NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
M = MDNode::concatenate(PM, M);
NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
} else if (NI->mayReadOrWriteMemory()) {
NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
}
}
}
/// When inlining a function that contains noalias scope metadata,
/// this metadata needs to be cloned so that the inlined blocks
/// have different "unique scopes" at every call site. Were this not done, then
/// aliasing scopes from a function inlined into a caller multiple times could
/// not be differentiated (and this would lead to miscompiles because the
/// non-aliasing property communicated by the metadata could have
/// call-site-specific control dependencies).
static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
const Function *CalledFunc = CS.getCalledFunction();
SetVector<const MDNode *> MD;
// Note: We could only clone the metadata if it is already used in the
// caller. I'm omitting that check here because it might confuse
// inter-procedural alias analysis passes. We can revisit this if it becomes
// an efficiency or overhead problem.
for (const BasicBlock &I : *CalledFunc)
for (const Instruction &J : I) {
if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
MD.insert(M);
if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
MD.insert(M);
}
if (MD.empty())
return;
// Walk the existing metadata, adding the complete (perhaps cyclic) chain to
// the set.
SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
while (!Queue.empty()) {
const MDNode *M = cast<MDNode>(Queue.pop_back_val());
for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
if (MD.insert(M1))
Queue.push_back(M1);
}
// Now we have a complete set of all metadata in the chains used to specify
// the noalias scopes and the lists of those scopes.
SmallVector<TempMDTuple, 16> DummyNodes;
DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
for (const MDNode *I : MD) {
DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
MDMap[I].reset(DummyNodes.back().get());
}
// Create new metadata nodes to replace the dummy nodes, replacing old
// metadata references with either a dummy node or an already-created new
// node.
for (const MDNode *I : MD) {
SmallVector<Metadata *, 4> NewOps;
for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
const Metadata *V = I->getOperand(i);
if (const MDNode *M = dyn_cast<MDNode>(V))
NewOps.push_back(MDMap[M]);
else
NewOps.push_back(const_cast<Metadata *>(V));
}
MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
MDTuple *TempM = cast<MDTuple>(MDMap[I]);
assert(TempM->isTemporary() && "Expected temporary node");
TempM->replaceAllUsesWith(NewM);
}
// Now replace the metadata in the new inlined instructions with the
// repacements from the map.
for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
VMI != VMIE; ++VMI) {
if (!VMI->second)
continue;
Instruction *NI = dyn_cast<Instruction>(VMI->second);
if (!NI)
continue;
if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
MDNode *NewMD = MDMap[M];
// If the call site also had alias scope metadata (a list of scopes to
// which instructions inside it might belong), propagate those scopes to
// the inlined instructions.
if (MDNode *CSM =
CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
NewMD = MDNode::concatenate(NewMD, CSM);
NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
} else if (NI->mayReadOrWriteMemory()) {
if (MDNode *M =
CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
NI->setMetadata(LLVMContext::MD_alias_scope, M);
}
if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
MDNode *NewMD = MDMap[M];
// If the call site also had noalias metadata (a list of scopes with
// which instructions inside it don't alias), propagate those scopes to
// the inlined instructions.
if (MDNode *CSM =
CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
NewMD = MDNode::concatenate(NewMD, CSM);
NI->setMetadata(LLVMContext::MD_noalias, NewMD);
} else if (NI->mayReadOrWriteMemory()) {
if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
NI->setMetadata(LLVMContext::MD_noalias, M);
}
}
}
/// If the inlined function has noalias arguments,
/// then add new alias scopes for each noalias argument, tag the mapped noalias
/// parameters with noalias metadata specifying the new scope, and tag all
/// non-derived loads, stores and memory intrinsics with the new alias scopes.
static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
const DataLayout &DL, AAResults *CalleeAAR) {
if (!EnableNoAliasConversion)
return;
const Function *CalledFunc = CS.getCalledFunction();
SmallVector<const Argument *, 4> NoAliasArgs;
for (const Argument &Arg : CalledFunc->args())
if (Arg.hasNoAliasAttr() && !Arg.use_empty())
NoAliasArgs.push_back(&Arg);
if (NoAliasArgs.empty())
return;
// To do a good job, if a noalias variable is captured, we need to know if
// the capture point dominates the particular use we're considering.
DominatorTree DT;
DT.recalculate(const_cast<Function&>(*CalledFunc));
// noalias indicates that pointer values based on the argument do not alias
// pointer values which are not based on it. So we add a new "scope" for each
// noalias function argument. Accesses using pointers based on that argument
// become part of that alias scope, accesses using pointers not based on that
// argument are tagged as noalias with that scope.
DenseMap<const Argument *, MDNode *> NewScopes;
MDBuilder MDB(CalledFunc->getContext());
// Create a new scope domain for this function.
MDNode *NewDomain =
MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
const Argument *A = NoAliasArgs[i];
std::string Name = CalledFunc->getName();
if (A->hasName()) {
Name += ": %";
Name += A->getName();
} else {
Name += ": argument ";
Name += utostr(i);
}
// Note: We always create a new anonymous root here. This is true regardless
// of the linkage of the callee because the aliasing "scope" is not just a
// property of the callee, but also all control dependencies in the caller.
MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
NewScopes.insert(std::make_pair(A, NewScope));
}
// Iterate over all new instructions in the map; for all memory-access
// instructions, add the alias scope metadata.
for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
VMI != VMIE; ++VMI) {
if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
if (!VMI->second)
continue;
Instruction *NI = dyn_cast<Instruction>(VMI->second);
if (!NI)
continue;
bool IsArgMemOnlyCall = false, IsFuncCall = false;
SmallVector<const Value *, 2> PtrArgs;
if (const LoadInst *LI = dyn_cast<LoadInst>(I))
PtrArgs.push_back(LI->getPointerOperand());
else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
PtrArgs.push_back(SI->getPointerOperand());
else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
PtrArgs.push_back(VAAI->getPointerOperand());
else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
PtrArgs.push_back(CXI->getPointerOperand());
else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
PtrArgs.push_back(RMWI->getPointerOperand());
else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
// If we know that the call does not access memory, then we'll still
// know that about the inlined clone of this call site, and we don't
// need to add metadata.
if (ICS.doesNotAccessMemory())
continue;
IsFuncCall = true;
if (CalleeAAR) {
FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
if (MRB == FMRB_OnlyAccessesArgumentPointees ||