forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIRGenSIL.cpp
6454 lines (5552 loc) · 244 KB
/
IRGenSIL.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
//===--- IRGenSIL.cpp - Swift Per-Function IR Generation ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements basic setup and teardown for the class which
// performs IR generation for function bodies.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "irgensil"
#include "swift/AST/ASTContext.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/Types.h"
#include "swift/Basic/ExternalUnion.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/STLExtras.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/BasicBlockBits.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILLinkage.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/TerminatorUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Transforms/Utils/Local.h"
#include "CallEmission.h"
#include "EntryPointArgumentEmission.h"
#include "Explosion.h"
#include "GenArchetype.h"
#include "GenBuiltin.h"
#include "GenCall.h"
#include "GenCast.h"
#include "GenClass.h"
#include "GenConstant.h"
#include "GenDecl.h"
#include "GenEnum.h"
#include "GenExistential.h"
#include "GenFunc.h"
#include "GenHeap.h"
#include "GenIntegerLiteral.h"
#include "GenMeta.h"
#include "GenObjC.h"
#include "GenOpaque.h"
#include "GenPointerAuth.h"
#include "GenPoly.h"
#include "GenProto.h"
#include "GenStruct.h"
#include "GenTuple.h"
#include "GenType.h"
#include "IRGenDebugInfo.h"
#include "IRGenModule.h"
#include "MetadataLayout.h"
#include "MetadataRequest.h"
#include "NativeConventionSchema.h"
#include "ReferenceTypeInfo.h"
using namespace swift;
using namespace irgen;
namespace {
class LoweredValue;
struct DynamicallyEnforcedAddress {
Address Addr;
llvm::Value *ScratchBuffer;
};
struct CoroutineState {
Address Buffer;
llvm::Value *Continuation;
TemporarySet Temporaries;
};
/// Represents a SIL value lowered to IR, in one of these forms:
/// - an Address, corresponding to a SIL address value;
/// - an Explosion of (unmanaged) Values, corresponding to a SIL "register"; or
/// - a CallEmission for a partially-applied curried function or method.
class LoweredValue {
public:
enum class Kind {
/// The first two LoweredValue kinds correspond to a SIL address value.
///
/// The LoweredValue of an existential alloc_stack keeps an owning container
/// in addition to the address of the allocated buffer.
/// Depending on the allocated type, the container may be equal to the
/// buffer itself (for types with known sizes) or it may be the address
/// of a fixed-size container which points to the heap-allocated buffer.
/// In this case the address-part may be null, which means that the buffer
/// is not allocated yet.
ContainedAddress,
/// The LoweredValue of a resilient, generic, or loadable typed alloc_stack
/// keeps an optional stackrestore point in addition to the address of the
/// allocated buffer. For all other address values the stackrestore point is
/// just null.
/// If the stackrestore point is set (currently, this might happen for
/// opaque types: generic and resilient) the deallocation of the stack must
/// reset the stack pointer to this point.
StackAddress,
/// A @box together with the address of the box value.
OwnedAddress,
/// The lowered value of a begin_access instruction using dynamic
/// enforcement.
DynamicallyEnforcedAddress,
/// A normal value, represented as an exploded array of llvm Values.
ExplosionVector,
/// The special case of a single explosion.
SingletonExplosion,
/// A value that represents a function pointer.
FunctionPointer,
/// A value that represents an Objective-C method that must be called with
/// a form of objc_msgSend.
ObjCMethod,
/// The special case of an empty explosion.
EmptyExplosion,
/// A coroutine state.
CoroutineState,
};
Kind kind;
private:
using ExplosionVector = SmallVector<llvm::Value *, 4>;
using SingletonExplosion = llvm::Value*;
using Members = ExternalUnionMembers<ContainedAddress,
StackAddress,
OwnedAddress,
DynamicallyEnforcedAddress,
ExplosionVector,
SingletonExplosion,
FunctionPointer,
ObjCMethod,
CoroutineState,
void>;
static Members::Index getMemberIndexForKind(Kind kind) {
switch (kind) {
case Kind::ContainedAddress: return Members::indexOf<ContainedAddress>();
case Kind::StackAddress: return Members::indexOf<StackAddress>();
case Kind::OwnedAddress: return Members::indexOf<OwnedAddress>();
case Kind::DynamicallyEnforcedAddress: return Members::indexOf<DynamicallyEnforcedAddress>();
case Kind::ExplosionVector: return Members::indexOf<ExplosionVector>();
case Kind::SingletonExplosion: return Members::indexOf<SingletonExplosion>();
case Kind::FunctionPointer: return Members::indexOf<FunctionPointer>();
case Kind::ObjCMethod: return Members::indexOf<ObjCMethod>();
case Kind::CoroutineState: return Members::indexOf<CoroutineState>();
case Kind::EmptyExplosion: return Members::indexOf<void>();
}
llvm_unreachable("bad kind");
}
ExternalUnion<Kind, Members, getMemberIndexForKind> Storage;
public:
/// Create an address value without a stack restore point.
LoweredValue(const Address &address)
: kind(Kind::StackAddress) {
Storage.emplace<StackAddress>(kind, address);
}
/// Create an address value with an optional stack restore point.
LoweredValue(const StackAddress &address)
: kind(Kind::StackAddress) {
Storage.emplace<StackAddress>(kind, address);
}
/// Create an address value using dynamic enforcement.
LoweredValue(const DynamicallyEnforcedAddress &address)
: kind(Kind::DynamicallyEnforcedAddress) {
Storage.emplace<DynamicallyEnforcedAddress>(kind, address);
}
enum ContainerForUnallocatedAddress_t { ContainerForUnallocatedAddress };
/// Create an address value for an alloc_stack, consisting of a container and
/// a not yet allocated buffer.
LoweredValue(const Address &container, ContainerForUnallocatedAddress_t)
: kind(Kind::ContainedAddress) {
Storage.emplace<ContainedAddress>(kind, container, Address());
}
/// Create an address value for an alloc_stack, consisting of a container and
/// the address of the allocated buffer.
LoweredValue(const ContainedAddress &address)
: kind(Kind::ContainedAddress) {
Storage.emplace<ContainedAddress>(kind, address);
}
LoweredValue(const FunctionPointer &fn)
: kind(Kind::FunctionPointer) {
Storage.emplace<FunctionPointer>(kind, fn);
}
LoweredValue(ObjCMethod &&objcMethod)
: kind(Kind::ObjCMethod) {
Storage.emplace<ObjCMethod>(kind, std::move(objcMethod));
}
LoweredValue(Explosion &e) {
auto elts = e.claimAll();
if (elts.empty()) {
kind = Kind::EmptyExplosion;
} else if (elts.size() == 1) {
kind = Kind::SingletonExplosion;
Storage.emplace<SingletonExplosion>(kind, elts.front());
} else {
kind = Kind::ExplosionVector;
auto &explosion = Storage.emplace<ExplosionVector>(kind);
explosion.append(elts.begin(), elts.end());
}
}
LoweredValue(const OwnedAddress &boxWithAddress)
: kind(Kind::OwnedAddress) {
Storage.emplace<OwnedAddress>(kind, boxWithAddress);
}
LoweredValue(CoroutineState &&state)
: kind(Kind::CoroutineState) {
Storage.emplace<CoroutineState>(kind, std::move(state));
}
LoweredValue(LoweredValue &&lv)
: kind(lv.kind) {
Storage.moveConstruct(kind, std::move(lv.Storage));
}
LoweredValue &operator=(LoweredValue &&lv) {
Storage.moveAssign(kind, lv.kind, std::move(lv.Storage));
kind = lv.kind;
return *this;
}
~LoweredValue() {
Storage.destruct(kind);
}
bool isAddress() const {
return (kind == Kind::StackAddress ||
kind == Kind::DynamicallyEnforcedAddress);
}
bool isUnallocatedAddressInBuffer() const {
return kind == Kind::ContainedAddress &&
!Storage.get<ContainedAddress>(kind).getAddress().isValid();
}
bool isBoxWithAddress() const {
return kind == Kind::OwnedAddress;
}
const StackAddress &getStackAddress() const {
return Storage.get<StackAddress>(kind);
}
Address getContainerOfAddress() const {
const auto &containedAddress = Storage.get<ContainedAddress>(kind);
assert(containedAddress.getContainer().isValid() && "address has no container");
return containedAddress.getContainer();
}
Address getAddressInContainer() const {
const auto &containedAddress = Storage.get<ContainedAddress>(kind);
assert(containedAddress.getContainer().isValid() &&
"address has no container");
return containedAddress.getAddress();
}
const DynamicallyEnforcedAddress &getDynamicallyEnforcedAddress() const {
return Storage.get<DynamicallyEnforcedAddress>(kind);
}
Address getAnyAddress() const {
if (kind == LoweredValue::Kind::StackAddress) {
return Storage.get<StackAddress>(kind).getAddress();
} else if (kind == LoweredValue::Kind::ContainedAddress) {
return getAddressInContainer();
} else {
return getDynamicallyEnforcedAddress().Addr;
}
}
Address getAddressOfBox() const {
return Storage.get<OwnedAddress>(kind).getAddress();
}
ArrayRef<llvm::Value *> getKnownExplosionVector() const {
return Storage.get<ExplosionVector>(kind);
}
llvm::Value *getKnownSingletonExplosion() const {
return Storage.get<SingletonExplosion>(kind);
}
const FunctionPointer &getFunctionPointer() const {
return Storage.get<FunctionPointer>(kind);
}
const ObjCMethod &getObjCMethod() const {
return Storage.get<ObjCMethod>(kind);
}
const CoroutineState &getCoroutineState() const {
return Storage.get<CoroutineState>(kind);
}
/// Produce an explosion for this lowered value. Note that many
/// different storage kinds can be turned into an explosion.
Explosion getExplosion(IRGenFunction &IGF, SILType type) const {
Explosion e;
getExplosion(IGF, type, e);
return e;
}
void getExplosion(IRGenFunction &IGF, SILType type, Explosion &ex) const;
/// Produce an explosion which is known to be a single value.
llvm::Value *getSingletonExplosion(IRGenFunction &IGF, SILType type) const;
/// Produce a callee from this value.
Callee getCallee(IRGenFunction &IGF, llvm::Value *selfValue,
CalleeInfo &&calleeInfo) const;
};
using PHINodeVector = llvm::TinyPtrVector<llvm::PHINode*>;
/// Represents a lowered SIL basic block. This keeps track
/// of SIL branch arguments so that they can be lowered to LLVM phi nodes.
struct LoweredBB {
llvm::BasicBlock *bb;
PHINodeVector phis;
LoweredBB() = default;
explicit LoweredBB(llvm::BasicBlock *bb, PHINodeVector &&phis)
: bb(bb), phis(std::move(phis))
{}
};
/// Visits a SIL Function and generates LLVM IR.
class IRGenSILFunction :
public IRGenFunction, public SILInstructionVisitor<IRGenSILFunction>
{
public:
llvm::DenseMap<SILValue, LoweredValue> LoweredValues;
llvm::DenseMap<SILValue, StackAddress> LoweredPartialApplyAllocations;
llvm::DenseMap<SILType, LoweredValue> LoweredUndefs;
/// All alloc_ref instructions which allocate the object on the stack.
llvm::SmallPtrSet<SILInstruction *, 8> StackAllocs;
/// With closure captures it is actually possible to have two function
/// arguments that both have the same name. Until this is fixed, we need to
/// also hash the ArgNo here.
using StackSlotKey =
std::pair<unsigned, std::pair<const SILDebugScope *, StringRef>>;
/// Keeps track of the mapping of source variables to -O0 shadow copy allocas.
llvm::SmallDenseMap<StackSlotKey, Address, 8> ShadowStackSlots;
llvm::SmallDenseMap<Decl *, SmallString<4>, 8> AnonymousVariables;
unsigned NumAnonVars = 0;
/// Accumulative amount of allocated bytes on the stack. Used to limit the
/// size for stack promoted objects.
/// We calculate it on demand, so that we don't have to do it if the
/// function does not have any stack promoted allocations.
int EstimatedStackSize = -1;
llvm::MapVector<SILBasicBlock *, LoweredBB> LoweredBBs;
// Destination basic blocks for condfail traps.
llvm::SmallVector<llvm::BasicBlock *, 8> FailBBs;
SILFunction *CurSILFn;
// If valid, the address by means of which a return--which is direct in
// SIL--is passed indirectly in IR. Such indirection is necessary when the
// value which would be returned directly cannot fit into registers.
Address IndirectReturn;
// A cached dominance analysis.
std::unique_ptr<DominanceInfo> Dominance;
IRGenSILFunction(IRGenModule &IGM, SILFunction *f);
~IRGenSILFunction();
/// Generate IR for the SIL Function.
void emitSILFunction();
/// Calculates EstimatedStackSize.
void estimateStackSize();
void setLoweredValue(SILValue v, LoweredValue &&lv) {
auto inserted = LoweredValues.insert({v, std::move(lv)});
assert(inserted.second && "already had lowered value for sil value?!");
(void)inserted;
}
/// Create a new Address corresponding to the given SIL address value.
void setLoweredAddress(SILValue v, const Address &address) {
assert(v->getType().isAddress() && "address for non-address value?!");
setLoweredValue(v, address);
}
void setLoweredStackAddress(SILValue v, const StackAddress &address) {
assert(v->getType().isAddress() && "address for non-address value?!");
setLoweredValue(v, address);
}
void setLoweredDynamicallyEnforcedAddress(SILValue v,
const Address &address,
llvm::Value *scratch) {
assert(v->getType().isAddress() && "address for non-address value?!");
setLoweredValue(v, DynamicallyEnforcedAddress{address, scratch});
}
void setContainerOfUnallocatedAddress(SILValue v,
const Address &buffer) {
assert(v->getType().isAddress() && "address for non-address value?!");
setLoweredValue(v,
LoweredValue(buffer, LoweredValue::ContainerForUnallocatedAddress));
}
void overwriteAllocatedAddress(SILValue v, const Address &address) {
assert(v->getType().isAddress() && "address for non-address value?!");
auto it = LoweredValues.find(v);
assert(it != LoweredValues.end() && "no existing entry for overwrite?");
assert(it->second.isUnallocatedAddressInBuffer() &&
"not an unallocated address");
it->second = ContainedAddress(it->second.getContainerOfAddress(), address);
}
void setAllocatedAddressForBuffer(SILValue v, const Address &allocedAddress);
/// Create a new Explosion corresponding to the given SIL value.
void setLoweredExplosion(SILValue v, Explosion &e) {
assert(v->getType().isObject() && "explosion for address value?!");
setLoweredValue(v, LoweredValue(e));
}
void setCorrespondingLoweredValues(SILInstructionResultArray results,
Explosion &allValues) {
for (SILValue result : results) {
auto resultType = result->getType();
auto &resultTI = getTypeInfo(resultType);
// If the value is indirect, the next explosion value should just be
// a pointer.
if (resultType.isAddress()) {
auto pointer = allValues.claimNext();
setLoweredAddress(result, resultTI.getAddressForPointer(pointer));
continue;
}
// Otherwise, claim out the right number of values.
Explosion resultValue;
cast<LoadableTypeInfo>(resultTI).reexplode(*this, allValues, resultValue);
setLoweredExplosion(result, resultValue);
}
}
void setLoweredBox(SILValue v, const OwnedAddress &box) {
assert(v->getType().isObject() && "box for address value?!");
setLoweredValue(v, LoweredValue(box));
}
/// Map the given SIL value to a FunctionPointer value.
void setLoweredFunctionPointer(SILValue v, const FunctionPointer &fnPtr) {
assert(v->getType().isObject() && "function for address value?!");
assert(v->getType().is<SILFunctionType>() &&
"function for non-function value?!");
setLoweredValue(v, fnPtr);
}
/// Create a new Objective-C method corresponding to the given SIL value.
void setLoweredObjCMethod(SILValue v, SILDeclRef method) {
assert(v->getType().isObject() && "function for address value?!");
assert(v->getType().is<SILFunctionType>() &&
"function for non-function value?!");
setLoweredValue(v, ObjCMethod{method, SILType(), false});
}
/// Create a new Objective-C method corresponding to the given SIL value that
/// starts its search from the given search type.
///
/// Unlike \c setLoweredObjCMethod, which finds the method in the actual
/// runtime type of the object, this routine starts at the static type of the
/// object and searches up the class hierarchy (toward superclasses).
///
/// \param searchType The class from which the Objective-C runtime will start
/// its search for a method.
///
/// \param startAtSuper Whether we want to start at the superclass of the
/// static type (vs. the static type itself).
void setLoweredObjCMethodBounded(SILValue v, SILDeclRef method,
SILType searchType, bool startAtSuper) {
assert(v->getType().isObject() && "function for address value?!");
assert(v->getType().is<SILFunctionType>() &&
"function for non-function value?!");
setLoweredValue(v, ObjCMethod{method, searchType, startAtSuper});
}
void setLoweredCoroutine(SILValue tokenResult, CoroutineState &&state) {
setLoweredValue(tokenResult, std::move(state));
}
LoweredValue &getUndefLoweredValue(SILType t) {
auto found = LoweredUndefs.find(t);
if (found != LoweredUndefs.end())
return found->second;
auto &ti = getTypeInfo(t);
switch (t.getCategory()) {
case SILValueCategory::Address: {
Address undefAddr = ti.getAddressForPointer(
llvm::UndefValue::get(ti.getStorageType()->getPointerTo()));
LoweredUndefs.insert({t, LoweredValue(undefAddr)});
break;
}
case SILValueCategory::Object: {
auto schema = ti.getSchema();
Explosion e;
for (auto &elt : schema) {
assert(!elt.isAggregate()
&& "non-scalar element in loadable type schema?!");
e.add(llvm::UndefValue::get(elt.getScalarType()));
}
LoweredUndefs.insert({t, LoweredValue(e)});
break;
}
}
found = LoweredUndefs.find(t);
assert(found != LoweredUndefs.end());
return found->second;
}
/// Get the LoweredValue corresponding to the given SIL value, which must
/// have been lowered.
LoweredValue &getLoweredValue(SILValue v) {
if (isa<SILUndef>(v))
return getUndefLoweredValue(v->getType());
auto foundValue = LoweredValues.find(v);
assert(foundValue != LoweredValues.end() &&
"no lowered explosion for sil value!");
return foundValue->second;
}
/// Get the Address of a SIL value of address type, which must have been
/// lowered.
Address getLoweredAddress(SILValue v) {
return getLoweredValue(v).getAnyAddress();
}
StackAddress getLoweredStackAddress(SILValue v) {
return getLoweredValue(v).getStackAddress();
}
llvm::Value *getLoweredDynamicEnforcementScratchBuffer(BeginAccessInst *v) {
return getLoweredValue(v).getDynamicallyEnforcedAddress().ScratchBuffer;
}
const CoroutineState &getLoweredCoroutine(SILValue v) {
return getLoweredValue(v).getCoroutineState();
}
/// Add the unmanaged LLVM values lowered from a SIL value to an explosion.
void getLoweredExplosion(SILValue v, Explosion &e) {
getLoweredValue(v).getExplosion(*this, v->getType(), e);
}
/// Create an Explosion containing the unmanaged LLVM values lowered from a
/// SIL value.
Explosion getLoweredExplosion(SILValue v) {
return getLoweredValue(v).getExplosion(*this, v->getType());
}
/// Return the single member of the lowered explosion for the
/// given SIL value.
llvm::Value *getLoweredSingletonExplosion(SILValue v) {
return getLoweredValue(v).getSingletonExplosion(*this, v->getType());
}
LoweredBB &getLoweredBB(SILBasicBlock *bb) {
auto foundBB = LoweredBBs.find(bb);
assert(foundBB != LoweredBBs.end() && "no llvm bb for sil bb?!");
return foundBB->second;
}
TypeExpansionContext getExpansionContext() {
return TypeExpansionContext(*CurSILFn);
}
SILType getLoweredTypeInContext(SILType ty) {
return CurSILFn->getModule()
.Types.getLoweredType(ty.getASTType(), getExpansionContext())
.getCategoryType(ty.getCategory());
}
StringRef getOrCreateAnonymousVarName(VarDecl *Decl) {
llvm::SmallString<4> &Name = AnonymousVariables[Decl];
if (Name.empty()) {
{
llvm::raw_svector_ostream S(Name);
S << '_' << NumAnonVars++;
}
AnonymousVariables.insert({Decl, Name});
}
return Name;
}
template <class DebugVarCarryingInst>
StringRef getVarName(DebugVarCarryingInst *i, bool &IsAnonymous) {
auto VarInfo = i->getVarInfo();
if (!VarInfo)
return StringRef();
StringRef Name = i->getVarInfo()->Name;
// The $match variables generated by the type checker are not
// guaranteed to be unique within their scope, but they have
// unique VarDecls.
if ((Name.empty() || Name == "$match") && i->getDecl()) {
IsAnonymous = true;
return getOrCreateAnonymousVarName(i->getDecl());
}
return Name;
}
/// To make it unambiguous whether a `var` binding has been initialized,
/// zero-initialize the shadow copy alloca. LLDB uses the first pointer-sized
/// field to recognize to detect uninitizialized variables. This can be
/// removed once swiftc switches to @llvm.dbg.addr() intrinsics.
void zeroInit(llvm::AllocaInst *AI) {
if (!AI)
return;
// Only do this at -Onone.
uint64_t Size = *AI->getAllocationSizeInBits(IGM.DataLayout) / 8;
if (IGM.IRGen.Opts.shouldOptimize() || !Size)
return;
llvm::IRBuilder<> ZeroInitBuilder(AI->getNextNode());
// No debug location is how LLVM marks prologue instructions.
ZeroInitBuilder.SetCurrentDebugLocation(nullptr);
ZeroInitBuilder.CreateMemSet(
AI, llvm::ConstantInt::get(IGM.Int8Ty, 0),
Size, llvm::MaybeAlign(AI->getAlignment()));
}
/// Account for bugs in LLVM.
///
/// - When a variable is spilled into a stack slot, LiveDebugValues fails to
/// recognize a restore of that slot for a different variable.
///
/// - The LLVM type legalizer currently doesn't update debug
/// intrinsics when a large value is split up into smaller
/// pieces. Note that this heuristic as a bit too conservative
/// on 32-bit targets as it will also fire for doubles.
///
/// - CodeGen Prepare may drop dbg.values pointing to PHI instruction.
bool needsShadowCopy(llvm::Value *Storage) {
// If we have a constant data vector, we always need a shadow copy due to
// bugs in LLVM.
if (isa<llvm::ConstantDataVector>(Storage))
return true;
return !isa<llvm::Constant>(Storage);
}
#ifndef NDEBUG
/// Check if \p Val can be stored into \p Alloca, and emit some diagnostic
/// info if it can't.
bool canAllocaStoreValue(Address Alloca, llvm::Value *Val,
SILDebugVariable VarInfo,
const SILDebugScope *Scope) {
bool canStore =
cast<llvm::PointerType>(Alloca->getType())->getElementType() ==
Val->getType();
if (canStore)
return true;
llvm::errs() << "Invalid shadow copy:\n"
<< " Value : " << *Val << "\n"
<< " Alloca: " << *Alloca.getAddress() << "\n"
<< "---\n"
<< "Previous shadow copy into " << VarInfo.Name
<< " in the same scope!\n"
<< "Scope:\n";
Scope->print(getSILModule());
return false;
}
#endif
/// Unconditionally emit a stack shadow copy of an \c llvm::Value.
llvm::Value *emitShadowCopy(llvm::Value *Storage, const SILDebugScope *Scope,
SILDebugVariable VarInfo,
llvm::Optional<Alignment> _Align) {
auto Align = _Align.getValueOr(IGM.getPointerAlignment());
unsigned ArgNo = VarInfo.ArgNo;
auto &Alloca = ShadowStackSlots[{ArgNo, {Scope, VarInfo.Name}}];
if (!Alloca.isValid())
Alloca = createAlloca(Storage->getType(), Align, VarInfo.Name + ".debug");
zeroInit(cast<llvm::AllocaInst>(Alloca.getAddress()));
assert(canAllocaStoreValue(Alloca, Storage, VarInfo, Scope) &&
"bad scope?");
ArtificialLocation AutoRestore(Scope, IGM.DebugInfo.get(), Builder);
Builder.CreateStore(Storage, Alloca.getAddress(), Align);
return Alloca.getAddress();
}
/// At -Onone, emit a shadow copy of an Address in an alloca, so the
/// register allocator doesn't elide the dbg.value intrinsic when
/// register pressure is high. There is a trade-off to this: With
/// shadow copies, we lose the precise lifetime.
llvm::Value *emitShadowCopyIfNeeded(llvm::Value *Storage,
const SILDebugScope *Scope,
SILDebugVariable VarInfo,
bool IsAnonymous,
llvm::Optional<Alignment> Align = None) {
// Never emit shadow copies when optimizing, or if already on the stack. No
// debug info is emitted for refcounts either. Shadow copies are also
// turned off for async functions, because they make it impossible to track
// debug info during coroutine splitting. Instead we are relying on LLVM's
// CoroSplit.cpp to emit shadow copies.
if (IGM.IRGen.Opts.DisableDebuggerShadowCopies ||
IGM.IRGen.Opts.shouldOptimize() || IsAnonymous || CurSILFn->isAsync() ||
isa<llvm::AllocaInst>(Storage) || isa<llvm::UndefValue>(Storage) ||
!needsShadowCopy(Storage))
return Storage;
// Emit a shadow copy.
return emitShadowCopy(Storage, Scope, VarInfo, Align);
}
/// Like \c emitShadowCopyIfNeeded() but takes an \c Address instead of an
/// \c llvm::Value.
llvm::Value *emitShadowCopyIfNeeded(Address Storage,
const SILDebugScope *Scope,
SILDebugVariable VarInfo,
bool IsAnonymous) {
return emitShadowCopyIfNeeded(Storage.getAddress(), Scope, VarInfo,
IsAnonymous, Storage.getAlignment());
}
/// Like \c emitShadowCopyIfNeeded() but takes an exploded value.
void emitShadowCopyIfNeeded(SILValue &SILVal, const SILDebugScope *Scope,
SILDebugVariable VarInfo, bool IsAnonymous,
llvm::SmallVectorImpl<llvm::Value *> ©) {
Explosion e = getLoweredExplosion(SILVal);
// Only do this at -O0.
if (IGM.IRGen.Opts.DisableDebuggerShadowCopies ||
IGM.IRGen.Opts.shouldOptimize() || IsAnonymous || CurSILFn->isAsync()) {
auto vals = e.claimAll();
copy.append(vals.begin(), vals.end());
return;
}
// Single or empty values.
if (e.size() <= 1) {
auto vals = e.claimAll();
for (auto val : vals)
copy.push_back(
emitShadowCopyIfNeeded(val, Scope, VarInfo, IsAnonymous));
return;
}
SILType Type = SILVal->getType();
auto <I = cast<LoadableTypeInfo>(IGM.getTypeInfo(Type));
auto Alloca = LTI.allocateStack(*this, Type, VarInfo.Name + ".debug");
zeroInit(cast<llvm::AllocaInst>(Alloca.getAddress().getAddress()));
ArtificialLocation AutoRestore(Scope, IGM.DebugInfo.get(), Builder);
LTI.initialize(*this, e, Alloca.getAddress(), false /* isOutlined */);
copy.push_back(Alloca.getAddressPointer());
}
/// Force all archetypes referenced by the type to be bound by this point.
/// TODO: just make sure that we have a path to them that the debug info
/// can follow.
void bindArchetypes(swift::Type Ty) {
auto runtimeTy = IGM.getRuntimeReifiedType(Ty->getCanonicalType());
if (!IGM.IRGen.Opts.shouldOptimize() && runtimeTy->hasArchetype())
runtimeTy.visit([&](CanType t) {
if (auto archetype = dyn_cast<ArchetypeType>(t))
emitTypeMetadataRef(archetype);
});
}
/// Emit debug info for a function argument or a local variable.
template <typename StorageType>
void emitDebugVariableDeclaration(StorageType Storage, DebugTypeInfo Ty,
SILType SILTy, const SILDebugScope *DS,
VarDecl *VarDecl, SILDebugVariable VarInfo,
IndirectionKind Indirection = DirectValue) {
// TODO: fix demangling for C++ types (SR-13223).
if (swift::TypeBase *ty = SILTy.getASTType().getPointer()) {
if (MetatypeType *metaTy = dyn_cast<MetatypeType>(ty))
ty = metaTy->getRootClass().getPointer();
if (ty->getStructOrBoundGenericStruct() &&
ty->getStructOrBoundGenericStruct()->getClangDecl() &&
isa<clang::CXXRecordDecl>(
ty->getStructOrBoundGenericStruct()->getClangDecl()))
return;
}
assert(IGM.DebugInfo && "debug info not enabled");
if (VarInfo.ArgNo) {
PrologueLocation AutoRestore(IGM.DebugInfo.get(), Builder);
IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, Ty, DS, VarDecl,
VarInfo, Indirection);
} else
IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, Ty, DS, VarDecl,
VarInfo, Indirection);
}
void emitFailBB() {
if (!FailBBs.empty()) {
// Move the trap basic blocks to the end of the function.
for (auto *FailBB : FailBBs) {
auto &BlockList = CurFn->getBasicBlockList();
BlockList.splice(BlockList.end(), BlockList, FailBB);
}
}
}
//===--------------------------------------------------------------------===//
// SIL instruction lowering
//===--------------------------------------------------------------------===//
void visitSILBasicBlock(SILBasicBlock *BB);
void emitErrorResultVar(CanSILFunctionType FnTy,
SILResultInfo ErrorInfo,
DebugValueInst *DbgValue);
void emitDebugInfoForAllocStack(AllocStackInst *i, const TypeInfo &type,
llvm::Value *addr);
void visitAllocStackInst(AllocStackInst *i);
void visitAllocRefInst(AllocRefInst *i);
void visitAllocRefDynamicInst(AllocRefDynamicInst *i);
void visitAllocBoxInst(AllocBoxInst *i);
void visitProjectBoxInst(ProjectBoxInst *i);
void visitApplyInst(ApplyInst *i);
void visitTryApplyInst(TryApplyInst *i);
void visitFullApplySite(FullApplySite i);
void visitPartialApplyInst(PartialApplyInst *i);
void visitBuiltinInst(BuiltinInst *i);
void visitFunctionRefBaseInst(FunctionRefBaseInst *i);
void visitFunctionRefInst(FunctionRefInst *i);
void visitDynamicFunctionRefInst(DynamicFunctionRefInst *i);
void visitPreviousDynamicFunctionRefInst(PreviousDynamicFunctionRefInst *i);
void visitAllocGlobalInst(AllocGlobalInst *i);
void visitGlobalAddrInst(GlobalAddrInst *i);
void visitGlobalValueInst(GlobalValueInst *i);
void visitBaseAddrForOffsetInst(BaseAddrForOffsetInst *i);
void visitIntegerLiteralInst(IntegerLiteralInst *i);
void visitFloatLiteralInst(FloatLiteralInst *i);
void visitStringLiteralInst(StringLiteralInst *i);
void visitLoadInst(LoadInst *i);
void visitStoreInst(StoreInst *i);
void visitAssignInst(AssignInst *i) {
llvm_unreachable("assign is not valid in canonical SIL");
}
void visitAssignByWrapperInst(AssignByWrapperInst *i) {
llvm_unreachable("assign_by_wrapper is not valid in canonical SIL");
}
void visitMarkUninitializedInst(MarkUninitializedInst *i) {
llvm_unreachable("mark_uninitialized is not valid in canonical SIL");
}
void visitMarkFunctionEscapeInst(MarkFunctionEscapeInst *i) {
llvm_unreachable("mark_function_escape is not valid in canonical SIL");
}
void visitLoadBorrowInst(LoadBorrowInst *i) {
llvm_unreachable("unimplemented");
}
void visitDebugValueInst(DebugValueInst *i);
void visitDebugValueAddrInst(DebugValueAddrInst *i);
void visitRetainValueInst(RetainValueInst *i);
void visitRetainValueAddrInst(RetainValueAddrInst *i);
void visitCopyValueInst(CopyValueInst *i);
void visitReleaseValueInst(ReleaseValueInst *i);
void visitReleaseValueAddrInst(ReleaseValueAddrInst *i);
void visitDestroyValueInst(DestroyValueInst *i);
void visitAutoreleaseValueInst(AutoreleaseValueInst *i);
void visitSetDeallocatingInst(SetDeallocatingInst *i);
void visitObjectInst(ObjectInst *i) {
llvm_unreachable("object instruction cannot appear in a function");
}
void visitStructInst(StructInst *i);
void visitTupleInst(TupleInst *i);
void visitEnumInst(EnumInst *i);
void visitInitEnumDataAddrInst(InitEnumDataAddrInst *i);
void visitSelectEnumInst(SelectEnumInst *i);
void visitSelectEnumAddrInst(SelectEnumAddrInst *i);
void visitSelectValueInst(SelectValueInst *i);
void visitUncheckedEnumDataInst(UncheckedEnumDataInst *i);
void visitUncheckedTakeEnumDataAddrInst(UncheckedTakeEnumDataAddrInst *i);
void visitInjectEnumAddrInst(InjectEnumAddrInst *i);
void visitObjCProtocolInst(ObjCProtocolInst *i);
void visitMetatypeInst(MetatypeInst *i);
void visitValueMetatypeInst(ValueMetatypeInst *i);
void visitExistentialMetatypeInst(ExistentialMetatypeInst *i);
void visitTupleExtractInst(TupleExtractInst *i);
void visitDestructureTupleInst(DestructureTupleInst *i) {
llvm_unreachable("unimplemented");
}
void visitDestructureStructInst(DestructureStructInst *i) {
llvm_unreachable("unimplemented");
}
void visitTupleElementAddrInst(TupleElementAddrInst *i);
void visitStructExtractInst(StructExtractInst *i);
void visitStructElementAddrInst(StructElementAddrInst *i);
void visitRefElementAddrInst(RefElementAddrInst *i);
void visitRefTailAddrInst(RefTailAddrInst *i);
void visitClassMethodInst(ClassMethodInst *i);
void visitSuperMethodInst(SuperMethodInst *i);
void visitObjCMethodInst(ObjCMethodInst *i);
void visitObjCSuperMethodInst(ObjCSuperMethodInst *i);
void visitWitnessMethodInst(WitnessMethodInst *i);
void visitAllocValueBufferInst(AllocValueBufferInst *i);
void visitProjectValueBufferInst(ProjectValueBufferInst *i);
void visitDeallocValueBufferInst(DeallocValueBufferInst *i);
void visitOpenExistentialAddrInst(OpenExistentialAddrInst *i);
void visitOpenExistentialMetatypeInst(OpenExistentialMetatypeInst *i);
void visitOpenExistentialRefInst(OpenExistentialRefInst *i);
void visitOpenExistentialValueInst(OpenExistentialValueInst *i);
void visitInitExistentialAddrInst(InitExistentialAddrInst *i);
void visitInitExistentialValueInst(InitExistentialValueInst *i);
void visitInitExistentialMetatypeInst(InitExistentialMetatypeInst *i);
void visitInitExistentialRefInst(InitExistentialRefInst *i);
void visitDeinitExistentialAddrInst(DeinitExistentialAddrInst *i);
void visitDeinitExistentialValueInst(DeinitExistentialValueInst *i);
void visitAllocExistentialBoxInst(AllocExistentialBoxInst *i);
void visitOpenExistentialBoxInst(OpenExistentialBoxInst *i);
void visitOpenExistentialBoxValueInst(OpenExistentialBoxValueInst *i);
void visitProjectExistentialBoxInst(ProjectExistentialBoxInst *i);
void visitDeallocExistentialBoxInst(DeallocExistentialBoxInst *i);
void visitProjectBlockStorageInst(ProjectBlockStorageInst *i);
void visitInitBlockStorageHeaderInst(InitBlockStorageHeaderInst *i);
void visitFixLifetimeInst(FixLifetimeInst *i);
void visitEndLifetimeInst(EndLifetimeInst *i) {
llvm_unreachable("unimplemented");
}
void
visitUncheckedOwnershipConversionInst(UncheckedOwnershipConversionInst *i) {
llvm_unreachable("unimplemented");
}
void visitBeginBorrowInst(BeginBorrowInst *i) {
llvm_unreachable("unimplemented");