From d67c98a62ab0c50e859df34ee258a58a6c0f676d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexis=20Laferrie=CC=80re?= Date: Mon, 11 Jan 2021 12:52:32 -0800 Subject: [PATCH 001/116] [next] Update reference to initializeDwarfEHPreparePass Fix rdar://73006157 --- tools/swift-llvm-opt/LLVMOpt.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/swift-llvm-opt/LLVMOpt.cpp b/tools/swift-llvm-opt/LLVMOpt.cpp index 2d02be6d9c3ba..251a0d8ca833a 100644 --- a/tools/swift-llvm-opt/LLVMOpt.cpp +++ b/tools/swift-llvm-opt/LLVMOpt.cpp @@ -237,7 +237,7 @@ int main(int argc, char **argv) { initializeAtomicExpandPass(Registry); initializeRewriteSymbolsLegacyPassPass(Registry); initializeWinEHPreparePass(Registry); - initializeDwarfEHPreparePass(Registry); + initializeDwarfEHPrepareLegacyPassPass(Registry); initializeSjLjEHPreparePass(Registry); // Register Swift Only Passes. From cc44a2b8f253a18a3c1fe802ef2d521649104179 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Mon, 11 Jan 2021 13:13:16 -0800 Subject: [PATCH 002/116] Pass clang::ASTContext for serialization. --- lib/Serialization/Serialization.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp index bc0b1cce8ab5e..f7cb6b7db005b 100644 --- a/lib/Serialization/Serialization.cpp +++ b/lib/Serialization/Serialization.cpp @@ -4492,7 +4492,8 @@ class ClangToSwiftBasicWriter : public: ClangToSwiftBasicWriter(Serializer &S, SmallVectorImpl &record) - : swift::DataStreamBasicWriter(S.getASTContext()), + : swift::DataStreamBasicWriter( + S.getASTContext().getClangModuleLoader()->getClangASTContext()), S(S), Record(record), Types(*this) {} void writeUInt64(uint64_t value) { From 14540176b83a02aee2f05f5e738ed4f94ea56872 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Thu, 14 Jan 2021 08:50:16 -0800 Subject: [PATCH 003/116] Adjust to llvm's byVal parameter attributes needing the storage type rdar://73172496 --- lib/IRGen/GenCall.cpp | 43 ++++++++++++++++++++++++++++++++++--------- lib/IRGen/GenCall.h | 3 ++- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/lib/IRGen/GenCall.cpp b/lib/IRGen/GenCall.cpp index 9109e53e3c751..5728e4c0e2b43 100644 --- a/lib/IRGen/GenCall.cpp +++ b/lib/IRGen/GenCall.cpp @@ -528,9 +528,10 @@ void IRGenModule::addSwiftErrorAttributes(llvm::AttributeList &attrs, void irgen::addByvalArgumentAttributes(IRGenModule &IGM, llvm::AttributeList &attrs, - unsigned argIndex, Alignment align) { + unsigned argIndex, Alignment align, + llvm::Type *storageType) { llvm::AttrBuilder b; - b.addAttribute(llvm::Attribute::ByVal); + b.addByValAttr(storageType); b.addAttribute(llvm::Attribute::getWithAlignment( IGM.getLLVMContext(), llvm::Align(align.getValue()))); attrs = attrs.addAttributes(IGM.getLLVMContext(), @@ -1579,10 +1580,12 @@ void SignatureExpansion::expandExternalSignatureTypes() { auto paramTy = getSILFuncConventions().getSILType( param, IGM.getMaximalTypeExpansionContext()); auto ¶mTI = cast(IGM.getTypeInfo(paramTy)); - if (AI.getIndirectByVal()) + if (AI.getIndirectByVal()) { addByvalArgumentAttributes( IGM, Attrs, getCurParamIndex(), - Alignment(AI.getIndirectAlign().getQuantity())); + Alignment(AI.getIndirectAlign().getQuantity()), + paramTI.getStorageType()); + } addPointerParameter(paramTI.getStorageType()); break; } @@ -2645,6 +2648,27 @@ llvm::CallInst *CallEmission::emitCallSite() { return call; } +static llvm::AttributeList +fixUpTypesInByValAndStructRetAttributes(llvm::FunctionType *fnType, + llvm::AttributeList attrList) { + auto &context = fnType->getContext(); + for (unsigned i = 0; i < fnType->getNumParams(); ++i) { + auto paramTy = fnType->getParamType(i); + auto attrListIndex = llvm::AttributeList::FirstArgIndex + i; + if (attrList.hasParamAttr(i, llvm::Attribute::StructRet) && + paramTy->getPointerElementType() != attrList.getParamStructRetType(i)) + attrList = attrList.replaceAttributeType( + context, attrListIndex, llvm::Attribute::StructRet, + paramTy->getPointerElementType()); + if (attrList.hasParamAttr(i, llvm::Attribute::ByVal) && + paramTy->getPointerElementType() != attrList.getParamByValType(i)) + attrList = attrList.replaceAttributeType( + context, attrListIndex, llvm::Attribute::ByVal, + paramTy->getPointerElementType()); + } + return attrList; +} + llvm::CallInst *IRBuilder::CreateCall(const FunctionPointer &fn, ArrayRef args) { assert(fn.getKind() == FunctionPointer::KindTy::Function); @@ -2659,11 +2683,12 @@ llvm::CallInst *IRBuilder::CreateCall(const FunctionPointer &fn, } assert(!isTrapIntrinsic(fn.getRawPointer()) && "Use CreateNonMergeableTrap"); - llvm::CallInst *call = IRBuilderBase::CreateCall( - cast( - fn.getRawPointer()->getType()->getPointerElementType()), - fn.getRawPointer(), args, bundles); - call->setAttributes(fn.getAttributes()); + auto fnTy = cast( + fn.getRawPointer()->getType()->getPointerElementType()); + llvm::CallInst *call = + IRBuilderBase::CreateCall(fnTy, fn.getRawPointer(), args, bundles); + call->setAttributes( + fixUpTypesInByValAndStructRetAttributes(fnTy, fn.getAttributes())); call->setCallingConv(fn.getCallingConv()); return call; } diff --git a/lib/IRGen/GenCall.h b/lib/IRGen/GenCall.h index f3bbddf5e3c19..613f28d6515e9 100644 --- a/lib/IRGen/GenCall.h +++ b/lib/IRGen/GenCall.h @@ -329,7 +329,8 @@ namespace irgen { void addByvalArgumentAttributes(IRGenModule &IGM, llvm::AttributeList &attrs, unsigned argIndex, - Alignment align); + Alignment align, + llvm::Type *storageType); /// Add signext or zeroext attribute set for an argument that needs /// extending. From 2e735ae12e609bfedac320fcabc7843b04abaa52 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Thu, 14 Jan 2021 16:26:30 -0800 Subject: [PATCH 004/116] Fix IR test case --- test/IRGen/abitypes.swift | 6 +++--- test/IRGen/big_types_corner_cases.sil | 4 ++-- test/IRGen/c_functions.swift | 4 ++-- test/IRGen/c_layout.sil | 4 ++-- test/IRGen/objc_class_export.swift | 4 ++-- test/IRGen/objc_structs.swift | 10 +++++----- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/test/IRGen/abitypes.swift b/test/IRGen/abitypes.swift index fcc836b9d70a2..204fd4fcfedaf 100644 --- a/test/IRGen/abitypes.swift +++ b/test/IRGen/abitypes.swift @@ -46,7 +46,7 @@ class Foo { // x86_64-macosx: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(double %0, double %1, double %2, double %3, %T8abitypes3FooC* swiftself %4) {{.*}} { - // x86_64-macosx: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, %TSo6CGRectV* byval align 8 %2) {{[#0-9]*}} { + // x86_64-macosx: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, %TSo6CGRectV* byval({{.*}}) align 8 %2) {{[#0-9]*}} { // armv7-ios: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // armv7-ios: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x i32] %2) {{[#0-9]*}} { // armv7s-ios: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { @@ -112,7 +112,7 @@ class Foo { } // Ensure that MyRect is passed as an indirect-byval on x86_64 because we run out of registers for direct arguments - // x86_64-macosx: define hidden float @"$s8abitypes3FooC25getXFromRectIndirectByVal{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, float %2, float %3, float %4, float %5, float %6, float %7, float %8, %TSo6MyRectV* byval align 8 %9) {{[#0-9]*}} { + // x86_64-macosx: define hidden float @"$s8abitypes3FooC25getXFromRectIndirectByVal{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, float %2, float %3, float %4, float %5, float %6, float %7, float %8, %TSo6MyRectV* byval({{.*}}) align 8 %9) {{[#0-9]*}} { @objc dynamic func getXFromRectIndirectByVal(_: Float, second _: Float, third _: Float, fourth _: Float, fifth _: Float, sixth _: Float, @@ -128,7 +128,7 @@ class Foo { // x86_64-macosx: alloca // x86_64-macosx: alloca // x86_64-macosx: [[TEMP:%.*]] = alloca [[TEMPTYPE:%.*]], align 8 - // x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, float, float, float, float, float, float, float, [[TEMPTYPE]]*)*)(i8* %{{.*}}, i8* %{{.*}}, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, [[TEMPTYPE]]* byval align 8 [[TEMP]]) + // x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, float, float, float, float, float, float, float, [[TEMPTYPE]]*)*)(i8* %{{.*}}, i8* %{{.*}}, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, [[TEMPTYPE]]* byval({{.*}}) align 8 [[TEMP]]) // x86_64-macosx: ret float [[RESULT]] return getXFromRectIndirectByVal(f, second: f, third: f, fourth: f, fifth: f, sixth: f, seventh: f, withRect: r); } diff --git a/test/IRGen/big_types_corner_cases.sil b/test/IRGen/big_types_corner_cases.sil index 3c27b90b7a5d3..94bd93812e38b 100644 --- a/test/IRGen/big_types_corner_cases.sil +++ b/test/IRGen/big_types_corner_cases.sil @@ -37,7 +37,7 @@ public struct BigBigStruct { } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @testBitfieldInBlock -// CHECK: call void {{%.*}}(%TSo11BitfieldOneV* noalias nocapture sret({{.*}}) {{%.*}}, %objc_block* {{%.*}}, %TSo11BitfieldOneV* byval align 8 {{%.*}}) +// CHECK: call void {{%.*}}(%TSo11BitfieldOneV* noalias nocapture sret({{.*}}) {{%.*}}, %objc_block* {{%.*}}, %TSo11BitfieldOneV* byval({{.*}}) align 8 {{%.*}}) sil @testBitfieldInBlock : $@convention(thin) (@owned @convention(block) (BitfieldOne) -> BitfieldOne, BitfieldOne) -> BitfieldOne { entry(%b : $@convention(block) (BitfieldOne) -> BitfieldOne, %x : $BitfieldOne): %r = apply %b(%x) : $@convention(block) (BitfieldOne) -> BitfieldOne @@ -45,7 +45,7 @@ entry(%b : $@convention(block) (BitfieldOne) -> BitfieldOne, %x : $BitfieldOne): } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @testTupleExtract -// CHECK: call void {{%.*}}(%TSo11BitfieldOneV* noalias nocapture sret({{.*}}) {{%.*}}, %objc_block* {{%.*}}, %TSo11BitfieldOneV* byval align 8 {{%.*}}) +// CHECK: call void {{%.*}}(%TSo11BitfieldOneV* noalias nocapture sret({{.*}}) {{%.*}}, %objc_block* {{%.*}}, %TSo11BitfieldOneV* byval({{.*}}) align 8 {{%.*}}) sil @testTupleExtract : $@convention(thin) (@owned (BitfieldOne, @convention(block) (BitfieldOne) -> BitfieldOne), BitfieldOne) -> BitfieldOne { entry(%b : $(BitfieldOne, @convention(block) (BitfieldOne) -> (BitfieldOne)), %x : $BitfieldOne): %a = tuple_extract %b : $(BitfieldOne, @convention(block) (BitfieldOne) -> (BitfieldOne)), 1 diff --git a/test/IRGen/c_functions.swift b/test/IRGen/c_functions.swift index 3d42cfc1c3657..b3763850a0896 100644 --- a/test/IRGen/c_functions.swift +++ b/test/IRGen/c_functions.swift @@ -22,9 +22,9 @@ func test_indirect_by_val_alignment() { // x86_64-LABEL: define hidden swiftcc void @"$s11c_functions30test_indirect_by_val_alignmentyyF"() // x86_64: %indirect-temporary = alloca %TSo7a_thinga, align [[ALIGN:[0-9]+]] // x86_64: [[CAST:%.*]] = bitcast %TSo7a_thinga* %indirect-temporary to %struct.a_thing* -// SYSV-x86_64: call void @log_a_thing(%struct.a_thing* byval align [[ALIGN]] [[CAST]]) +// SYSV-x86_64: call void @log_a_thing(%struct.a_thing* byval({{.*}}) align [[ALIGN]] [[CAST]]) // WIN-x86_64: call void @log_a_thing(%struct.a_thing* [[CAST]]) -// x86_64: define internal void @log_a_thing(%struct.a_thing* {{(byval align [[ALIGN]])?}} +// x86_64: define internal void @log_a_thing(%struct.a_thing* {{(byval(%struct.a_thing) align [[ALIGN]])?}} // aarch64: define hidden swiftcc void @"$s11c_functions30test_indirect_by_val_alignmentyyF"() // arm64: define hidden swiftcc void @"$s11c_functions30test_indirect_by_val_alignmentyyF"() diff --git a/test/IRGen/c_layout.sil b/test/IRGen/c_layout.sil index 6649a69784512..35660de5536f9 100644 --- a/test/IRGen/c_layout.sil +++ b/test/IRGen/c_layout.sil @@ -90,7 +90,7 @@ bb0: // CHECK-x86_64: [[ADDR_M:%.*]] = getelementptr inbounds %TSo11BitfieldOneV, %TSo11BitfieldOneV* [[ARG]], i32 0, i32 8 // CHECK-x86_64: [[ADDR_M_V:%.*]] = getelementptr inbounds %Ts6UInt32V, %Ts6UInt32V* [[ADDR_M]], i32 0, i32 0 // CHECK-x86_64: store i32 [[M]], i32* [[ADDR_M_V]], align 8 -// CHECK-SYSV-x86_64: call void @consumeBitfieldOne(%TSo11BitfieldOneV* byval align 8 [[ARG]]) +// CHECK-SYSV-x86_64: call void @consumeBitfieldOne(%TSo11BitfieldOneV* byval({{.*}}) align 8 [[ARG]]) // CHECK-WIN-x86_64: call void @consumeBitfieldOne(%TSo11BitfieldOneV* [[ARG]]) // CHECK-x86_64: ret void @@ -365,7 +365,7 @@ entry(%b : $@convention(block) (CChar) -> CChar, %c : $CChar): } // CHECK-x86_64-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @testBitfieldInBlock -// CHECK-SYSV-x86_64: call void {{%.*}}(%TSo11BitfieldOneV* noalias nocapture sret({{.*}}) {{%.*}}, %objc_block* {{%.*}}, %TSo11BitfieldOneV* byval align 8 {{%.*}}) +// CHECK-SYSV-x86_64: call void {{%.*}}(%TSo11BitfieldOneV* noalias nocapture sret({{.*}}) {{%.*}}, %objc_block* {{%.*}}, %TSo11BitfieldOneV* byval({{.*}}) align 8 {{%.*}}) // CHECK-WIN-x86_64: call void {{%.*}}(%TSo11BitfieldOneV* noalias nocapture sret({{.*}}) {{%.*}}, %objc_block* {{%.*}}, %TSo11BitfieldOneV* {{%.*}}) sil @testBitfieldInBlock : $@convention(thin) (@owned @convention(block) (BitfieldOne) -> BitfieldOne, BitfieldOne) -> BitfieldOne { entry(%b : $@convention(block) (BitfieldOne) -> BitfieldOne, %x : $BitfieldOne): diff --git a/test/IRGen/objc_class_export.swift b/test/IRGen/objc_class_export.swift index 46eb04f2c4e1a..41f56b912b5bc 100644 --- a/test/IRGen/objc_class_export.swift +++ b/test/IRGen/objc_class_export.swift @@ -81,7 +81,7 @@ struct BigStructWithNativeObjects { @objc func drawInRect(dirty dirty: NSRect) { } - // CHECK: define internal void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tFTo"([[OPAQUE:%.*]]* %0, i8* %1, [[NSRECT]]* byval align 8 %2) {{[#0-9]*}} { + // CHECK: define internal void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tFTo"([[OPAQUE:%.*]]* %0, i8* %1, [[NSRECT]]* byval({{.*}}) align 8 %2) {{[#0-9]*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]* // CHECK: call swiftcc void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) // CHECK: } @@ -97,7 +97,7 @@ struct BigStructWithNativeObjects { @objc func convertRectToBacking(r r: NSRect) -> NSRect { return r } - // CHECK: define internal void @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tFTo"([[NSRECT]]* noalias nocapture sret({{.*}}) %0, [[OPAQUE5:%.*]]* %1, i8* %2, [[NSRECT]]* byval align 8 %3) {{[#0-9]*}} { + // CHECK: define internal void @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tFTo"([[NSRECT]]* noalias nocapture sret({{.*}}) %0, [[OPAQUE5:%.*]]* %1, i8* %2, [[NSRECT]]* byval({{.*}} align 8 %3) {{[#0-9]*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) diff --git a/test/IRGen/objc_structs.swift b/test/IRGen/objc_structs.swift index 933d9c6b507da..e2ac58e3ba07d 100644 --- a/test/IRGen/objc_structs.swift +++ b/test/IRGen/objc_structs.swift @@ -27,7 +27,7 @@ func getFrame(_ g: Gizmo) -> NSRect { // CHECK: define hidden swiftcc void @"$s12objc_structs8setFrame{{[_0-9a-zA-Z]*}}F"(%TSo5GizmoC* %0, double %1, double %2, double %3, double %4) {{.*}} { func setFrame(_ g: Gizmo, frame: NSRect) { // CHECK: load i8*, i8** @"\01L_selector(setFrame:)" - // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}}) + // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval({{.*}}) align 8 {{.*}}) g.setFrame(frame) } // CHECK: } @@ -41,14 +41,14 @@ func makeRect(_ a: Double, b: Double, c: Double, d: Double) -> NSRect { // CHECK: define hidden swiftcc [[stringLayout:[^@]*]] @"$s12objc_structs14stringFromRect{{[_0-9a-zA-Z]*}}F"(double %0, double %1, double %2, double %3) {{.*}} { func stringFromRect(_ r: NSRect) -> String { - // CHECK: call [[OPAQUE0:.*]]* @NSStringFromRect(%struct.NSRect* byval align 8 {{.*}}) + // CHECK: call [[OPAQUE0:.*]]* @NSStringFromRect(%struct.NSRect* byval({{.*}}) align 8 {{.*}}) return NSStringFromRect(r) } // CHECK: } // CHECK: define hidden swiftcc { double, double, double, double } @"$s12objc_structs9insetRect{{[_0-9a-zA-Z]*}}F"(double %0, double %1, double %2, double %3, double %4, double %5) func insetRect(_ r: NSRect, x: Double, y: Double) -> NSRect { - // CHECK: call void @NSInsetRect(%struct.NSRect* noalias nocapture sret({{.*}}) {{.*}}, %struct.NSRect* byval align 8 {{.*}}, double {{.*}}, double {{.*}}) + // CHECK: call void @NSInsetRect(%struct.NSRect* noalias nocapture sret({{.*}}) {{.*}}, %struct.NSRect* byval({{.*}}) align 8 {{.*}}, double {{.*}}, double {{.*}}) return NSInsetRect(r, x, y) } // CHECK: } @@ -56,13 +56,13 @@ func insetRect(_ r: NSRect, x: Double, y: Double) -> NSRect { // CHECK: define hidden swiftcc { double, double, double, double } @"$s12objc_structs19convertRectFromBase{{[_0-9a-zA-Z]*}}F"([[NSVIEW]]* %0, double %1, double %2, double %3, double %4) func convertRectFromBase(_ v: NSView, r: NSRect) -> NSRect { // CHECK: load i8*, i8** @"\01L_selector(convertRectFromBase:)", align 8 - // CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[NSRECT]]* noalias nocapture sret({{.*}}) {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}}) + // CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[NSRECT]]* noalias nocapture sret({{.*}}) {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval({{.*}}) align 8 {{.*}}) return v.convertRect(fromBase: r) } // CHECK: } // CHECK: define hidden swiftcc { {{.*}}*, {{.*}}*, {{.*}}*, {{.*}}* } @"$s12objc_structs20useStructOfNSStringsySo0deF0VADF"({{.*}}* %0, {{.*}}* %1, {{.*}}* %2, {{.*}}* %3) -// CHECK: call void @useStructOfNSStringsInObjC(%struct.StructOfNSStrings* noalias nocapture sret({{.*}}) {{%.*}}, %struct.StructOfNSStrings* byval align 8 {{%.*}}) +// CHECK: call void @useStructOfNSStringsInObjC(%struct.StructOfNSStrings* noalias nocapture sret({{.*}}) {{%.*}}, %struct.StructOfNSStrings* byval({{.*}}) align 8 {{%.*}}) func useStructOfNSStrings(_ s: StructOfNSStrings) -> StructOfNSStrings { return useStructOfNSStringsInObjC(s) } From 30094a373059b5c6eea672278d239ab2a4cd94e0 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Thu, 14 Jan 2021 16:43:47 -0800 Subject: [PATCH 005/116] More IR test fixes --- test/ClangImporter/CoreGraphics_test.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/ClangImporter/CoreGraphics_test.swift b/test/ClangImporter/CoreGraphics_test.swift index ef16031857079..f0490eb5c3a1e 100644 --- a/test/ClangImporter/CoreGraphics_test.swift +++ b/test/ClangImporter/CoreGraphics_test.swift @@ -116,8 +116,8 @@ public func testRenames(transform: CGAffineTransform, context: CGContext, context.clip(to: rect) context.clip(to: rect, mask: image) -// CHECK: call void @CGContextClipToRect(%struct.CGContext* [[CONTEXT]], %struct.CGRect* nonnull byval align 8 %{{.*}}) -// CHECK: call void @CGContextClipToMask(%struct.CGContext* [[CONTEXT]], %struct.CGRect* nonnull byval align 8 %{{.*}}, %struct.CGImage* %{{.*}}) +// CHECK: call void @CGContextClipToRect(%struct.CGContext* [[CONTEXT]], %struct.CGRect* nonnull byval({{.*}}) align 8 %{{.*}}) +// CHECK: call void @CGContextClipToMask(%struct.CGContext* [[CONTEXT]], %struct.CGRect* nonnull byval({{.*}}) align 8 %{{.*}}, %struct.CGImage* %{{.*}}) var slice = CGRect.zero var remainder = CGRect.zero @@ -125,7 +125,7 @@ public func testRenames(transform: CGAffineTransform, context: CGContext, from: edge) assert((slice, remainder) == rect.divided(atDistance: CGFloat(2.0), from: edge)) -// CHECK: call void @CGRectDivide(%struct.CGRect* nonnull byval align 8 %{{.*}}, %struct.CGRect* nonnull %{{.*}}, %struct.CGRect* nonnull %{{.*}}, double {{2\.0+.*}}, i32 %{{.*}}) +// CHECK: call void @CGRectDivide(%struct.CGRect* nonnull byval({{.*}}) align 8 %{{.*}}, %struct.CGRect* nonnull %{{.*}}, %struct.CGRect* nonnull %{{.*}}, double {{2\.0+.*}}, i32 %{{.*}}) // // CHECK: ret void } From d411b2eda1a2816214cca2e821edc6c264275531 Mon Sep 17 00:00:00 2001 From: David Zarzycki Date: Fri, 22 Jan 2021 11:48:18 -0500 Subject: [PATCH 006/116] Unbreak building against apple/main --- lib/ClangImporter/ClangImporter.cpp | 3 ++- lib/Immediate/Immediate.cpp | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp index 6d9f0c961bb39..c5ce5e791c403 100644 --- a/lib/ClangImporter/ClangImporter.cpp +++ b/lib/ClangImporter/ClangImporter.cpp @@ -821,7 +821,8 @@ bool ClangImporter::canReadPCH(StringRef PCHFilename) { &Impl.Instance->getModuleCache()); auto invocation = std::make_shared(*Impl.Invocation); - invocation->getPreprocessorOpts().DisablePCHValidation = false; + invocation->getPreprocessorOpts().DisablePCHOrModuleValidation = + clang::DisableValidationForModuleKind::None; invocation->getPreprocessorOpts().AllowPCHWithCompilerErrors = false; invocation->getHeaderSearchOpts().ModulesValidateSystemHeaders = true; invocation->getLangOpts()->NeededByPCHOrCompilationUsesPCH = true; diff --git a/lib/Immediate/Immediate.cpp b/lib/Immediate/Immediate.cpp index 93720e4df4139..f2318bfad57b7 100644 --- a/lib/Immediate/Immediate.cpp +++ b/lib/Immediate/Immediate.cpp @@ -33,6 +33,7 @@ #include "llvm/ExecutionEngine/Orc/DebugUtils.h" #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/LLJIT.h" +#include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h" #include "llvm/ExecutionEngine/Orc/OrcRPCTargetProcessControl.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Transforms/IPO.h" From 8971b9548b4752de3a072b9b80edcf5b8fe95bf9 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Thu, 28 Jan 2021 12:44:15 -0800 Subject: [PATCH 007/116] Re-enable async argument debug info test. rdar//7247369 --- test/DebugInfo/async-args.swift | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/test/DebugInfo/async-args.swift b/test/DebugInfo/async-args.swift index 300a56e52929f..5132060e93836 100644 --- a/test/DebugInfo/async-args.swift +++ b/test/DebugInfo/async-args.swift @@ -10,24 +10,24 @@ func withGenericArg(_ msg: T) async { // this up after coroutine splitting. // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYlF"(%swift.task* %0, %swift.executor* %1, %swift.context* swiftasync %2) // CHECK: call void @llvm.dbg.declare(metadata %swift.context** %[[ALLOCA:[^,]*]], - // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression( - // CHECK-SAME: DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) - // CHECK: call void @llvm.dbg.declare(metadata %swift.context** %[[ALLOCA]], // CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression( // CHECK-SAME: DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}})) + // CHECK: call void @llvm.dbg.declare(metadata %swift.context** %[[ALLOCA]], + // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression( + // CHECK-SAME: DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) // CHECK: store %swift.context* %2, %swift.context** %[[ALLOCA]], align await forceSplit() // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYlF.resume.0"(i8* %0, i8* %1, i8* swiftasync %2) - // CHECK: store i8* %2, i8** %[[ALLOCA:.*]], align - // CHECK: call void @llvm.dbg.declare(metadata i8** %[[ALLOCA]], - // CHECK-SAME: metadata ![[TAU_R:[0-9]+]], metadata !DIExpression( + // CHECK: call void @llvm.dbg.declare(metadata i8** %[[ALLOCA:[^,]*]], + // CHECK-SAME: metadata ![[MSG_R:[0-9]+]], metadata !DIExpression( // CHECK-SAME: DW_OP_deref, DW_OP_plus_uconst, [[OFFSET:[0-9]+]], - // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}})) + // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) // CHECK: call void @llvm.dbg.declare(metadata i8** %[[ALLOCA]], - // CHECK-SAME: metadata ![[MSG_R:[0-9]+]], metadata !DIExpression( + // CHECK-SAME: metadata ![[TAU_R:[0-9]+]], metadata !DIExpression( // CHECK-SAME: DW_OP_deref, DW_OP_plus_uconst, [[OFFSET]], - // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) + // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}})) + // CHECK: store i8* %2, i8** %[[ALLOCA]], align use(msg) } @@ -35,8 +35,8 @@ func withGenericArg(_ msg: T) async { runAsyncAndBlock { await withGenericArg("hello (asynchronously)") } -// CHECK: ![[MSG]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[TAU]] = !DILocalVariable(name: "$\CF\84_0_0", -// CHECK: ![[TAU_R]] = !DILocalVariable(name: "$\CF\84_0_0", +// CHECK: ![[MSG]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[MSG_R]] = !DILocalVariable(name: "msg", arg: 1, +// CHECK: ![[TAU_R]] = !DILocalVariable(name: "$\CF\84_0_0", From 9cc21c4f91459b10aeaf9b5f4c94cfc2d9ff4d9e Mon Sep 17 00:00:00 2001 From: Erik Eckstein Date: Tue, 2 Feb 2021 09:04:45 +0100 Subject: [PATCH 008/116] Fix a compilation error introduced by merging --- lib/IRGen/IRGenDebugInfo.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index 736babeb12750..265fa857cccd9 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -2070,8 +2070,8 @@ void IRGenDebugInfoImpl::setInlinedTrapLocation(IRBuilder &Builder, TheLastScope = TheLastScope->InlinedCallSite; } auto LastLocation = llvm::DILocation::get( - IGM.getLLVMContext(), LastDebugLoc.line, LastDebugLoc.column, - getOrCreateScope(TheLastScope)); + IGM.getLLVMContext(), LastFilenameAndLocation.line, + LastFilenameAndLocation.column, getOrCreateScope(TheLastScope)); // FIXME: This location should point to stdlib instead of being artificial. auto DL = llvm::DILocation::get(IGM.getLLVMContext(), 0, 0, getOrCreateScope(Scope), LastLocation); From cff11f2c8d0958c385374a3a7b5024986fcc1335 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Thu, 11 Feb 2021 10:38:03 -0800 Subject: [PATCH 009/116] Adjust IRGen undef.sil test for current llvm-project --- test/IRGen/undef.sil | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/IRGen/undef.sil b/test/IRGen/undef.sil index d66d1c882453d..f5b234e5c6bc1 100644 --- a/test/IRGen/undef.sil +++ b/test/IRGen/undef.sil @@ -6,9 +6,9 @@ import Builtin // CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @undefined() {{.*}} { // CHECK: entry: -// CHECK: store i64 undef, i64* poison, align 8 -// CHECK: store i8 undef, i8* poison, align 8 -// CHECK: store i8* undef, i8** poison, align 8 +// CHECK: store i64 undef, i64* undef, align 8 +// CHECK: store i8 undef, i8* undef, align 8 +// CHECK: store i8* undef, i8** undef, align 8 // CHECK: ret void // CHECK: } sil @undefined : $() -> () { From 7e8cf9b2d3b8e8ddb31b807ac7911e254db921d9 Mon Sep 17 00:00:00 2001 From: Robert Widmann Date: Wed, 3 Mar 2021 17:10:58 -0800 Subject: [PATCH 010/116] [next] Adapt To RISC-V V Builtin Types https://reviews.llvm.org/D92715 Adds new builtins for use with RISC-V intrinsics. Match clang here and define stubs for these types. --- lib/AST/ClangTypeConverter.cpp | 4 ++++ lib/ClangImporter/ClangAdapter.cpp | 11 +++++++---- lib/ClangImporter/ImportType.cpp | 11 +++++++---- lib/IRGen/GenCall.cpp | 11 +++++++---- 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/lib/AST/ClangTypeConverter.cpp b/lib/AST/ClangTypeConverter.cpp index 053f1ae2444dd..6e56885abbbe1 100644 --- a/lib/AST/ClangTypeConverter.cpp +++ b/lib/AST/ClangTypeConverter.cpp @@ -85,6 +85,10 @@ getClangBuiltinTypeFromKind(const clang::ASTContext &context, case clang::BuiltinType::Id: \ return context.Id##Ty; #include "clang/Basic/PPCTypes.def" +#define RVV_TYPE(Name, Id, SingletonId) \ + case clang::BuiltinType::Id: \ + return context.Id##Ty; +#include "clang/Basic/RISCVVTypes.def" } // Not a valid BuiltinType. diff --git a/lib/ClangImporter/ClangAdapter.cpp b/lib/ClangImporter/ClangAdapter.cpp index 511e71e18d952..7f58453fdf9f1 100644 --- a/lib/ClangImporter/ClangAdapter.cpp +++ b/lib/ClangImporter/ClangAdapter.cpp @@ -468,16 +468,19 @@ OmissionTypeName importer::getClangTypeNameForOmission(clang::ASTContext &ctx, return OmissionTypeName(); // ARM SVE builtin types that don't have Swift equivalents. -#define SVE_TYPE(Name, Id, ...) \ - case clang::BuiltinType::Id: +#define SVE_TYPE(Name, Id, ...) case clang::BuiltinType::Id: #include "clang/Basic/AArch64SVEACLETypes.def" return OmissionTypeName(); // PPC MMA builtin types that don't have Swift equivalents. -#define PPC_VECTOR_TYPE(Name, Id, Size) \ - case clang::BuiltinType::Id: +#define PPC_VECTOR_TYPE(Name, Id, Size) case clang::BuiltinType::Id: #include "clang/Basic/PPCTypes.def" return OmissionTypeName(); + + // RISC-V V builtin types that don't have Swift equivalents. +#define RVV_TYPE(Name, Id, Size) case clang::BuiltinType::Id: +#include "clang/Basic/RISCVVTypes.def" + return OmissionTypeName(); } } diff --git a/lib/ClangImporter/ImportType.cpp b/lib/ClangImporter/ImportType.cpp index 0a894ce5f807d..05d95149eedf3 100644 --- a/lib/ClangImporter/ImportType.cpp +++ b/lib/ClangImporter/ImportType.cpp @@ -361,16 +361,19 @@ namespace { return Type(); // ARM SVE builtin types that don't have Swift equivalents. -#define SVE_TYPE(Name, Id, ...) \ - case clang::BuiltinType::Id: +#define SVE_TYPE(Name, Id, ...) case clang::BuiltinType::Id: #include "clang/Basic/AArch64SVEACLETypes.def" return Type(); // PPC SVE builtin types that don't have Swift equivalents. -#define PPC_VECTOR_TYPE(Name, Id, Size) \ - case clang::BuiltinType::Id: +#define PPC_VECTOR_TYPE(Name, Id, Size) case clang::BuiltinType::Id: #include "clang/Basic/PPCTypes.def" return Type(); + + // RISC-V V builtin types that don't have Swift equivalents. +#define RVV_TYPE(Name, Id, Size) case clang::BuiltinType::Id: +#include "clang/Basic/RISCVVTypes.def" + return Type(); } llvm_unreachable("Invalid BuiltinType."); diff --git a/lib/IRGen/GenCall.cpp b/lib/IRGen/GenCall.cpp index 0e40dfd187b87..6c46a02d70b07 100644 --- a/lib/IRGen/GenCall.cpp +++ b/lib/IRGen/GenCall.cpp @@ -1250,17 +1250,20 @@ namespace { llvm_unreachable("OpenCL type in ABI lowering"); // We should never see ARM SVE types at all. -#define SVE_TYPE(Name, Id, ...) \ - case clang::BuiltinType::Id: +#define SVE_TYPE(Name, Id, ...) case clang::BuiltinType::Id: #include "clang/Basic/AArch64SVEACLETypes.def" llvm_unreachable("ARM SVE type in ABI lowering"); // We should never see PPC MMA types at all. -#define PPC_VECTOR_TYPE(Name, Id, Size) \ - case clang::BuiltinType::Id: +#define PPC_VECTOR_TYPE(Name, Id, Size) case clang::BuiltinType::Id: #include "clang/Basic/PPCTypes.def" llvm_unreachable("PPC MMA type in ABI lowering"); + // We should never see RISC-V V types at all. +#define RVV_TYPE(Name, Id, Size) case clang::BuiltinType::Id: +#include "clang/Basic/RISCVVTypes.def" + llvm_unreachable("RISC-V V type in ABI lowering"); + // Handle all the integer types as opaque values. #define BUILTIN_TYPE(Id, SingletonId) #define SIGNED_TYPE(Id, SingletonId) \ From 0e0825a3e8bc7cff0039903934c422b5e833451d Mon Sep 17 00:00:00 2001 From: Robert Widmann Date: Wed, 3 Mar 2021 18:49:33 -0800 Subject: [PATCH 011/116] Work Around MSVC Regression in std::less --- lib/Basic/OutputFileMap.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/Basic/OutputFileMap.cpp b/lib/Basic/OutputFileMap.cpp index 26535a373beaf..085fc905b74b8 100644 --- a/lib/Basic/OutputFileMap.cpp +++ b/lib/Basic/OutputFileMap.cpp @@ -88,7 +88,10 @@ void OutputFileMap::dump(llvm::raw_ostream &os, bool Sort) const { const TypeToPathMap &Map = InputPair.second; std::vector Pairs; Pairs.insert(Pairs.end(), Map.begin(), Map.end()); - std::sort(Pairs.begin(), Pairs.end()); + std::sort(Pairs.begin(), Pairs.end(), [](const TypePathPair &LHS, + const TypePathPair &RHS) -> bool { + return LHS < RHS; + }); for (auto &OutputPair : Pairs) { printOutputPair(InputPair.first, OutputPair); } From 2dfe3551a356797db49086a91db8059dc135655e Mon Sep 17 00:00:00 2001 From: Robert Widmann Date: Wed, 3 Mar 2021 18:49:57 -0800 Subject: [PATCH 012/116] Adapt to ModuleFileExtensions Growing RTTI Add a temporary workaround for https://reviews.llvm.org/D96155, which added a sealed RTTI hierarchy to ModuleFileExtension. We pass a bogus value for now. A better solution will arrive in D97702. --- lib/ClangImporter/ImporterImpl.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/ClangImporter/ImporterImpl.h b/lib/ClangImporter/ImporterImpl.h index 58f31fc287a43..2e418099366a0 100644 --- a/lib/ClangImporter/ImporterImpl.h +++ b/lib/ClangImporter/ImporterImpl.h @@ -1524,7 +1524,9 @@ class SwiftNameLookupExtension : public clang::ModuleFileExtension { LookupTableMap &tables, ASTContext &ctx, ClangSourceBufferImporter &buffersForDiagnostics, const PlatformAvailability &avail, bool inferIAM) - : pchLookupTable(pchLookupTable), lookupTables(tables), swiftCtx(ctx), + : // An unfortunate workaround until D97702 lands. + clang::ModuleFileExtension(static_cast(42)), + pchLookupTable(pchLookupTable), lookupTables(tables), swiftCtx(ctx), buffersForDiagnostics(buffersForDiagnostics), availability(avail), inferImportAsMember(inferIAM) {} From 0de3016f256b8aceeffacd914a1751e9ff612126 Mon Sep 17 00:00:00 2001 From: Robert Widmann Date: Wed, 3 Mar 2021 20:03:35 -0800 Subject: [PATCH 013/116] Use Explicit Alignment in CmpXchg Functions Adapt to https://reviews.llvm.org/D97223 --- lib/IRGen/GenBuiltin.cpp | 5 +++-- lib/IRGen/IRGenFunction.cpp | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/IRGen/GenBuiltin.cpp b/lib/IRGen/GenBuiltin.cpp index 7cd173008c644..2c11d95b037a3 100644 --- a/lib/IRGen/GenBuiltin.cpp +++ b/lib/IRGen/GenBuiltin.cpp @@ -647,7 +647,8 @@ if (Builtin.ID == BuiltinValueKind::id) { \ pointer = IGF.Builder.CreateBitCast(pointer, llvm::PointerType::getUnqual(cmp->getType())); llvm::Value *value = IGF.Builder.CreateAtomicCmpXchg( - pointer, cmp, newval, successOrdering, failureOrdering, + pointer, cmp, newval, llvm::MaybeAlign(), + successOrdering, failureOrdering, isSingleThread ? llvm::SyncScope::SingleThread : llvm::SyncScope::System); cast(value)->setVolatile(isVolatile); @@ -715,7 +716,7 @@ if (Builtin.ID == BuiltinValueKind::id) { \ pointer = IGF.Builder.CreateBitCast(pointer, llvm::PointerType::getUnqual(val->getType())); llvm::Value *value = IGF.Builder.CreateAtomicRMW( - SubOpcode, pointer, val, ordering, + SubOpcode, pointer, val, llvm::MaybeAlign(), ordering, isSingleThread ? llvm::SyncScope::SingleThread : llvm::SyncScope::System); cast(value)->setVolatile(isVolatile); diff --git a/lib/IRGen/IRGenFunction.cpp b/lib/IRGen/IRGenFunction.cpp index 1251032888489..f1f5c04ff605f 100644 --- a/lib/IRGen/IRGenFunction.cpp +++ b/lib/IRGen/IRGenFunction.cpp @@ -668,6 +668,7 @@ void IRGenFunction::emitAwaitAsyncContinuation( contAwaitSyncAddr->getType()->getPointerElementType(), 1); auto results = Builder.CreateAtomicCmpXchg( contAwaitSyncAddr, null, one, + llvm::MaybeAlign(), llvm::AtomicOrdering::Release /*success ordering*/, llvm::AtomicOrdering::Acquire /* failure ordering */, llvm::SyncScope::System); @@ -710,6 +711,7 @@ void IRGenFunction::emitAwaitAsyncContinuation( auto results = Builder.CreateAtomicCmpXchg( contAwaitSyncAddr, null, one, + llvm::MaybeAlign(), llvm::AtomicOrdering::Release /*success ordering*/, llvm::AtomicOrdering::Acquire /* failure ordering */, llvm::SyncScope::System); From 40e420641041912dfa970ae9d7e5fcc9eee29aa0 Mon Sep 17 00:00:00 2001 From: Robert Widmann Date: Wed, 3 Mar 2021 21:30:00 -0800 Subject: [PATCH 014/116] Fixup Coverage Mapping Adapt to https://reviews.llvm.org/D95753 --- lib/IRGen/GenCoverage.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/IRGen/GenCoverage.cpp b/lib/IRGen/GenCoverage.cpp index bdedf23c75619..b2b87ffa7239f 100644 --- a/lib/IRGen/GenCoverage.cpp +++ b/lib/IRGen/GenCoverage.cpp @@ -68,12 +68,10 @@ void IRGenModule::emitCoverageMapping() { auto remapper = getOptions().CoveragePrefixMap; // Awkwardly munge absolute filenames into a vector of StringRefs. llvm::SmallVector FilenameStrs; - llvm::SmallVector FilenameRefs; for (StringRef Name : Files) { llvm::SmallString<256> Path(Name); llvm::sys::fs::make_absolute(Path); FilenameStrs.push_back(remapper.remapPath(Path)); - FilenameRefs.push_back(FilenameStrs.back()); } // Encode the filenames. @@ -81,7 +79,7 @@ void IRGenModule::emitCoverageMapping() { llvm::LLVMContext &Ctx = getLLVMContext(); { llvm::raw_string_ostream OS(Filenames); - llvm::coverage::CoverageFilenamesSectionWriter(FilenameRefs).write(OS); + llvm::coverage::CoverageFilenamesSectionWriter(FilenameStrs).write(OS); } auto *FilenamesVal = llvm::ConstantDataArray::getString(Ctx, Filenames, false); From 3b7b158ee13c1f84528174f4b5f16904876b0acd Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 30 Mar 2021 21:13:41 -0700 Subject: [PATCH 015/116] [Basic] Update for fs::createUniqueFile changes in llvm https://reviews.llvm.org/D97785 reintroduced a flags parameter to `fs::createUniqueFile`, this time preceding `params`. (Compare: https://github.com/apple/swift/pull/18472) rdar://76036856 --- lib/Basic/FileSystem.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/Basic/FileSystem.cpp b/lib/Basic/FileSystem.cpp index 963ea61c65b62..6cafa430832dd 100644 --- a/lib/Basic/FileSystem.cpp +++ b/lib/Basic/FileSystem.cpp @@ -101,7 +101,8 @@ tryToOpenTemporaryFile(Optional &openedStream, int fd; const unsigned perms = fs::all_read | fs::all_write; - std::error_code EC = fs::createUniqueFile(tempPath, fd, tempPath, perms); + std::error_code EC = fs::createUniqueFile(tempPath, fd, tempPath, + fs::OF_None, perms); if (EC) { // Ignore the specific error; the caller has to fall back to not using a From 319fba53075e80c60da32020b70467b3d73165cb Mon Sep 17 00:00:00 2001 From: Cyndy Ishida Date: Mon, 5 Apr 2021 12:48:30 -0700 Subject: [PATCH 016/116] [TBDGen] update header includes for TextAPI move, NFC (#36755) --- lib/TBDGen/TBDGen.cpp | 8 ++++---- lib/TBDGen/TBDGenRequests.cpp | 2 +- lib/TBDGen/TBDGenVisitor.h | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/TBDGen/TBDGen.cpp b/lib/TBDGen/TBDGen.cpp index 1589db2dc2145..4c2cc49631a0c 100644 --- a/lib/TBDGen/TBDGen.cpp +++ b/lib/TBDGen/TBDGen.cpp @@ -46,10 +46,10 @@ #include "llvm/Support/Process.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/YAMLParser.h" -#include "llvm/TextAPI/MachO/InterfaceFile.h" -#include "llvm/TextAPI/MachO/Symbol.h" -#include "llvm/TextAPI/MachO/TextAPIReader.h" -#include "llvm/TextAPI/MachO/TextAPIWriter.h" +#include "llvm/TextAPI/InterfaceFile.h" +#include "llvm/TextAPI/Symbol.h" +#include "llvm/TextAPI/TextAPIReader.h" +#include "llvm/TextAPI/TextAPIWriter.h" #include "APIGen.h" #include "TBDGenVisitor.h" diff --git a/lib/TBDGen/TBDGenRequests.cpp b/lib/TBDGen/TBDGenRequests.cpp index a71bdcd925632..a298987054bd1 100644 --- a/lib/TBDGen/TBDGenRequests.cpp +++ b/lib/TBDGen/TBDGenRequests.cpp @@ -19,7 +19,7 @@ #include "swift/Subsystems.h" #include "swift/TBDGen/TBDGen.h" #include "clang/Basic/TargetInfo.h" -#include "llvm/TextAPI/MachO/InterfaceFile.h" +#include "llvm/TextAPI/InterfaceFile.h" #include "APIGen.h" diff --git a/lib/TBDGen/TBDGenVisitor.h b/lib/TBDGen/TBDGenVisitor.h index 328fc024a110a..92d8db4bfd8f8 100644 --- a/lib/TBDGen/TBDGenVisitor.h +++ b/lib/TBDGen/TBDGenVisitor.h @@ -29,7 +29,7 @@ #include "swift/SIL/TypeLowering.h" #include "llvm/ADT/StringSet.h" #include "llvm/ADT/Triple.h" -#include "llvm/TextAPI/MachO/InterfaceFile.h" +#include "llvm/TextAPI/InterfaceFile.h" using namespace swift::irgen; using StringSet = llvm::StringSet<>; From 6f8a640c73ba282e7cc20e4fcc98102a0d19dae6 Mon Sep 17 00:00:00 2001 From: gsecula Date: Tue, 4 May 2021 18:59:01 -0400 Subject: [PATCH 017/116] [RTTI] Updated ModuleFileExtension constructor Constructor call of ModuleFileExtension has been updated to allow the toolchain to build. Previously this constructor call was passed a bogus value as a workaround in response to clang change https://reviews.llvm.org/D96155. The workaround was added in commit 2dfe3551a356797db49086a91db8059dc135655e. Due to clang update https://reviews.llvm.org/D97702, ModuleFileExtension no longer requires constructor parameters. I was unable to verify this fix works due to other problems in next branch. --- lib/ClangImporter/ImporterImpl.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ClangImporter/ImporterImpl.h b/lib/ClangImporter/ImporterImpl.h index afa49201becd2..a9ea54e3f8f77 100644 --- a/lib/ClangImporter/ImporterImpl.h +++ b/lib/ClangImporter/ImporterImpl.h @@ -1572,8 +1572,8 @@ class SwiftNameLookupExtension : public clang::ModuleFileExtension { LookupTableMap &tables, ASTContext &ctx, ClangSourceBufferImporter &buffersForDiagnostics, const PlatformAvailability &avail) - : // An unfortunate workaround until D97702 lands. - clang::ModuleFileExtension(static_cast(42)), + : // Update in response to D97702 landing. + clang::ModuleFileExtension(), pchLookupTable(pchLookupTable), lookupTables(tables), swiftCtx(ctx), buffersForDiagnostics(buffersForDiagnostics), availability(avail) {} From e316724243eb85cb43d5a31d9bb0cfd4aeffdd33 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Mon, 7 Jun 2021 11:52:40 -0700 Subject: [PATCH 018/116] Fix reference to in_place_t in_place_t was pulled out of optional_detail and moved up to the llvm namespace. --- include/swift/Syntax/AbsoluteRawSyntax.h | 5 +++-- include/swift/Syntax/SyntaxData.h | 3 +-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/swift/Syntax/AbsoluteRawSyntax.h b/include/swift/Syntax/AbsoluteRawSyntax.h index 21ca9b2abf4f5..ed40f6fbcd985 100644 --- a/include/swift/Syntax/AbsoluteRawSyntax.h +++ b/include/swift/Syntax/AbsoluteRawSyntax.h @@ -16,6 +16,8 @@ #include "swift/Basic/SourceLoc.h" #include "swift/Syntax/RawSyntax.h" +#include "llvm/ADT/STLForwardCompat.h" + namespace swift { namespace syntax { @@ -388,8 +390,7 @@ class OptionalStorage { OptionalStorage(OptionalStorage &&other) = default; template - explicit OptionalStorage(llvm::optional_detail::in_place_t, - ArgTypes &&...Args) + explicit OptionalStorage(llvm::in_place_t, ArgTypes &&...Args) : Storage(std::forward(Args)...) {} void reset() { Storage = AbsoluteRawSyntax(nullptr); } diff --git a/include/swift/Syntax/SyntaxData.h b/include/swift/Syntax/SyntaxData.h index 848ffd42aaad1..02d2d94990fb2 100644 --- a/include/swift/Syntax/SyntaxData.h +++ b/include/swift/Syntax/SyntaxData.h @@ -409,8 +409,7 @@ class OptionalStorage { OptionalStorage(OptionalStorage &&other) = default; template - explicit OptionalStorage(llvm::optional_detail::in_place_t, - ArgTypes &&...Args) + explicit OptionalStorage(llvm::in_place_t, ArgTypes &&...Args) : Storage(std::forward(Args)...) {} void reset() { Storage = SyntaxDataRef(AbsoluteRawSyntax(nullptr), nullptr); } From 96aae72756359a4d378f7fb80b3925b23cbe02a6 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Tue, 22 Jun 2021 10:53:01 -0700 Subject: [PATCH 019/116] Update ModuleName lookup The ModuleName is now put behind a ModuleID struct called "ID" instead of on the ModuleDep directly. --- lib/ClangImporter/ClangModuleDependencyScanner.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/ClangImporter/ClangModuleDependencyScanner.cpp b/lib/ClangImporter/ClangModuleDependencyScanner.cpp index ae520d3116b32..09049a47e18f4 100644 --- a/lib/ClangImporter/ClangModuleDependencyScanner.cpp +++ b/lib/ClangImporter/ClangModuleDependencyScanner.cpp @@ -200,7 +200,7 @@ void ClangImporter::recordModuleDependencies( for (const auto &clangModuleDep : clangDependencies.DiscoveredModules) { // If we've already cached this information, we're done. - if (cache.hasDependencies(clangModuleDep.ModuleName, + if (cache.hasDependencies(clangModuleDep.ID.ModuleName, ModuleDependenciesKind::Clang)) continue; @@ -257,7 +257,7 @@ void ClangImporter::recordModuleDependencies( // Swift frontend action: -emit-pcm swiftArgs.push_back("-emit-pcm"); swiftArgs.push_back("-module-name"); - swiftArgs.push_back(clangModuleDep.ModuleName); + swiftArgs.push_back(clangModuleDep.ID.ModuleName); // Pass down search paths to the -emit-module action. // Unlike building Swift modules, we need to include all search paths to @@ -284,7 +284,7 @@ void ClangImporter::recordModuleDependencies( dependencies.addModuleDependency(moduleName.ModuleName, &alreadyAddedModules); } - cache.recordDependencies(clangModuleDep.ModuleName, + cache.recordDependencies(clangModuleDep.ID.ModuleName, std::move(dependencies)); } } From 450b78f48dc4b97a44442bafe124a21c76267102 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Tue, 22 Jun 2021 10:53:43 -0700 Subject: [PATCH 020/116] NonPathCommandLine -> getAdditionalArgsWithoutModulePaths() This value was replaced with a call to 'getNonPathCommandLine()' in llvm-project commit 2b73565210ef0b3b29e0f067eef150a32adbb967. The API was later renamed 'getAdditionalArgsWithoutModulePaths()' in llvm-project commit 77fc4d1feef5f3041f614206447b4461992054bb. --- lib/ClangImporter/ClangModuleDependencyScanner.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/ClangImporter/ClangModuleDependencyScanner.cpp b/lib/ClangImporter/ClangModuleDependencyScanner.cpp index 09049a47e18f4..2a09c7b9bced5 100644 --- a/lib/ClangImporter/ClangModuleDependencyScanner.cpp +++ b/lib/ClangImporter/ClangModuleDependencyScanner.cpp @@ -247,7 +247,8 @@ void ClangImporter::recordModuleDependencies( // Add all args the non-path arguments required to be passed in, according // to the Clang scanner - for (const auto &clangArg : clangModuleDep.NonPathCommandLine) { + for (const auto &clangArg : + clangModuleDep.getAdditionalArgsWithoutModulePaths()) { swiftArgs.push_back("-Xcc"); swiftArgs.push_back("-Xclang"); swiftArgs.push_back("-Xcc"); From 1cec66e1581986927a572e968d3d438a7b8892a2 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Tue, 22 Jun 2021 11:48:43 -0700 Subject: [PATCH 021/116] Update ContextHash access The ContextHash is also in the ID of the ModuleDep, so access it through there. --- lib/ClangImporter/ClangModuleDependencyScanner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ClangImporter/ClangModuleDependencyScanner.cpp b/lib/ClangImporter/ClangModuleDependencyScanner.cpp index 2a09c7b9bced5..f043486c36f73 100644 --- a/lib/ClangImporter/ClangModuleDependencyScanner.cpp +++ b/lib/ClangImporter/ClangModuleDependencyScanner.cpp @@ -278,7 +278,7 @@ void ClangImporter::recordModuleDependencies( llvm::StringSet<> alreadyAddedModules; auto dependencies = ModuleDependencies::forClangModule( clangModuleDep.ClangModuleMapFile, - clangModuleDep.ContextHash, + clangModuleDep.ID.ContextHash, swiftArgs, fileDeps); for (const auto &moduleName : clangModuleDep.ClangModuleDeps) { From 0aafd0983562d73122c3f5c510ea93d177d5dcbb Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Tue, 22 Jun 2021 16:54:57 -0700 Subject: [PATCH 022/116] F_None was renamed OF_None This patch updates usages of F_None to OF_None, as LLVM changed that in commit 3302af9d4c39642bebe64dd60a3aa162fefc44b2. --- lib/APIDigester/ModuleAnalyzerNodes.cpp | 4 ++-- lib/Basic/FileSystem.cpp | 2 +- lib/DependencyScan/ScanDependencies.cpp | 8 ++++---- lib/Driver/Compilation.cpp | 8 ++++---- lib/Driver/Job.cpp | 2 +- lib/Frontend/DiagnosticVerifier.cpp | 2 +- lib/Frontend/SerializedDiagnosticConsumer.cpp | 2 +- lib/FrontendTool/FrontendTool.cpp | 8 ++++---- lib/FrontendTool/ImportedModules.cpp | 2 +- lib/FrontendTool/MakeStyleDependencies.cpp | 2 +- lib/FrontendTool/TBD.cpp | 2 +- lib/IRGen/IRGen.cpp | 2 +- lib/Localization/LocalizationFormat.cpp | 2 +- lib/SIL/IR/SILPrinter.cpp | 4 ++-- lib/SIL/Utils/SILRemarkStreamer.cpp | 2 +- .../UtilityPasses/SILDebugInfoGenerator.cpp | 2 +- tools/driver/autolink_extract_main.cpp | 2 +- tools/driver/swift_api_digester_main.cpp | 8 ++++---- tools/driver/swift_indent_main.cpp | 2 +- .../SILFunctionExtractor.cpp | 2 +- tools/sil-llvm-gen/SILLLVMGen.cpp | 2 +- tools/sil-opt/SILOpt.cpp | 2 +- .../swift-def-to-yaml-converter.cpp | 2 +- tools/swift-llvm-opt/LLVMOpt.cpp | 2 +- tools/swift-syntax-test/swift-syntax-test.cpp | 6 +++--- unittests/Basic/FileSystemTest.cpp | 18 +++++++++--------- unittests/Localization/LocalizationTest.h | 2 +- 27 files changed, 51 insertions(+), 51 deletions(-) diff --git a/lib/APIDigester/ModuleAnalyzerNodes.cpp b/lib/APIDigester/ModuleAnalyzerNodes.cpp index d991219662bc4..8e19cbd9ddc7d 100644 --- a/lib/APIDigester/ModuleAnalyzerNodes.cpp +++ b/lib/APIDigester/ModuleAnalyzerNodes.cpp @@ -2166,7 +2166,7 @@ void SwiftDeclCollector::deSerialize(StringRef Filename) { // Serialize the content of all roots to a given file using JSON format. void SwiftDeclCollector::serialize(StringRef Filename, SDKNode *Root) { std::error_code EC; - llvm::raw_fd_ostream fs(Filename, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream fs(Filename, EC, llvm::sys::fs::OF_None); json::Output yout(fs); yout << Root; } @@ -2259,7 +2259,7 @@ int swift::ide::api::dumpSDKContent(const CompilerInvocation &InitInvok, int swift::ide::api::deserializeSDKDump(StringRef dumpPath, StringRef OutputPath, CheckerOptions Opts) { std::error_code EC; - llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::OF_None); if (!fs::exists(dumpPath)) { llvm::errs() << dumpPath << " does not exist\n"; return 1; diff --git a/lib/Basic/FileSystem.cpp b/lib/Basic/FileSystem.cpp index 6cafa430832dd..8b6f5ea68e1ab 100644 --- a/lib/Basic/FileSystem.cpp +++ b/lib/Basic/FileSystem.cpp @@ -146,7 +146,7 @@ std::error_code swift::atomicallyWritingToFile( if (!OS.hasValue()) { std::error_code error; - OS.emplace(outputPath, error, fs::F_None); + OS.emplace(outputPath, error, fs::OF_None); if (error) { return error; } diff --git a/lib/DependencyScan/ScanDependencies.cpp b/lib/DependencyScan/ScanDependencies.cpp index 7baa5f813444f..307124b3e6cf8 100644 --- a/lib/DependencyScan/ScanDependencies.cpp +++ b/lib/DependencyScan/ScanDependencies.cpp @@ -1140,7 +1140,7 @@ bool swift::dependencies::scanDependencies(CompilerInstance &instance) { const FrontendOptions &opts = instance.getInvocation().getFrontendOptions(); std::string path = opts.InputsAndOutputs.getSingleOutputFilename(); std::error_code EC; - llvm::raw_fd_ostream out(path, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out(path, EC, llvm::sys::fs::OF_None); if (out.has_error() || EC) { Context.Diags.diagnose(SourceLoc(), diag::error_opening_output, path, EC.message()); @@ -1182,7 +1182,7 @@ bool swift::dependencies::prescanDependencies(CompilerInstance &instance) { const FrontendOptions &opts = instance.getInvocation().getFrontendOptions(); std::string path = opts.InputsAndOutputs.getSingleOutputFilename(); std::error_code EC; - llvm::raw_fd_ostream out(path, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out(path, EC, llvm::sys::fs::OF_None); // `-scan-dependencies` invocations use a single new instance // of a module cache ModuleDependenciesCache cache; @@ -1232,7 +1232,7 @@ bool swift::dependencies::batchScanDependencies( for (; ientries != batchInput->end() and iresults != batchScanResults.end(); ++ientries, ++iresults) { std::error_code EC; - llvm::raw_fd_ostream out((*ientries).outputPath, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out((*ientries).outputPath, EC, llvm::sys::fs::OF_None); if ((*iresults).getError()) return true; @@ -1264,7 +1264,7 @@ bool swift::dependencies::batchPrescanDependencies( ientries != batchInput->end() and iresults != batchPrescanResults.end(); ++ientries, ++iresults) { std::error_code EC; - llvm::raw_fd_ostream out((*ientries).outputPath, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out((*ientries).outputPath, EC, llvm::sys::fs::OF_None); if ((*iresults).getError()) return true; diff --git a/lib/Driver/Compilation.cpp b/lib/Driver/Compilation.cpp index 9bc9709163725..22ecbd790be1d 100644 --- a/lib/Driver/Compilation.cpp +++ b/lib/Driver/Compilation.cpp @@ -1614,7 +1614,7 @@ static void writeCompilationRecord(StringRef path, StringRef argsHash, llvm::sys::fs::rename(path, path + "~"); std::error_code error; - llvm::raw_fd_ostream out(path, error, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out(path, error, llvm::sys::fs::OF_None); if (out.has_error()) { // FIXME: How should we report this error? out.clear_error(); @@ -1718,7 +1718,7 @@ static bool writeFilelistIfNecessary(const Job *job, const ArgList &args, return true; std::error_code error; - llvm::raw_fd_ostream out(filelistInfo.path, error, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out(filelistInfo.path, error, llvm::sys::fs::OF_None); if (out.has_error()) { out.clear_error(); diags.diagnose(SourceLoc(), diag::error_unable_to_make_temporary_file, @@ -1826,7 +1826,7 @@ Compilation::Result Compilation::performSingleCommand(const Job *Cmd) { static bool writeAllSourcesFile(DiagnosticEngine &diags, StringRef path, ArrayRef inputFiles) { std::error_code error; - llvm::raw_fd_ostream out(path, error, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out(path, error, llvm::sys::fs::OF_None); if (out.has_error()) { out.clear_error(); diags.diagnose(SourceLoc(), diag::error_unable_to_make_temporary_file, @@ -1923,7 +1923,7 @@ void Compilation::addDependencyPathOrCreateDummy( } else if (!depPath.empty()) { // Create dummy empty file std::error_code EC; - llvm::raw_fd_ostream(depPath, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream(depPath, EC, llvm::sys::fs::OF_None); } } diff --git a/lib/Driver/Job.cpp b/lib/Driver/Job.cpp index 2d1ca77a723ac..10acf122015eb 100644 --- a/lib/Driver/Job.cpp +++ b/lib/Driver/Job.cpp @@ -464,7 +464,7 @@ void Job::printSummary(raw_ostream &os) const { bool Job::writeArgsToResponseFile() const { assert(hasResponseFile()); std::error_code EC; - llvm::raw_fd_ostream OS(ResponseFile->path, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream OS(ResponseFile->path, EC, llvm::sys::fs::OF_None); if (EC) { return true; } diff --git a/lib/Frontend/DiagnosticVerifier.cpp b/lib/Frontend/DiagnosticVerifier.cpp index 23c5a281ff55c..80a69bc5e5787 100644 --- a/lib/Frontend/DiagnosticVerifier.cpp +++ b/lib/Frontend/DiagnosticVerifier.cpp @@ -209,7 +209,7 @@ static void autoApplyFixes(SourceManager &SM, unsigned BufferID, std::error_code error; llvm::raw_fd_ostream outs(memBuffer->getBufferIdentifier(), error, - llvm::sys::fs::OpenFlags::F_None); + llvm::sys::fs::OpenFlags::OF_None); if (!error) outs << Result; } diff --git a/lib/Frontend/SerializedDiagnosticConsumer.cpp b/lib/Frontend/SerializedDiagnosticConsumer.cpp index f8f1ead32cc59..3e87d1268b6de 100644 --- a/lib/Frontend/SerializedDiagnosticConsumer.cpp +++ b/lib/Frontend/SerializedDiagnosticConsumer.cpp @@ -133,7 +133,7 @@ class SerializedDiagnosticConsumer : public DiagnosticConsumer { std::error_code EC; std::unique_ptr OS; OS.reset(new llvm::raw_fd_ostream(State->SerializedDiagnosticsPath, EC, - llvm::sys::fs::F_None)); + llvm::sys::fs::OF_None)); if (EC) { // Create a temporary diagnostics engine to print the error to stderr. SourceManager dummyMgr; diff --git a/lib/FrontendTool/FrontendTool.cpp b/lib/FrontendTool/FrontendTool.cpp index 1902efcf80a30..92afe65f9596b 100644 --- a/lib/FrontendTool/FrontendTool.cpp +++ b/lib/FrontendTool/FrontendTool.cpp @@ -127,7 +127,7 @@ static std::unique_ptr getFileOutputStream(StringRef OutputFilename, ASTContext &Ctx) { std::error_code errorCode; auto os = std::make_unique( - OutputFilename, errorCode, llvm::sys::fs::F_None); + OutputFilename, errorCode, llvm::sys::fs::OF_None); if (errorCode) { Ctx.Diags.diagnose(SourceLoc(), diag::error_opening_output, OutputFilename, errorCode.message()); @@ -249,7 +249,7 @@ class JSONFixitWriter std::unique_ptr OS; OS.reset(new llvm::raw_fd_ostream(FixitsOutputPath, EC, - llvm::sys::fs::F_None)); + llvm::sys::fs::OF_None)); if (EC) { // Create a temporary diagnostics engine to print the error to stderr. SourceManager dummyMgr; @@ -718,7 +718,7 @@ static bool writeLdAddCFileIfNeeded(CompilerInstance &Instance) { auto ldSymbols = getPublicSymbols(TBDGenDescriptor::forModule(module, tbdOpts)); std::error_code EC; - llvm::raw_fd_ostream OS(Path, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream OS(Path, EC, llvm::sys::fs::OF_None); if (EC) { Instance.getDiags().diagnose(SourceLoc(), diag::error_opening_output, Path, EC.message()); @@ -1062,7 +1062,7 @@ static bool printSwiftFeature(CompilerInstance &instance) { const FrontendOptions &opts = invocation.getFrontendOptions(); std::string path = opts.InputsAndOutputs.getSingleOutputFilename(); std::error_code EC; - llvm::raw_fd_ostream out(path, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out(path, EC, llvm::sys::fs::OF_None); if (out.has_error() || EC) { context.Diags.diagnose(SourceLoc(), diag::error_opening_output, path, diff --git a/lib/FrontendTool/ImportedModules.cpp b/lib/FrontendTool/ImportedModules.cpp index 9316af5a09dc1..f73dfc64d25cf 100644 --- a/lib/FrontendTool/ImportedModules.cpp +++ b/lib/FrontendTool/ImportedModules.cpp @@ -47,7 +47,7 @@ bool swift::emitImportedModules(ModuleDecl *mainModule, auto &Context = mainModule->getASTContext(); std::string path = opts.InputsAndOutputs.getSingleOutputFilename(); std::error_code EC; - llvm::raw_fd_ostream out(path, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out(path, EC, llvm::sys::fs::OF_None); if (out.has_error() || EC) { Context.Diags.diagnose(SourceLoc(), diag::error_opening_output, path, diff --git a/lib/FrontendTool/MakeStyleDependencies.cpp b/lib/FrontendTool/MakeStyleDependencies.cpp index 9e2fa946926bf..02368ea8d5e19 100644 --- a/lib/FrontendTool/MakeStyleDependencies.cpp +++ b/lib/FrontendTool/MakeStyleDependencies.cpp @@ -97,7 +97,7 @@ bool swift::emitMakeDependenciesIfNeeded(DiagnosticEngine &diags, return false; std::error_code EC; - llvm::raw_fd_ostream out(dependenciesFilePath, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out(dependenciesFilePath, EC, llvm::sys::fs::OF_None); if (out.has_error() || EC) { diags.diagnose(SourceLoc(), diag::error_opening_output, diff --git a/lib/FrontendTool/TBD.cpp b/lib/FrontendTool/TBD.cpp index 7f92dfb938e77..493f8203348af 100644 --- a/lib/FrontendTool/TBD.cpp +++ b/lib/FrontendTool/TBD.cpp @@ -44,7 +44,7 @@ static std::vector sortSymbols(llvm::StringSet<> &symbols) { bool swift::writeTBD(ModuleDecl *M, StringRef OutputFilename, const TBDGenOptions &Opts) { std::error_code EC; - llvm::raw_fd_ostream OS(OutputFilename, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream OS(OutputFilename, EC, llvm::sys::fs::OF_None); if (EC) { M->getASTContext().Diags.diagnose(SourceLoc(), diag::error_opening_output, OutputFilename, EC.message()); diff --git a/lib/IRGen/IRGen.cpp b/lib/IRGen/IRGen.cpp index 26ee4aefe55ef..09dd430bcfa1d 100644 --- a/lib/IRGen/IRGen.cpp +++ b/lib/IRGen/IRGen.cpp @@ -526,7 +526,7 @@ bool swift::performLLVM(const IRGenOptions &Opts, if (!OutputFilename.empty()) { // Try to open the output file. Clobbering an existing file is fine. // Open in binary mode if we're doing binary output. - llvm::sys::fs::OpenFlags OSFlags = llvm::sys::fs::F_None; + llvm::sys::fs::OpenFlags OSFlags = llvm::sys::fs::OF_None; std::error_code EC; RawOS.emplace(OutputFilename, EC, OSFlags); diff --git a/lib/Localization/LocalizationFormat.cpp b/lib/Localization/LocalizationFormat.cpp index ee830337a35e1..249b094d248d9 100644 --- a/lib/Localization/LocalizationFormat.cpp +++ b/lib/Localization/LocalizationFormat.cpp @@ -76,7 +76,7 @@ void SerializedLocalizationWriter::insert(swift::DiagID id, bool SerializedLocalizationWriter::emit(llvm::StringRef filePath) { assert(llvm::sys::path::extension(filePath) == ".db"); std::error_code error; - llvm::raw_fd_ostream OS(filePath, error, llvm::sys::fs::F_None); + llvm::raw_fd_ostream OS(filePath, error, llvm::sys::fs::OF_None); if (OS.has_error()) { return true; } diff --git a/lib/SIL/IR/SILPrinter.cpp b/lib/SIL/IR/SILPrinter.cpp index 61d1d857a56e7..c491265a869d4 100644 --- a/lib/SIL/IR/SILPrinter.cpp +++ b/lib/SIL/IR/SILPrinter.cpp @@ -2620,7 +2620,7 @@ void SILFunction::dump() const { void SILFunction::dump(const char *FileName) const { std::error_code EC; - llvm::raw_fd_ostream os(FileName, EC, llvm::sys::fs::OpenFlags::F_None); + llvm::raw_fd_ostream os(FileName, EC, llvm::sys::fs::OpenFlags::OF_None); print(os); } @@ -2869,7 +2869,7 @@ void SILModule::dump(bool Verbose) const { void SILModule::dump(const char *FileName, bool Verbose, bool PrintASTDecls) const { std::error_code EC; - llvm::raw_fd_ostream os(FileName, EC, llvm::sys::fs::OpenFlags::F_None); + llvm::raw_fd_ostream os(FileName, EC, llvm::sys::fs::OpenFlags::OF_None); SILPrintContext Ctx(os, Verbose); print(Ctx, getSwiftModule(), PrintASTDecls); } diff --git a/lib/SIL/Utils/SILRemarkStreamer.cpp b/lib/SIL/Utils/SILRemarkStreamer.cpp index 68317a23ba4a5..156562c665df5 100644 --- a/lib/SIL/Utils/SILRemarkStreamer.cpp +++ b/lib/SIL/Utils/SILRemarkStreamer.cpp @@ -60,7 +60,7 @@ SILRemarkStreamer::create(SILModule &silModule) { auto &diagEngine = silModule.getASTContext().Diags; std::error_code errorCode; auto file = std::make_unique(filename, errorCode, - llvm::sys::fs::F_None); + llvm::sys::fs::OF_None); if (errorCode) { diagEngine.diagnose(SourceLoc(), diag::cannot_open_file, filename, errorCode.message()); diff --git a/lib/SILOptimizer/UtilityPasses/SILDebugInfoGenerator.cpp b/lib/SILOptimizer/UtilityPasses/SILDebugInfoGenerator.cpp index 37b8e19c73c7e..0912a60f8dcfa 100644 --- a/lib/SILOptimizer/UtilityPasses/SILDebugInfoGenerator.cpp +++ b/lib/SILOptimizer/UtilityPasses/SILDebugInfoGenerator.cpp @@ -114,7 +114,7 @@ class SILDebugInfoGenerator : public SILModuleTransform { std::error_code EC; llvm::raw_fd_ostream OutFile(FileName, EC, - llvm::sys::fs::OpenFlags::F_None); + llvm::sys::fs::OpenFlags::OF_None); assert(!OutFile.has_error() && !EC && "Can't write SIL debug file"); PrintContext Ctx(OutFile); diff --git a/tools/driver/autolink_extract_main.cpp b/tools/driver/autolink_extract_main.cpp index 76825313eb3f1..64c0252c8ef04 100644 --- a/tools/driver/autolink_extract_main.cpp +++ b/tools/driver/autolink_extract_main.cpp @@ -223,7 +223,7 @@ int autolink_extract_main(ArrayRef Args, const char *Argv0, std::string OutputFilename = Invocation.getOutputFilename(); std::error_code EC; - llvm::raw_fd_ostream OutOS(OutputFilename, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream OutOS(OutputFilename, EC, llvm::sys::fs::OF_None); if (OutOS.has_error() || EC) { Instance.getDiags().diagnose(SourceLoc(), diag::error_opening_output, OutputFilename, EC.message()); diff --git a/tools/driver/swift_api_digester_main.cpp b/tools/driver/swift_api_digester_main.cpp index 7a337d8f2a5b6..db049c399be04 100644 --- a/tools/driver/swift_api_digester_main.cpp +++ b/tools/driver/swift_api_digester_main.cpp @@ -2183,7 +2183,7 @@ static int diagnoseModuleChange(SDKContext &Ctx, SDKNodeRoot *LeftModule, std::unique_ptr FileOS; if (!OutputPath.empty()) { std::error_code EC; - FileOS.reset(new llvm::raw_fd_ostream(OutputPath, EC, llvm::sys::fs::F_None)); + FileOS.reset(new llvm::raw_fd_ostream(OutputPath, EC, llvm::sys::fs::OF_None)); OS = FileOS.get(); } bool FailOnError; @@ -2328,7 +2328,7 @@ static int generateMigrationScript(StringRef LeftPath, StringRef RightPath, auto &typeMemberDiffs = Ctx.getTypeMemberDiffs(); std::error_code EC; - llvm::raw_fd_ostream Fs(DiffPath, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream Fs(DiffPath, EC, llvm::sys::fs::OF_None); removeRedundantAndSort(AllItems); removeRedundantAndSort(typeMemberDiffs); removeRedundantAndSort(AllNoEscapingFuncs); @@ -2374,7 +2374,7 @@ static int deserializeDiffItems(APIDiffItemStore &Store, StringRef DiffPath, StringRef OutputPath) { Store.addStorePath(DiffPath); std::error_code EC; - llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::OF_None); APIDiffItemStore::serialize(FS, Store.getAllDiffItems()); return 0; } @@ -2382,7 +2382,7 @@ static int deserializeDiffItems(APIDiffItemStore &Store, StringRef DiffPath, static int deserializeNameCorrection(APIDiffItemStore &Store, StringRef OutputPath) { std::error_code EC; - llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::OF_None); std::set Result; for (auto *Item: Store.getAllDiffItems()) { if (auto *CI = dyn_cast(Item)) { diff --git a/tools/driver/swift_indent_main.cpp b/tools/driver/swift_indent_main.cpp index d5280177a0ab7..ff2d8d1ae00a8 100644 --- a/tools/driver/swift_indent_main.cpp +++ b/tools/driver/swift_indent_main.cpp @@ -220,7 +220,7 @@ class SwiftIndentInvocation { Destination = Filename; else Destination = OutputFilename; - llvm::raw_fd_ostream out(Destination, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream out(Destination, EC, llvm::sys::fs::OF_None); if (out.has_error() || EC) { Diags.diagnose(SourceLoc(), diag::error_opening_output, Filename, EC.message()); diff --git a/tools/sil-func-extractor/SILFunctionExtractor.cpp b/tools/sil-func-extractor/SILFunctionExtractor.cpp index be96d55123a3a..0647c93cc25c6 100644 --- a/tools/sil-func-extractor/SILFunctionExtractor.cpp +++ b/tools/sil-func-extractor/SILFunctionExtractor.cpp @@ -356,7 +356,7 @@ int main(int argc, char **argv) { SILMod->print(llvm::outs(), CI.getMainModule(), SILOpts, !DisableASTDump); } else { std::error_code EC; - llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::OF_None); if (EC) { llvm::errs() << "while opening '" << OutputFile << "': " << EC.message() << '\n'; diff --git a/tools/sil-llvm-gen/SILLLVMGen.cpp b/tools/sil-llvm-gen/SILLLVMGen.cpp index 38c0da3791a0d..92610da9c78a1 100644 --- a/tools/sil-llvm-gen/SILLLVMGen.cpp +++ b/tools/sil-llvm-gen/SILLLVMGen.cpp @@ -179,7 +179,7 @@ int main(int argc, char **argv) { return 1; std::error_code EC; - llvm::raw_fd_ostream outStream(OutputFilename, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream outStream(OutputFilename, EC, llvm::sys::fs::OF_None); if (outStream.has_error() || EC) { CI.getDiags().diagnose(SourceLoc(), diag::error_opening_output, OutputFilename, EC.message()); diff --git a/tools/sil-opt/SILOpt.cpp b/tools/sil-opt/SILOpt.cpp index 8e493d49cdeb2..74d05793ea4c7 100644 --- a/tools/sil-opt/SILOpt.cpp +++ b/tools/sil-opt/SILOpt.cpp @@ -601,7 +601,7 @@ int main(int argc, char **argv) { SILMod->print(llvm::outs(), CI.getMainModule(), SILOpts, !DisableASTDump); } else { std::error_code EC; - llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_None); + llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::OF_None); if (EC) { llvm::errs() << "while opening '" << OutputFile << "': " << EC.message() << '\n'; diff --git a/tools/swift-def-to-yaml-converter/swift-def-to-yaml-converter.cpp b/tools/swift-def-to-yaml-converter/swift-def-to-yaml-converter.cpp index 95ba4b5570682..34018341aafee 100644 --- a/tools/swift-def-to-yaml-converter/swift-def-to-yaml-converter.cpp +++ b/tools/swift-def-to-yaml-converter/swift-def-to-yaml-converter.cpp @@ -83,7 +83,7 @@ int main(int argc, char *argv[]) { std::error_code error; llvm::raw_fd_ostream OS(LocalizedFilePath.str(), error, - llvm::sys::fs::F_None); + llvm::sys::fs::OF_None); if (OS.has_error() || error) { llvm::errs() << "Error has occurred while trying to write to " diff --git a/tools/swift-llvm-opt/LLVMOpt.cpp b/tools/swift-llvm-opt/LLVMOpt.cpp index 251a0d8ca833a..8f1f112e67c32 100644 --- a/tools/swift-llvm-opt/LLVMOpt.cpp +++ b/tools/swift-llvm-opt/LLVMOpt.cpp @@ -283,7 +283,7 @@ int main(int argc, char **argv) { std::error_code EC; Out.reset( - new llvm::ToolOutputFile(OutputFilename, EC, llvm::sys::fs::F_None)); + new llvm::ToolOutputFile(OutputFilename, EC, llvm::sys::fs::OF_None)); if (EC) { llvm::errs() << EC.message() << '\n'; return 1; diff --git a/tools/swift-syntax-test/swift-syntax-test.cpp b/tools/swift-syntax-test/swift-syntax-test.cpp index d0fec196b1f34..d5055373d26d9 100644 --- a/tools/swift-syntax-test/swift-syntax-test.cpp +++ b/tools/swift-syntax-test/swift-syntax-test.cpp @@ -724,7 +724,7 @@ int doSerializeRawTree(const char *MainExecutablePath, if (!options::OutputFilename.empty()) { std::error_code errorCode; llvm::raw_fd_ostream os(options::OutputFilename, errorCode, - llvm::sys::fs::F_None); + llvm::sys::fs::OF_None); assert(!errorCode && "Couldn't open output file"); swift::json::Output out(os); out << *Root; @@ -738,7 +738,7 @@ int doSerializeRawTree(const char *MainExecutablePath, if (!options::DiagsOutputFilename.empty()) { std::error_code errorCode; llvm::raw_fd_ostream os(options::DiagsOutputFilename, errorCode, - llvm::sys::fs::F_None); + llvm::sys::fs::OF_None); if (errorCode) { llvm::errs() << "error opening file '" << options::DiagsOutputFilename << "': " << errorCode.message() << '\n'; @@ -762,7 +762,7 @@ int doDeserializeRawTree(const char *MainExecutablePath, auto Buffer = llvm::MemoryBuffer::getFile(InputFile); std::error_code errorCode; auto os = std::make_unique( - OutputFileName, errorCode, llvm::sys::fs::F_None); + OutputFileName, errorCode, llvm::sys::fs::OF_None); swift::json::SyntaxDeserializer deserializer(llvm::MemoryBufferRef(*(Buffer.get()))); deserializer.getSourceFileSyntax()->print(*os); diff --git a/unittests/Basic/FileSystemTest.cpp b/unittests/Basic/FileSystemTest.cpp index f7ac9115c31ae..82c1667bd8047 100644 --- a/unittests/Basic/FileSystemTest.cpp +++ b/unittests/Basic/FileSystemTest.cpp @@ -39,7 +39,7 @@ TEST(FileSystem, MoveFileIfDifferentEmpty) { path::append(sourceFile, "source.txt"); { std::error_code error; - llvm::raw_fd_ostream emptyOut(sourceFile, error, fs::F_None); + llvm::raw_fd_ostream emptyOut(sourceFile, error, fs::OF_None); ASSERT_NO_ERROR(error); } @@ -63,7 +63,7 @@ TEST(FileSystem, MoveFileIfDifferentEmpty) { // Test 2: Move empty over empty. { std::error_code error; - llvm::raw_fd_ostream emptyOut(destFile, error, fs::F_None); + llvm::raw_fd_ostream emptyOut(destFile, error, fs::OF_None); ASSERT_NO_ERROR(error); } @@ -84,7 +84,7 @@ TEST(FileSystem, MoveFileIfDifferentEmpty) { // Test 3: Move empty over non-empty. { std::error_code error; - llvm::raw_fd_ostream nonEmptyOut(destFile, error, fs::F_None); + llvm::raw_fd_ostream nonEmptyOut(destFile, error, fs::OF_None); ASSERT_NO_ERROR(error); nonEmptyOut << "a"; } @@ -123,7 +123,7 @@ TEST(FileSystem, MoveFileIfDifferentNonEmpty) { path::append(sourceFile, "source.txt"); { std::error_code error; - llvm::raw_fd_ostream sourceOut(sourceFile, error, fs::F_None); + llvm::raw_fd_ostream sourceOut(sourceFile, error, fs::OF_None); sourceOut << "original"; ASSERT_NO_ERROR(error); } @@ -148,7 +148,7 @@ TEST(FileSystem, MoveFileIfDifferentNonEmpty) { // Test 2: Move source over empty. { std::error_code error; - llvm::raw_fd_ostream emptyOut(destFile, error, fs::F_None); + llvm::raw_fd_ostream emptyOut(destFile, error, fs::OF_None); ASSERT_NO_ERROR(error); } @@ -168,7 +168,7 @@ TEST(FileSystem, MoveFileIfDifferentNonEmpty) { // Test 3: Move source over non-empty-but-different. { std::error_code error; - llvm::raw_fd_ostream nonEmptyOut(destFile, error, fs::F_None); + llvm::raw_fd_ostream nonEmptyOut(destFile, error, fs::OF_None); ASSERT_NO_ERROR(error); nonEmptyOut << "different"; } @@ -188,7 +188,7 @@ TEST(FileSystem, MoveFileIfDifferentNonEmpty) { // Test 4: Move source over identical. { std::error_code error; - llvm::raw_fd_ostream nonEmptyOut(destFile, error, fs::F_None); + llvm::raw_fd_ostream nonEmptyOut(destFile, error, fs::OF_None); ASSERT_NO_ERROR(error); nonEmptyOut << "original"; } @@ -233,7 +233,7 @@ TEST(FileSystem, MoveFileIfDifferentNonExistent) { { std::error_code error; - llvm::raw_fd_ostream emptyOut(destFile, error, fs::F_None); + llvm::raw_fd_ostream emptyOut(destFile, error, fs::OF_None); ASSERT_NO_ERROR(error); } @@ -254,7 +254,7 @@ TEST(FileSystem, MoveFileIfDifferentInvalid) { path::append(sourceFile, "source.txt"); { std::error_code error; - llvm::raw_fd_ostream emptyOut(sourceFile, error, fs::F_None); + llvm::raw_fd_ostream emptyOut(sourceFile, error, fs::OF_None); ASSERT_NO_ERROR(error); } diff --git a/unittests/Localization/LocalizationTest.h b/unittests/Localization/LocalizationTest.h index 714403070d6ee..6b78628c59a21 100644 --- a/unittests/Localization/LocalizationTest.h +++ b/unittests/Localization/LocalizationTest.h @@ -87,7 +87,7 @@ struct LocalizationTest : public ::testing::Test { protected: static bool convertDefIntoYAML(std::string outputPath) { std::error_code error; - llvm::raw_fd_ostream OS(outputPath, error, llvm::sys::fs::F_None); + llvm::raw_fd_ostream OS(outputPath, error, llvm::sys::fs::OF_None); if (OS.has_error() || error) return true; From 8112cda531d7aea68e8ecbfebda1cb13a8f419f5 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 23 Jun 2021 14:29:52 -0700 Subject: [PATCH 023/116] Updated F_Text and F_Append These enum cases were also updated to OF_Text and OF_Append. --- lib/Basic/Statistic.cpp | 6 +++--- lib/FrontendTool/LoadedModuleTrace.cpp | 2 +- lib/Migrator/MigrationState.cpp | 2 +- lib/Migrator/Migrator.cpp | 4 ++-- lib/SILOptimizer/Analysis/CallerAnalysis.cpp | 2 +- lib/SILOptimizer/Utils/OptimizerStatsUtils.cpp | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/Basic/Statistic.cpp b/lib/Basic/Statistic.cpp index b44fb5ec9d3d2..08451423165eb 100644 --- a/lib/Basic/Statistic.cpp +++ b/lib/Basic/Statistic.cpp @@ -251,7 +251,7 @@ class StatsProfiler { SmallString<256> Path(Dirname); llvm::sys::path::append(Path, Filename); std::error_code EC; - raw_fd_ostream Stream(Path, EC, fs::F_Append | fs::F_Text); + raw_fd_ostream Stream(Path, EC, fs::OF_Append | fs::OF_Text); if (EC) { llvm::errs() << "Error opening profile file '" << Path << "' for writing\n"; @@ -688,7 +688,7 @@ UnifiedStatsReporter::~UnifiedStatsReporter() } std::error_code EC; - raw_fd_ostream ostream(StatsFilename, EC, fs::F_Append | fs::F_Text); + raw_fd_ostream ostream(StatsFilename, EC, fs::OF_Append | fs::OF_Text); if (EC) { llvm::errs() << "Error opening -stats-output-dir file '" << StatsFilename << "' for writing\n"; @@ -726,7 +726,7 @@ UnifiedStatsReporter::flushTracesAndProfiles() { if (FrontendStatsEvents && SourceMgr) { std::error_code EC; - raw_fd_ostream tstream(TraceFilename, EC, fs::F_Append | fs::F_Text); + raw_fd_ostream tstream(TraceFilename, EC, fs::OF_Append | fs::OF_Text); if (EC) { llvm::errs() << "Error opening -trace-stats-events file '" << TraceFilename << "' for writing\n"; diff --git a/lib/FrontendTool/LoadedModuleTrace.cpp b/lib/FrontendTool/LoadedModuleTrace.cpp index 7ec8fd1bd6665..99cce3da1760a 100644 --- a/lib/FrontendTool/LoadedModuleTrace.cpp +++ b/lib/FrontendTool/LoadedModuleTrace.cpp @@ -707,7 +707,7 @@ bool swift::emitLoadedModuleTraceIfNeeded(ModuleDecl *mainModule, if (loadedModuleTracePath.empty()) return false; std::error_code EC; - llvm::raw_fd_ostream out(loadedModuleTracePath, EC, llvm::sys::fs::F_Append); + llvm::raw_fd_ostream out(loadedModuleTracePath, EC, llvm::sys::fs::OF_Append); if (out.has_error() || EC) { ctxt.Diags.diagnose(SourceLoc(), diag::error_opening_output, diff --git a/lib/Migrator/MigrationState.cpp b/lib/Migrator/MigrationState.cpp index 5493a29f4742f..8128e61646b08 100644 --- a/lib/Migrator/MigrationState.cpp +++ b/lib/Migrator/MigrationState.cpp @@ -35,7 +35,7 @@ std::string MigrationState::getOutputText() const { static bool quickDumpText(StringRef OutFilename, StringRef Text) { std::error_code Error; llvm::raw_fd_ostream FileOS(OutFilename, - Error, llvm::sys::fs::F_Text); + Error, llvm::sys::fs::OF_Text); if (FileOS.has_error()) { return true; } diff --git a/lib/Migrator/Migrator.cpp b/lib/Migrator/Migrator.cpp index baf7ae64c2870..b183c74c6aa9c 100644 --- a/lib/Migrator/Migrator.cpp +++ b/lib/Migrator/Migrator.cpp @@ -385,7 +385,7 @@ bool Migrator::emitRemap() const { std::error_code Error; llvm::raw_fd_ostream FileOS(RemapPath, - Error, llvm::sys::fs::F_Text); + Error, llvm::sys::fs::OF_Text); if (FileOS.has_error()) { return true; } @@ -406,7 +406,7 @@ bool Migrator::emitMigratedFile() const { std::error_code Error; llvm::raw_fd_ostream FileOS(OutFilename, - Error, llvm::sys::fs::F_Text); + Error, llvm::sys::fs::OF_Text); if (FileOS.has_error()) { return true; } diff --git a/lib/SILOptimizer/Analysis/CallerAnalysis.cpp b/lib/SILOptimizer/Analysis/CallerAnalysis.cpp index f27316bd95e9f..738d08ab79226 100644 --- a/lib/SILOptimizer/Analysis/CallerAnalysis.cpp +++ b/lib/SILOptimizer/Analysis/CallerAnalysis.cpp @@ -447,7 +447,7 @@ void CallerAnalysis::dump() const { print(llvm::errs()); } void CallerAnalysis::print(const char *filePath) const { using namespace llvm::sys; std::error_code error; - llvm::raw_fd_ostream fileOutputStream(filePath, error, fs::F_Text); + llvm::raw_fd_ostream fileOutputStream(filePath, error, fs::OF_Text); if (error) { llvm::errs() << "Failed to open path \"" << filePath << "\" for writing.!"; llvm_unreachable("default error handler"); diff --git a/lib/SILOptimizer/Utils/OptimizerStatsUtils.cpp b/lib/SILOptimizer/Utils/OptimizerStatsUtils.cpp index 4e6d8a114eae2..95a78ba10bbe2 100644 --- a/lib/SILOptimizer/Utils/OptimizerStatsUtils.cpp +++ b/lib/SILOptimizer/Utils/OptimizerStatsUtils.cpp @@ -558,7 +558,7 @@ llvm::raw_ostream &stats_os() { // Try to open the file. std::error_code EC; auto fd_stream = std::make_unique( - SILStatsOutputFile, EC, llvm::sys::fs::OpenFlags::F_Text); + SILStatsOutputFile, EC, llvm::sys::fs::OpenFlags::OF_Text); if (!fd_stream->has_error() && !EC) { stats_output_stream = {fd_stream.release(), [](llvm::raw_ostream *d) { delete d; }}; From d9c1034c6d0bc6dc55c8ae6da70f92cf5c9c45db Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 23 Jun 2021 15:38:12 -0700 Subject: [PATCH 024/116] Add missing ArrayRef import The ArrayRef definition used to be included transitively through PointerUnion.h -> DenseMapInfo.h -> ArrayRef.h. DenseMapInfo.h was cleaned up, removing the include of ArrayRef.h. We rely on the full type definition, so including it explicitly. --- include/swift/AST/Identifier.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/swift/AST/Identifier.h b/include/swift/AST/Identifier.h index 5d93f225c2d96..f3999438ed0a5 100644 --- a/include/swift/AST/Identifier.h +++ b/include/swift/AST/Identifier.h @@ -20,6 +20,7 @@ #include "swift/Basic/EditorPlaceholder.h" #include "swift/Basic/Debug.h" #include "swift/Basic/LLVM.h" +#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/Support/TrailingObjects.h" From 40eb1cf6f6114c5a3d3a83848d4d75175db6edc7 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 23 Jun 2021 16:25:31 -0700 Subject: [PATCH 025/116] Adding missing array import The `std::array` definition used to be included transitively through VersionTuple.h -> DenseMapInfo.h -> ArrayRef.h -> array. DenseMapInfo.h was cleaned up, removing the include of ArrayRef.h. We initialize a template Instantiation of the array, so we need the definition. --- include/swift/Basic/Version.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/swift/Basic/Version.h b/include/swift/Basic/Version.h index b93ea6cc0137a..f779f7376c846 100644 --- a/include/swift/Basic/Version.h +++ b/include/swift/Basic/Version.h @@ -25,6 +25,7 @@ #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/VersionTuple.h" +#include #include namespace swift { From 27efdd0f2641b4d648835595917c4737de17aa20 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Thu, 24 Jun 2021 14:45:03 -0700 Subject: [PATCH 026/116] Add missing optional include Optional.h was getting included through PointerUnion.h -> DenseMapInfo.h -> ArrayRef.h -> Optional.h. DenseMapInfo.h doesn't include ArrayRef anymore, so we weren't including llvm optional in the ASTWalker anymore. --- include/swift/AST/ASTWalker.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/swift/AST/ASTWalker.h b/include/swift/AST/ASTWalker.h index 74b5850741920..da88382da3b4d 100644 --- a/include/swift/AST/ASTWalker.h +++ b/include/swift/AST/ASTWalker.h @@ -13,6 +13,7 @@ #ifndef SWIFT_AST_ASTWALKER_H #define SWIFT_AST_ASTWALKER_H +#include "llvm/ADT/Optional.h" #include "llvm/ADT/PointerUnion.h" #include From 63ba6186040c7487253650cdd47be85a80e59c74 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Thu, 24 Jun 2021 15:36:28 -0700 Subject: [PATCH 027/116] Add missing StringRef include --- include/swift/SIL/Notifications.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/swift/SIL/Notifications.h b/include/swift/SIL/Notifications.h index f7ecd87024c70..d3682cb0d5a17 100644 --- a/include/swift/SIL/Notifications.h +++ b/include/swift/SIL/Notifications.h @@ -17,6 +17,7 @@ #include "swift/Basic/STLExtras.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" #include namespace swift { From 102b0c7be1163308428503b8092668f0c4400d87 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Thu, 24 Jun 2021 15:48:41 -0700 Subject: [PATCH 028/116] Add Optional.h to BlotSetVector It was getting included transitively before, but it isn't anymore due to refactorings in llvm. --- include/swift/Basic/BlotSetVector.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/swift/Basic/BlotSetVector.h b/include/swift/Basic/BlotSetVector.h index bf57c311c7929..fd72af4cffaa3 100644 --- a/include/swift/Basic/BlotSetVector.h +++ b/include/swift/Basic/BlotSetVector.h @@ -15,6 +15,7 @@ #include "swift/Basic/LLVM.h" #include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include From 99237f6a65008e44d2213520beecacdbeed135f1 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Thu, 24 Jun 2021 17:02:05 -0700 Subject: [PATCH 029/116] Fixed call to APInt::toString in SerializeSIL The toString has been updated so that it doesn't return a std::string anymore. Instead, you have to pass the memory buffer in. This patch cleans that up. --- lib/Serialization/SerializeSIL.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/Serialization/SerializeSIL.cpp b/lib/Serialization/SerializeSIL.cpp index caf1ea7ee3b34..6dead8892408d 100644 --- a/lib/Serialization/SerializeSIL.cpp +++ b/lib/Serialization/SerializeSIL.cpp @@ -1555,26 +1555,26 @@ void SILSerializer::writeSILInstruction(const SILInstruction &SI) { case SILInstructionKind::FloatLiteralInst: case SILInstructionKind::IntegerLiteralInst: { // Use SILOneOperandLayout to specify the type and the literal. - std::string Str; + llvm::SmallString Str; SILType Ty; switch (SI.getKind()) { default: llvm_unreachable("Out of sync with parent switch"); case SILInstructionKind::IntegerLiteralInst: - Str = cast(&SI)->getValue().toString(10, true); + cast(&SI)->getValue().toString(Str, 10, + /*signed*/ true); Ty = cast(&SI)->getType(); break; case SILInstructionKind::FloatLiteralInst: - Str = cast(&SI)->getBits().toString(16, - /*Signed*/false); + cast(&SI)->getValue().toString(Str, 16, + /*signed*/ true); Ty = cast(&SI)->getType(); break; } unsigned abbrCode = SILAbbrCodes[SILOneOperandLayout::Code]; - SILOneOperandLayout::emitRecord(Out, ScratchRecord, abbrCode, - (unsigned)SI.getKind(), 0, - S.addTypeRef(Ty.getASTType()), - (unsigned)Ty.getCategory(), - S.addUniquedStringRef(Str)); + SILOneOperandLayout::emitRecord( + Out, ScratchRecord, abbrCode, (unsigned)SI.getKind(), 0, + S.addTypeRef(Ty.getASTType()), (unsigned)Ty.getCategory(), + S.addUniquedStringRef(Str.str())); break; } case SILInstructionKind::MarkFunctionEscapeInst: { From 9bd93db2beafe8181557a5b9ec32f2cc812bcbbd Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Fri, 25 Jun 2021 10:21:02 -0700 Subject: [PATCH 030/116] Update all the APInt toStrings Just went through and updated the rest of the APInt toString calls. This should take care of them, I hope. --- lib/Driver/Driver.cpp | 2 +- lib/Frontend/Frontend.cpp | 5 +-- lib/Frontend/ModuleInterfaceLoader.cpp | 3 +- lib/IRGen/GenIntegerLiteral.cpp | 15 +++++---- lib/SIL/IR/SILPrinter.cpp | 8 ++--- lib/SILOptimizer/Utils/ConstantFolding.cpp | 39 +++++++++++----------- lib/Serialization/SerializeSIL.cpp | 2 +- 7 files changed, 38 insertions(+), 36 deletions(-) diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp index c06cf49827727..602b8f32c9a59 100644 --- a/lib/Driver/Driver.cpp +++ b/lib/Driver/Driver.cpp @@ -2760,7 +2760,7 @@ static void addDiagFileOutputForPersistentPCHAction( llvm::sys::path::append(outPathBuf, stem); outPathBuf += '-'; auto code = llvm::hash_value(ModuleOutPath); - outPathBuf += llvm::APInt(64, code).toString(36, /*Signed=*/false); + llvm::APInt(64, code).toString(outPathBuf, 36, /*Signed=*/false); llvm::sys::path::replace_extension(outPathBuf, suffix); } diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp index ab28bb381277a..6530cdef7edbb 100644 --- a/lib/Frontend/Frontend.cpp +++ b/lib/Frontend/Frontend.cpp @@ -30,9 +30,9 @@ #include "swift/SIL/SILModule.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SILOptimizer/Utils/Generics.h" +#include "swift/Serialization/ModuleDependencyScanner.h" #include "swift/Serialization/SerializationOptions.h" #include "swift/Serialization/SerializedModuleLoader.h" -#include "swift/Serialization/ModuleDependencyScanner.h" #include "swift/Strings.h" #include "swift/Subsystems.h" #include "clang/AST/ASTContext.h" @@ -44,6 +44,7 @@ #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" +#include using namespace swift; @@ -61,7 +62,7 @@ std::string CompilerInvocation::getPCHHash() const { SILOpts.getPCHHashComponents(), IRGenOpts.getPCHHashComponents()); - return llvm::APInt(64, Code).toString(36, /*Signed=*/false); + return llvm::toString(llvm::APInt(64, Code), 36, /*Signed=*/false); } const PrimarySpecificPaths & diff --git a/lib/Frontend/ModuleInterfaceLoader.cpp b/lib/Frontend/ModuleInterfaceLoader.cpp index d4d424570380a..c99ae97131ae7 100644 --- a/lib/Frontend/ModuleInterfaceLoader.cpp +++ b/lib/Frontend/ModuleInterfaceLoader.cpp @@ -33,6 +33,7 @@ #include "llvm/ADT/APInt.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringExtras.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Errc.h" @@ -1554,7 +1555,7 @@ InterfaceSubContextDelegateImpl::getCacheHash(StringRef useInterfacePath) { // ensure that we compile all swift interface files with the option set. unsigned(genericSubInvocation.getSILOptions().EnableOSSAModules)); - return llvm::APInt(64, H).toString(36, /*Signed=*/false); + return llvm::toString(llvm::APInt(64, H), 36, /*Signed=*/false); } std::error_code diff --git a/lib/IRGen/GenIntegerLiteral.cpp b/lib/IRGen/GenIntegerLiteral.cpp index 3183513d453e9..c36bb0a5ee299 100644 --- a/lib/IRGen/GenIntegerLiteral.cpp +++ b/lib/IRGen/GenIntegerLiteral.cpp @@ -16,9 +16,10 @@ #include "GenIntegerLiteral.h" +#include "swift/ABI/MetadataValues.h" +#include "llvm/ADT/StringExtras.h" #include "llvm/IR/Constants.h" #include "llvm/IR/GlobalVariable.h" -#include "swift/ABI/MetadataValues.h" #include "BitPatternBuilder.h" #include "Explosion.h" @@ -177,12 +178,12 @@ ConstantIntegerLiteralMap::get(IRGenModule &IGM, APInt &&value) { // TODO: make this shared within the image auto arrayTy = llvm::ArrayType::get(IGM.SizeTy, numChunks); auto initV = llvm::ConstantArray::get(arrayTy, chunks); - auto globalArray = - new llvm::GlobalVariable(*IGM.getModule(), arrayTy, /*constant*/ true, - llvm::GlobalVariable::PrivateLinkage, initV, - IGM.EnableValueNames - ? Twine("intliteral.") + value.toString(10, true) - : ""); + auto globalArray = new llvm::GlobalVariable( + *IGM.getModule(), arrayTy, /*constant*/ true, + llvm::GlobalVariable::PrivateLinkage, initV, + IGM.EnableValueNames + ? Twine("intliteral.") + llvm::toString(value, 10, true) + : ""); globalArray->setUnnamedAddr(llvm::GlobalVariable::UnnamedAddr::Global); // Various clients expect this to be a i64*, not an [N x i64]*, so cast down. diff --git a/lib/SIL/IR/SILPrinter.cpp b/lib/SIL/IR/SILPrinter.cpp index c491265a869d4..18e1eba93cd83 100644 --- a/lib/SIL/IR/SILPrinter.cpp +++ b/lib/SIL/IR/SILPrinter.cpp @@ -1346,12 +1346,12 @@ class SILPrinter : public SILInstructionVisitor { *this << ILI->getType() << ", " << lit; } void visitFloatLiteralInst(FloatLiteralInst *FLI) { - *this << FLI->getType() << ", 0x"; - APInt bits = FLI->getBits(); - *this << bits.toString(16, /*Signed*/ false); + llvm::SmallString<12> hex; llvm::SmallString<12> decimal; + FLI->getBits().toString(hex, 16, /*Signed*/ false); FLI->getValue().toString(decimal); - *this << " // " << decimal; + *this << FLI->getType() + << (llvm::Twine(", 0x") + hex + " // " + decimal).str(); } static StringRef getStringEncodingName(StringLiteralInst::Encoding kind) { switch (kind) { diff --git a/lib/SILOptimizer/Utils/ConstantFolding.cpp b/lib/SILOptimizer/Utils/ConstantFolding.cpp index 545d25cd35516..45b5886fe4d90 100644 --- a/lib/SILOptimizer/Utils/ConstantFolding.cpp +++ b/lib/SILOptimizer/Utils/ConstantFolding.cpp @@ -23,6 +23,7 @@ #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/Statistic.h" +#include "llvm/ADT/StringExtras.h" #include "llvm/IR/Intrinsics.h" #include "llvm/Support/Debug.h" @@ -245,24 +246,23 @@ constantFoldBinaryWithOverflow(BuiltinInst *BI, llvm::Intrinsic::ID ID, break; } + SmallString<10> LhsStr; + SmallString<10> RhsStr; + LHSInt.toString(LhsStr, /*Radix*/ 10, Signed); + RHSInt.toString(RhsStr, /*Radix*/ 10, Signed); if (!OpType.isNull()) { - diagnose(BI->getModule().getASTContext(), - Loc.getSourceLoc(), - diag::arithmetic_operation_overflow, - LHSInt.toString(/*Radix*/ 10, Signed), - Operator, - RHSInt.toString(/*Radix*/ 10, Signed), - OpType).highlight(LHSRange).highlight(RHSRange); + diagnose(BI->getModule().getASTContext(), Loc.getSourceLoc(), + diag::arithmetic_operation_overflow, LhsStr, Operator, RhsStr, + OpType) + .highlight(LHSRange) + .highlight(RHSRange); } else { // If we cannot get the type info in an expected way, describe the type. - diagnose(BI->getModule().getASTContext(), - Loc.getSourceLoc(), - diag::arithmetic_operation_overflow_generic_type, - LHSInt.toString(/*Radix*/ 10, Signed), - Operator, - RHSInt.toString(/*Radix*/ 10, Signed), - Signed, - LHSInt.getBitWidth()).highlight(LHSRange).highlight(RHSRange); + diagnose(BI->getModule().getASTContext(), Loc.getSourceLoc(), + diag::arithmetic_operation_overflow_generic_type, LhsStr, + Operator, RhsStr, Signed, LHSInt.getBitWidth()) + .highlight(LHSRange) + .highlight(RHSRange); } ResultsInError = Optional(true); } @@ -570,12 +570,11 @@ constantFoldAndCheckDivision(BuiltinInst *BI, BuiltinValueKind ID, // Otherwise emit the diagnostic, set ResultsInError to be true, and return // nullptr. - diagnose(M.getASTContext(), - BI->getLoc().getSourceLoc(), + diagnose(M.getASTContext(), BI->getLoc().getSourceLoc(), diag::division_overflow, - NumVal.toString(/*Radix*/ 10, /*Signed*/true), + llvm::toString(NumVal, /*Radix*/ 10, /*Signed*/ true), IsRem ? "%" : "/", - DenomVal.toString(/*Radix*/ 10, /*Signed*/true)); + llvm::toString(DenomVal, /*Radix*/ 10, /*Signed*/ true)); ResultsInError = Optional(true); return nullptr; } @@ -1366,7 +1365,7 @@ case BuiltinValueKind::id: if (VInt.isNegative() && ResultsInError.hasValue()) { diagnose(M.getASTContext(), BI->getLoc().getSourceLoc(), diag::wrong_non_negative_assumption, - VInt.toString(/*Radix*/ 10, /*Signed*/ true)); + llvm::toString(VInt, /*Radix*/ 10, /*Signed*/ true)); ResultsInError = Optional(true); } return V; diff --git a/lib/Serialization/SerializeSIL.cpp b/lib/Serialization/SerializeSIL.cpp index 6dead8892408d..ae706fa67efc3 100644 --- a/lib/Serialization/SerializeSIL.cpp +++ b/lib/Serialization/SerializeSIL.cpp @@ -1555,7 +1555,7 @@ void SILSerializer::writeSILInstruction(const SILInstruction &SI) { case SILInstructionKind::FloatLiteralInst: case SILInstructionKind::IntegerLiteralInst: { // Use SILOneOperandLayout to specify the type and the literal. - llvm::SmallString Str; + llvm::SmallString<10> Str; SILType Ty; switch (SI.getKind()) { default: llvm_unreachable("Out of sync with parent switch"); From 0919c2cd703881b9a606453e0bfd42467b9bc8ae Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 30 Jun 2021 11:08:33 -0700 Subject: [PATCH 031/116] StringRef ends/startswith-lower -> insensitive Updating StringRef startswith and endswith API to use insensitive rather than lower. (cherry picked from commit 1b8b39e6deb41ef2d551772b114fd974dc762e0d) --- lib/AST/DocComment.cpp | 2 +- lib/Basic/StringExtras.cpp | 6 +++--- lib/IRGen/IRGenModule.cpp | 2 +- lib/Sema/CSStep.cpp | 2 +- tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/AST/DocComment.cpp b/lib/AST/DocComment.cpp index 8f28dd83cb2ff..a8dc09f70d63b 100644 --- a/lib/AST/DocComment.cpp +++ b/lib/AST/DocComment.cpp @@ -191,7 +191,7 @@ bool extractSeparatedParams( auto ParagraphContent = ParagraphText->getLiteralContent(); auto PotentialMatch = ParagraphContent.substr(0, ParameterPrefix.size()); - if (!PotentialMatch.startswith_lower(ParameterPrefix)) { + if (!PotentialMatch.startswith_insensitive(ParameterPrefix)) { NormalItems.push_back(Child); continue; } diff --git a/lib/Basic/StringExtras.cpp b/lib/Basic/StringExtras.cpp index ce3ee468df6ef..5c7687f1aba83 100644 --- a/lib/Basic/StringExtras.cpp +++ b/lib/Basic/StringExtras.cpp @@ -392,8 +392,8 @@ static bool matchNameWordToTypeWord(StringRef nameWord, StringRef typeWord) { // We can match the suffix of the type so long as everything preceding the // match is neither a lowercase letter nor a '_'. This ignores type // prefixes for acronyms, e.g., the 'NS' in 'NSURL'. - if (typeWord.endswith_lower(nameWord) && - !clang::isLowercase(typeWord[typeWord.size()-nameWord.size()])) { + if (typeWord.endswith_insensitive(nameWord) && + !clang::isLowercase(typeWord[typeWord.size() - nameWord.size()])) { // Check that everything preceding the match is neither a lowercase letter // nor a '_'. for (unsigned i = 0, n = nameWord.size(); i != n; ++i) { @@ -405,7 +405,7 @@ static bool matchNameWordToTypeWord(StringRef nameWord, StringRef typeWord) { // We can match a prefix so long as everything following the match is // a number. - if (typeWord.startswith_lower(nameWord)) { + if (typeWord.startswith_insensitive(nameWord)) { for (unsigned i = nameWord.size(), n = typeWord.size(); i != n; ++i) { if (!clang::isDigit(typeWord[i])) return false; } diff --git a/lib/IRGen/IRGenModule.cpp b/lib/IRGen/IRGenModule.cpp index 660ebd67dbfa1..3f6f46000dfd2 100644 --- a/lib/IRGen/IRGenModule.cpp +++ b/lib/IRGen/IRGenModule.cpp @@ -1215,7 +1215,7 @@ llvm::SmallString<32> getTargetDependentLibraryOption(const llvm::Triple &T, if (quote) buffer += '"'; buffer += library; - if (!library.endswith_lower(".lib")) + if (!library.endswith_insensitive(".lib")) buffer += ".lib"; if (quote) buffer += '"'; diff --git a/lib/Sema/CSStep.cpp b/lib/Sema/CSStep.cpp index 5088a782b0f35..deeb249acad86 100644 --- a/lib/Sema/CSStep.cpp +++ b/lib/Sema/CSStep.cpp @@ -756,7 +756,7 @@ bool swift::isSIMDOperator(ValueDecl *value) { if (nominal->getName().empty()) return false; - return nominal->getName().str().startswith_lower("simd"); + return nominal->getName().str().startswith_insensitive("simd"); } bool DisjunctionStep::shortCircuitDisjunctionAt( diff --git a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp index bf06de0191586..35eee7e2706c5 100644 --- a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp +++ b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp @@ -541,7 +541,7 @@ void CodeCompletionOrganizer::Impl::addCompletionsWithFilter( if (options.fuzzyMatching && filterText.size() >= options.minFuzzyLength) { match = pattern.matchesCandidate(completion->getName()); } else { - match = completion->getName().startswith_lower(filterText); + match = completion->getName().startswith_insensitive(filterText); } bool isExactMatch = match && completion->getName().equals_lower(filterText); From 42ff140171dbe9d8f4783e0f40d59b3f7a2bfe63 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 30 Jun 2021 10:49:16 -0700 Subject: [PATCH 032/116] llvm::StringRef equals_lower -> equals_insensitive The `equals_lower` API was replaced with `equals_insensitive` in llvm commit 2e4a2b8430aca6f7aef8100a5ff81ca0328d03f9 and 3eed57e7ef7da5eda765ccc19fd26fb8dfcd8d41. Ran git clang-format. (cherry picked from commit e21e70a6bf1d9fb5743e3d1deb1b5db20e8f9910) --- lib/AST/DocComment.cpp | 2 +- lib/Basic/StringExtras.cpp | 14 +++++++------- lib/IDE/SyntaxModel.cpp | 4 ++-- lib/Sema/CSDiagnostics.cpp | 2 +- .../lib/SwiftLang/CodeCompletionOrganizer.cpp | 3 ++- .../tools/sourcekitd-test/sourcekitd-test.cpp | 4 ++-- 6 files changed, 15 insertions(+), 14 deletions(-) diff --git a/lib/AST/DocComment.cpp b/lib/AST/DocComment.cpp index a8dc09f70d63b..9d290a180f623 100644 --- a/lib/AST/DocComment.cpp +++ b/lib/AST/DocComment.cpp @@ -115,7 +115,7 @@ bool extractParameterOutline( } auto HeadingContent = HeadingText->getLiteralContent(); - if (!HeadingContent.rtrim().equals_lower("parameters:")) { + if (!HeadingContent.rtrim().equals_insensitive("parameters:")) { NormalItems.push_back(Child); continue; } diff --git a/lib/Basic/StringExtras.cpp b/lib/Basic/StringExtras.cpp index 5c7687f1aba83..57dd2ecd0f5b8 100644 --- a/lib/Basic/StringExtras.cpp +++ b/lib/Basic/StringExtras.cpp @@ -45,8 +45,8 @@ bool swift::canBeMemberName(StringRef identifier) { } bool swift::isPreposition(StringRef word) { -#define PREPOSITION(Word) \ - if (word.equals_lower(#Word)) \ +#define PREPOSITION(Word) \ + if (word.equals_insensitive(#Word)) \ return true; #include "PartsOfSpeech.def" @@ -55,11 +55,11 @@ bool swift::isPreposition(StringRef word) { PartOfSpeech swift::getPartOfSpeech(StringRef word) { // FIXME: This implementation is woefully inefficient. -#define PREPOSITION(Word) \ - if (word.equals_lower(#Word)) \ +#define PREPOSITION(Word) \ + if (word.equals_insensitive(#Word)) \ return PartOfSpeech::Preposition; -#define VERB(Word) \ - if (word.equals_lower(#Word)) \ +#define VERB(Word) \ + if (word.equals_insensitive(#Word)) \ return PartOfSpeech::Verb; #include "PartsOfSpeech.def" @@ -417,7 +417,7 @@ static bool matchNameWordToTypeWord(StringRef nameWord, StringRef typeWord) { } // Check for an exact match. - return nameWord.equals_lower(typeWord); + return nameWord.equals_insensitive(typeWord); } /// Match the beginning of the name to the given type name. diff --git a/lib/IDE/SyntaxModel.cpp b/lib/IDE/SyntaxModel.cpp index 147e5d124d5e4..4a1f0aac456fc 100644 --- a/lib/IDE/SyntaxModel.cpp +++ b/lib/IDE/SyntaxModel.cpp @@ -1624,7 +1624,7 @@ class DocFieldParser { ; StringRef ident(identStart, ptr - identStart); - if (ident.equals_lower("parameter")) { + if (ident.equals_insensitive("parameter")) { if (numSpaces > 1 || !advanceIf(' ')) return None; while (advanceIf([](char c) { return c != ':'; })) @@ -1634,7 +1634,7 @@ class DocFieldParser { return ident; } else if (advanceIf(':')) { - if (ident.equals_lower("parameters") && numSpaces > 1) + if (ident.equals_insensitive("parameters") && numSpaces > 1) return None; auto lowerIdent = ident.lower(); bool isField = llvm::StringSwitch(lowerIdent) diff --git a/lib/Sema/CSDiagnostics.cpp b/lib/Sema/CSDiagnostics.cpp index ccc9f0954045c..bd2b5d8474016 100644 --- a/lib/Sema/CSDiagnostics.cpp +++ b/lib/Sema/CSDiagnostics.cpp @@ -3459,7 +3459,7 @@ DeclName MissingMemberFailure::findCorrectEnumCaseName( auto candidate = corrections.getUniqueCandidateMatching([&](ValueDecl *candidate) { return (isa(candidate) && - candidate->getBaseIdentifier().str().equals_lower( + candidate->getBaseIdentifier().str().equals_insensitive( memberName.getBaseIdentifier().str())); }); return (candidate ? candidate->getName() : DeclName()); diff --git a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp index 35eee7e2706c5..0e2a180eab486 100644 --- a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp +++ b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp @@ -544,7 +544,8 @@ void CodeCompletionOrganizer::Impl::addCompletionsWithFilter( match = completion->getName().startswith_insensitive(filterText); } - bool isExactMatch = match && completion->getName().equals_lower(filterText); + bool isExactMatch = + match && completion->getName().equals_insensitive(filterText); if (isExactMatch) { if (!exactMatch) { // first match diff --git a/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp b/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp index 9e052d541b931..5838d04b46c6b 100644 --- a/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp +++ b/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp @@ -302,9 +302,9 @@ static int printDiags(); static void getSemanticInfo(sourcekitd_variant_t Info, StringRef Filename); static Optional getReqOptValueAsInt(StringRef Value) { - if (Value.equals_lower("true")) + if (Value.equals_insensitive("true")) return 1; - if (Value.equals_lower("false")) + if (Value.equals_insensitive("false")) return 0; int64_t Ret; if (Value.find_first_not_of("-0123456789") != StringRef::npos || From 2c04be27245eab1dc29129ab0d690c687f2e81d6 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 30 Jun 2021 10:46:14 -0700 Subject: [PATCH 033/116] llvm::StringRef compare_lower -> compare_insensitive The `compare_lower` API was replaced with `compare_insensitive` in llvm commit 2e4a2b8430aca6f7aef8100a5ff81ca0328d03f9. git clang-format ran. (cherry picked from commit aca2de95ee26e37a9ecf4837f12a31d3c5ee9110) --- lib/AST/ASTContext.cpp | 2 +- lib/IDE/CodeCompletion.cpp | 14 +++++++------- lib/IDE/ModuleInterfacePrinting.cpp | 5 +++-- lib/Markup/AST.cpp | 12 ++++++------ .../lib/SwiftLang/CodeCompletionOrganizer.cpp | 2 +- tools/driver/swift_api_digester_main.cpp | 8 +++++--- 6 files changed, 23 insertions(+), 20 deletions(-) diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp index 8265a6fe1a2ae..2e061672921a6 100644 --- a/lib/AST/ASTContext.cpp +++ b/lib/AST/ASTContext.cpp @@ -2028,7 +2028,7 @@ void ASTContext::getVisibleTopLevelModuleNames( // Sort and unique. std::sort(names.begin(), names.end(), [](Identifier LHS, Identifier RHS) { - return LHS.str().compare_lower(RHS.str()) < 0; + return LHS.str().compare_insensitive(RHS.str()) < 0; }); names.erase(std::unique(names.begin(), names.end()), names.end()); } diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp index 81ab6ac7996d0..835c1206ea99c 100644 --- a/lib/IDE/CodeCompletion.cpp +++ b/lib/IDE/CodeCompletion.cpp @@ -1502,13 +1502,13 @@ void CodeCompletionContext::sortCompletionResults( // Sort nameCache, and then transform Results to return the pointers in order. std::sort(nameCache.begin(), nameCache.end(), [](const ResultAndName &LHS, const ResultAndName &RHS) { - int Result = StringRef(LHS.name).compare_lower(RHS.name); - // If the case insensitive comparison is equal, then secondary sort order - // should be case sensitive. - if (Result == 0) - Result = LHS.name.compare(RHS.name); - return Result < 0; - }); + int Result = StringRef(LHS.name).compare_insensitive(RHS.name); + // If the case insensitive comparison is equal, then secondary + // sort order should be case sensitive. + if (Result == 0) + Result = LHS.name.compare(RHS.name); + return Result < 0; + }); llvm::transform(nameCache, Results.begin(), [](const ResultAndName &entry) { return entry.result; }); diff --git a/lib/IDE/ModuleInterfacePrinting.cpp b/lib/IDE/ModuleInterfacePrinting.cpp index f11e4e3126da2..ede301374bc9c 100644 --- a/lib/IDE/ModuleInterfacePrinting.cpp +++ b/lib/IDE/ModuleInterfacePrinting.cpp @@ -207,8 +207,9 @@ void swift::ide::collectModuleGroups(ModuleDecl *M, for (auto File : M->getFiles()) { File->collectAllGroups(Into); } - std::sort(Into.begin(), Into.end(), - [](StringRef L, StringRef R) { return L.compare_lower(R) < 0; }); + std::sort(Into.begin(), Into.end(), [](StringRef L, StringRef R) { + return L.compare_insensitive(R) < 0; + }); } /// Determine whether the given extension has a Clang node that diff --git a/lib/Markup/AST.cpp b/lib/Markup/AST.cpp index b4b3bec013557..9d55716a20382 100644 --- a/lib/Markup/AST.cpp +++ b/lib/Markup/AST.cpp @@ -341,9 +341,9 @@ swift::markup::MarkupASTNode *swift::markup::createSimpleField( if (false) { } -#define MARKUP_SIMPLE_FIELD(Id, Keyword, XMLKind) \ - else if (Tag.compare_lower(#Keyword) == 0) { \ - return Id::create(MC, Children); \ +#define MARKUP_SIMPLE_FIELD(Id, Keyword, XMLKind) \ + else if (Tag.compare_insensitive(#Keyword) == 0) { \ + return Id::create(MC, Children); \ } #include "swift/Markup/SimpleFields.def" llvm_unreachable("Given tag not for any simple markup field"); @@ -353,9 +353,9 @@ bool swift::markup::isAFieldTag(StringRef Tag) { if (false) { } -#define MARKUP_SIMPLE_FIELD(Id, Keyword, XMLKind) \ - else if (Tag.compare_lower(#Keyword) == 0) { \ - return true; \ +#define MARKUP_SIMPLE_FIELD(Id, Keyword, XMLKind) \ + else if (Tag.compare_insensitive(#Keyword) == 0) { \ + return true; \ } #include "swift/Markup/SimpleFields.def" return false; diff --git a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp index 0e2a180eab486..b27128a1c3c03 100644 --- a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp +++ b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp @@ -625,7 +625,7 @@ static double combinedScore(const Options &options, double matchScore, static int compareResultName(Item &a, Item &b) { // Sort first by filter name (case-insensitive). - if (int primary = StringRef(a.name).compare_lower(b.name)) + if (int primary = StringRef(a.name).compare_insensitive(b.name)) return primary; // Next, sort by full description text. diff --git a/tools/driver/swift_api_digester_main.cpp b/tools/driver/swift_api_digester_main.cpp index db049c399be04..a8fc409b493e3 100644 --- a/tools/driver/swift_api_digester_main.cpp +++ b/tools/driver/swift_api_digester_main.cpp @@ -196,13 +196,15 @@ class RemovedAddedNodeMatcher : public NodeMatcher, public MatchedNodeListener { bool detectFuncToProperty(SDKNode *R, SDKNode *A) { if (R->getKind() == SDKNodeKind::DeclFunction) { if (A->getKind() == SDKNodeKind::DeclVar) { - if (A->getName().compare_lower(R->getName()) == 0) { + if (A->getName().compare_insensitive(R->getName()) == 0) { R->annotate(NodeAnnotation::GetterToProperty); } else if (R->getName().startswith("get") && - R->getName().substr(3).compare_lower(A->getName()) == 0) { + R->getName().substr(3).compare_insensitive(A->getName()) == + 0) { R->annotate(NodeAnnotation::GetterToProperty); } else if (R->getName().startswith("set") && - R->getName().substr(3).compare_lower(A->getName()) == 0) { + R->getName().substr(3).compare_insensitive(A->getName()) == + 0) { R->annotate(NodeAnnotation::SetterToProperty); } else { return false; From 902cbd259af73781540cde8aa8fa2068dca692e4 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Fri, 25 Jun 2021 13:59:32 -0700 Subject: [PATCH 034/116] Add missing ArrayRef.h include makeArrayRef was being included through an import an DenseMap.h -> DenseMapInfo.h -> ArrayRef.h. That was broken fairly recently. (cherry picked from commit fe2b3c6021583f34b7c5833cebc2f439e10e6f35) --- include/swift/Basic/MultiMapCache.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/swift/Basic/MultiMapCache.h b/include/swift/Basic/MultiMapCache.h index ab90b710823cc..b13fc7975d40d 100644 --- a/include/swift/Basic/MultiMapCache.h +++ b/include/swift/Basic/MultiMapCache.h @@ -14,6 +14,7 @@ #define SWIFT_BASIC_MULTIMAPCACHE_H #include "swift/Basic/LLVM.h" +#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" namespace swift { From 9a33e8f07ac9cbfbdd5873d564400150374b0446 Mon Sep 17 00:00:00 2001 From: Eric Miotto <1094986+edymtt@users.noreply.github.com> Date: Tue, 6 Jul 2021 09:59:41 -0700 Subject: [PATCH 035/116] Include `` in `Ownership.h` This is to address the following failure in Linux ``` /home/buildnode/jenkins/workspace/swift-PR-Linux-smoke-test@2/branch-rebranch/swift/include/swift/AST/ReferenceStorage.def:189:1: error: use of undeclared identifier 'INT_MIN' ``` --- include/swift/AST/Ownership.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/swift/AST/Ownership.h b/include/swift/AST/Ownership.h index ee8c2e273e5cd..c8bf8c0c16fb6 100644 --- a/include/swift/AST/Ownership.h +++ b/include/swift/AST/Ownership.h @@ -26,6 +26,7 @@ #include "llvm/Support/raw_ostream.h" #include #include +#include namespace swift { From 685ebd4660350e8b89f86e8fa6065dc7811cdc86 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 30 Jun 2021 14:41:15 -0700 Subject: [PATCH 036/116] Fix `PrintName` calls OptTable::PrintName was renamed 'printName' in commit f1e2d5851bf86. --- lib/Driver/Driver.cpp | 2 +- lib/FrontendTool/FrontendTool.cpp | 2 +- tools/SourceKit/tools/sourcekitd-test/TestOptions.cpp | 2 +- tools/driver/autolink_extract_main.cpp | 2 +- tools/driver/modulewrap_main.cpp | 2 +- tools/driver/swift_api_digester_main.cpp | 2 +- tools/driver/swift_api_extract_main.cpp | 2 +- tools/driver/swift_indent_main.cpp | 2 +- tools/driver/swift_symbolgraph_extract_main.cpp | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp index 602b8f32c9a59..ea03ee75e5192 100644 --- a/lib/Driver/Driver.cpp +++ b/lib/Driver/Driver.cpp @@ -3539,7 +3539,7 @@ void Driver::printHelp(bool ShowHidden) const { if (!ShowHidden) ExcludedFlagsBitmask |= HelpHidden; - getOpts().PrintHelp(llvm::outs(), Name.c_str(), "Swift compiler", + getOpts().printHelp(llvm::outs(), Name.c_str(), "Swift compiler", IncludedFlagsBitmask, ExcludedFlagsBitmask, /*ShowAllAliases*/false); diff --git a/lib/FrontendTool/FrontendTool.cpp b/lib/FrontendTool/FrontendTool.cpp index 86510267e6211..f11a8aaad290d 100644 --- a/lib/FrontendTool/FrontendTool.cpp +++ b/lib/FrontendTool/FrontendTool.cpp @@ -2108,7 +2108,7 @@ int swift::performFrontend(ArrayRef Args, Invocation.getFrontendOptions().PrintHelpHidden ? 0 : llvm::opt::HelpHidden; std::unique_ptr Options(createSwiftOptTable()); - Options->PrintHelp(llvm::outs(), displayName(MainExecutablePath).c_str(), + Options->printHelp(llvm::outs(), displayName(MainExecutablePath).c_str(), "Swift frontend", IncludedFlagsBitmask, ExcludedFlagsBitmask, /*ShowAllAliases*/false); return finishDiagProcessing(0, /*verifierEnabled*/ false); diff --git a/tools/SourceKit/tools/sourcekitd-test/TestOptions.cpp b/tools/SourceKit/tools/sourcekitd-test/TestOptions.cpp index d3091dcbbaf3c..da867d9c99655 100644 --- a/tools/SourceKit/tools/sourcekitd-test/TestOptions.cpp +++ b/tools/SourceKit/tools/sourcekitd-test/TestOptions.cpp @@ -446,6 +446,6 @@ void TestOptions::printHelp(bool ShowHidden) const { TestOptTable Table; - Table.PrintHelp(llvm::outs(), "sourcekitd-test [options] ", + Table.printHelp(llvm::outs(), "sourcekitd-test [options] ", "SourceKit Testing Tool", ShowHidden); } diff --git a/tools/driver/autolink_extract_main.cpp b/tools/driver/autolink_extract_main.cpp index 64c0252c8ef04..ba1c120928437 100644 --- a/tools/driver/autolink_extract_main.cpp +++ b/tools/driver/autolink_extract_main.cpp @@ -82,7 +82,7 @@ class AutolinkExtractInvocation { if (ParsedArgs.getLastArg(OPT_help)) { std::string ExecutableName = llvm::sys::path::stem(MainExecutablePath).str(); - Table->PrintHelp(llvm::outs(), ExecutableName.c_str(), + Table->printHelp(llvm::outs(), ExecutableName.c_str(), "Swift Autolink Extract", options::AutolinkExtractOption, 0, /*ShowAllAliases*/false); return 1; diff --git a/tools/driver/modulewrap_main.cpp b/tools/driver/modulewrap_main.cpp index 9166e066974b5..daadbd8648c8a 100644 --- a/tools/driver/modulewrap_main.cpp +++ b/tools/driver/modulewrap_main.cpp @@ -96,7 +96,7 @@ class ModuleWrapInvocation { if (ParsedArgs.getLastArg(OPT_help)) { std::string ExecutableName = llvm::sys::path::stem(MainExecutablePath).str(); - Table->PrintHelp(llvm::outs(), ExecutableName.c_str(), + Table->printHelp(llvm::outs(), ExecutableName.c_str(), "Swift Module Wrapper", options::ModuleWrapOption, 0, /*ShowAllAliases*/false); return 1; diff --git a/tools/driver/swift_api_digester_main.cpp b/tools/driver/swift_api_digester_main.cpp index a759c62b9ddff..4c1058b1fc072 100644 --- a/tools/driver/swift_api_digester_main.cpp +++ b/tools/driver/swift_api_digester_main.cpp @@ -2655,7 +2655,7 @@ class SwiftAPIDigesterInvocation { void printHelp() { std::string ExecutableName = llvm::sys::path::stem(MainExecutablePath).str(); - Table->PrintHelp(llvm::outs(), ExecutableName.c_str(), "Swift API Digester", + Table->printHelp(llvm::outs(), ExecutableName.c_str(), "Swift API Digester", /*IncludedFlagsBitmask*/ SwiftAPIDigesterOption, /*ExcludedFlagsBitmask*/ 0, /*ShowAllAliases*/ false); diff --git a/tools/driver/swift_api_extract_main.cpp b/tools/driver/swift_api_extract_main.cpp index 70dda49862c41..57c98dbd9f092 100644 --- a/tools/driver/swift_api_extract_main.cpp +++ b/tools/driver/swift_api_extract_main.cpp @@ -65,7 +65,7 @@ class SwiftAPIExtractInvocation { if (ParsedArgs.getLastArg(OPT_help)) { std::string ExecutableName = llvm::sys::path::stem(MainExecutablePath).str(); - Table->PrintHelp(llvm::outs(), ExecutableName.c_str(), + Table->printHelp(llvm::outs(), ExecutableName.c_str(), "Swift API Extract", options::SwiftAPIExtractOption, 0, /*ShowAllAliases*/ false); return 1; diff --git a/tools/driver/swift_indent_main.cpp b/tools/driver/swift_indent_main.cpp index ff2d8d1ae00a8..c9997169edfa0 100644 --- a/tools/driver/swift_indent_main.cpp +++ b/tools/driver/swift_indent_main.cpp @@ -149,7 +149,7 @@ class SwiftIndentInvocation { if (ParsedArgs.getLastArg(OPT_help)) { std::string ExecutableName = llvm::sys::path::stem(MainExecutablePath).str(); - Table->PrintHelp(llvm::outs(), ExecutableName.c_str(), + Table->printHelp(llvm::outs(), ExecutableName.c_str(), "Swift Format Tool", options::SwiftIndentOption, 0, /*ShowAllAliases*/false); return 1; diff --git a/tools/driver/swift_symbolgraph_extract_main.cpp b/tools/driver/swift_symbolgraph_extract_main.cpp index 7297c5ac55aa4..29cb48ef6db4e 100644 --- a/tools/driver/swift_symbolgraph_extract_main.cpp +++ b/tools/driver/swift_symbolgraph_extract_main.cpp @@ -62,7 +62,7 @@ int swift_symbolgraph_extract_main(ArrayRef Args, if (ParsedArgs.getLastArg(OPT_help) || Args.empty()) { std::string ExecutableName = llvm::sys::path::stem(MainExecutablePath).str(); - Table->PrintHelp(llvm::outs(), ExecutableName.c_str(), + Table->printHelp(llvm::outs(), ExecutableName.c_str(), "Swift Symbol Graph Extractor", SwiftSymbolGraphExtractOption, 0, /*ShowAllAliases*/ false); From 4046f61ba9e47c86007339d9a4c43816c45ee77c Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Fri, 25 Jun 2021 16:37:52 -0700 Subject: [PATCH 037/116] VK_RValue -> VK_PRValue Clang updated the naming in commit aef5d8fdc7d0d348125d5ecf4a13be5888eb1654 in order to be more consistent with c++11 category naming. --- lib/ClangImporter/ImportDecl.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp index 48d2198a236f9..a253a96507900 100644 --- a/lib/ClangImporter/ImportDecl.cpp +++ b/lib/ClangImporter/ImportDecl.cpp @@ -1167,14 +1167,14 @@ makeBitFieldAccessors(ClangImporter::Implementation &Impl, auto cGetterSelfExpr = new (Ctx) clang::DeclRefExpr(Ctx, cGetterSelf, false, recordType, - clang::VK_RValue, + clang::VK_PRValue, clang::SourceLocation()); auto cGetterExpr = clang::MemberExpr::CreateImplicit(Ctx, cGetterSelfExpr, /*isarrow=*/ false, fieldDecl, fieldType, - clang::VK_RValue, + clang::VK_PRValue, clang::OK_BitField); @@ -1211,7 +1211,7 @@ makeBitFieldAccessors(ClangImporter::Implementation &Impl, auto cSetterSelfExpr = new (Ctx) clang::DeclRefExpr(Ctx, cSetterSelf, false, recordPointerType, - clang::VK_RValue, + clang::VK_PRValue, clang::SourceLocation()); auto cSetterMemberExpr = clang::MemberExpr::CreateImplicit(Ctx, @@ -1224,7 +1224,7 @@ makeBitFieldAccessors(ClangImporter::Implementation &Impl, auto cSetterValueExpr = new (Ctx) clang::DeclRefExpr(Ctx, cSetterValue, false, fieldType, - clang::VK_RValue, + clang::VK_PRValue, clang::SourceLocation()); auto cSetterExpr = clang::BinaryOperator::Create(Ctx, @@ -1232,7 +1232,7 @@ makeBitFieldAccessors(ClangImporter::Implementation &Impl, cSetterValueExpr, clang::BO_Assign, fieldType, - clang::VK_RValue, + clang::VK_PRValue, clang::OK_Ordinary, clang::SourceLocation(), clang::FPOptionsOverride()); From 1e6787925f4b6b9b6a59e28458a22ba2a4314a5a Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Thu, 1 Jul 2021 16:38:18 -0700 Subject: [PATCH 038/116] Fix IRGen datalayout Same issue as with TBDGen. Clang doesn't hold onto the Datalayout object anymore, but instead keeps the description string that is constructed on the fly. This patch updates IRGen to behave the same way. --- lib/IRGen/IRGen.cpp | 2 +- lib/IRGen/IRGenModule.cpp | 19 +++++++++---------- lib/IRGen/IRGenModule.h | 2 +- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/lib/IRGen/IRGen.cpp b/lib/IRGen/IRGen.cpp index 09dd430bcfa1d..987111913ad9a 100644 --- a/lib/IRGen/IRGen.cpp +++ b/lib/IRGen/IRGen.cpp @@ -1533,7 +1533,7 @@ bool swift::performLLVM(const IRGenOptions &Opts, ASTContext &Ctx, auto *Clang = static_cast(Ctx.getClangModuleLoader()); // Use clang's datalayout. - Module->setDataLayout(Clang->getTargetInfo().getDataLayout()); + Module->setDataLayout(Clang->getTargetInfo().getDataLayoutString()); embedBitcode(Module, Opts); if (::performLLVM(Opts, Ctx.Diags, nullptr, nullptr, Module, diff --git a/lib/IRGen/IRGenModule.cpp b/lib/IRGen/IRGenModule.cpp index 103bee8fef4b9..4d2fa324efd0d 100644 --- a/lib/IRGen/IRGenModule.cpp +++ b/lib/IRGen/IRGenModule.cpp @@ -192,19 +192,18 @@ static void sanityCheckStdlib(IRGenModule &IGM) { IRGenModule::IRGenModule(IRGenerator &irgen, std::unique_ptr &&target, - SourceFile *SF, - StringRef ModuleName, StringRef OutputFilename, + SourceFile *SF, StringRef ModuleName, + StringRef OutputFilename, StringRef MainInputFilenameForDebugInfo, StringRef PrivateDiscriminator) - : LLVMContext(new llvm::LLVMContext()), - IRGen(irgen), Context(irgen.SIL.getASTContext()), + : LLVMContext(new llvm::LLVMContext()), IRGen(irgen), + Context(irgen.SIL.getASTContext()), // The LLVMContext (and the IGM itself) will get deleted by the IGMDeleter // as long as the IGM is registered with the IRGenerator. - ClangCodeGen(createClangCodeGenerator(Context, *LLVMContext, - irgen.Opts, + ClangCodeGen(createClangCodeGenerator(Context, *LLVMContext, irgen.Opts, ModuleName, PrivateDiscriminator)), Module(*ClangCodeGen->GetModule()), - DataLayout(irgen.getClangDataLayout()), + DataLayout(irgen.getClangDataLayoutString()), Triple(irgen.getEffectiveClangTriple()), TargetMachine(std::move(target)), silConv(irgen.SIL), OutputFilename(OutputFilename), MainInputFilenameForDebugInfo(MainInputFilenameForDebugInfo), @@ -1750,12 +1749,12 @@ llvm::Triple IRGenerator::getEffectiveClangTriple() { return llvm::Triple(CI->getTargetInfo().getTargetOpts().Triple); } -const llvm::DataLayout &IRGenerator::getClangDataLayout() { +const llvm::StringRef IRGenerator::getClangDataLayoutString() { return static_cast( SIL.getASTContext().getClangModuleLoader()) ->getTargetInfo() - .getDataLayout(); - } + .getDataLayoutString(); +} TypeExpansionContext IRGenModule::getMaximalTypeExpansionContext() const { return TypeExpansionContext::maximal(getSwiftModule(), diff --git a/lib/IRGen/IRGenModule.h b/lib/IRGen/IRGenModule.h index 02e7c6077dd54..fddcef1a699fa 100644 --- a/lib/IRGen/IRGenModule.h +++ b/lib/IRGen/IRGenModule.h @@ -519,7 +519,7 @@ class IRGenerator { /// Return the effective triple used by clang. llvm::Triple getEffectiveClangTriple(); - const llvm::DataLayout &getClangDataLayout(); + const llvm::StringRef getClangDataLayoutString(); }; class ConstantReference { From 58e2f5301a20ed511a0ac2a4b2c8267145d5b22b Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Thu, 1 Jul 2021 16:33:39 -0700 Subject: [PATCH 039/116] Fix TBDGen datalayout This patch fixes the call to get the datalayout from the clang module. Clang no longer holds onto the DataLayout object, so we have to do that if we want to keep it around. Rather than instanciating it early, we can just hold onto the string description, which clang does keep around, and only construct the actual DataLayout once we need it. --- include/swift/AST/TBDGenRequests.h | 2 +- lib/TBDGen/TBDGen.cpp | 6 ++++-- lib/TBDGen/TBDGenRequests.cpp | 4 ++-- lib/TBDGen/TBDGenVisitor.h | 8 +++++--- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/include/swift/AST/TBDGenRequests.h b/include/swift/AST/TBDGenRequests.h index d68f36854b4d0..6bfa735c1031e 100644 --- a/include/swift/AST/TBDGenRequests.h +++ b/include/swift/AST/TBDGenRequests.h @@ -70,7 +70,7 @@ class TBDGenDescriptor final { const TBDGenOptions &getOptions() const { return Opts; } TBDGenOptions &getOptions() { return Opts; } - const llvm::DataLayout &getDataLayout() const; + const StringRef getDataLayoutString() const; const llvm::Triple &getTarget() const; bool operator==(const TBDGenDescriptor &other) const; diff --git a/lib/TBDGen/TBDGen.cpp b/lib/TBDGen/TBDGen.cpp index aec10dca625ba..98002ffccf6b5 100644 --- a/lib/TBDGen/TBDGen.cpp +++ b/lib/TBDGen/TBDGen.cpp @@ -68,7 +68,7 @@ static bool isGlobalOrStaticVar(VarDecl *VD) { TBDGenVisitor::TBDGenVisitor(const TBDGenDescriptor &desc, APIRecorder &recorder) - : TBDGenVisitor(desc.getTarget(), desc.getDataLayout(), + : TBDGenVisitor(desc.getTarget(), desc.getDataLayoutString(), desc.getParentModule(), desc.getOptions(), recorder) {} void TBDGenVisitor::addSymbolInternal(StringRef name, SymbolKind kind, @@ -390,7 +390,9 @@ void TBDGenVisitor::addSymbol(StringRef name, SymbolSource source, if (kind == SymbolKind::ObjectiveCClass) { mangled = name; } else { - llvm::Mangler::getNameWithPrefix(mangled, name, DataLayout); + if (!DataLayout) + DataLayout = llvm::DataLayout(DataLayoutDescription); + llvm::Mangler::getNameWithPrefix(mangled, name, *DataLayout); } addSymbolInternal(mangled, kind, source); diff --git a/lib/TBDGen/TBDGenRequests.cpp b/lib/TBDGen/TBDGenRequests.cpp index a298987054bd1..09c3fd613cc87 100644 --- a/lib/TBDGen/TBDGenRequests.cpp +++ b/lib/TBDGen/TBDGenRequests.cpp @@ -48,10 +48,10 @@ ModuleDecl *TBDGenDescriptor::getParentModule() const { return Input.get()->getParentModule(); } -const llvm::DataLayout &TBDGenDescriptor::getDataLayout() const { +const StringRef TBDGenDescriptor::getDataLayoutString() const { auto &ctx = getParentModule()->getASTContext(); auto *clang = static_cast(ctx.getClangModuleLoader()); - return clang->getTargetInfo().getDataLayout(); + return llvm::StringRef(clang->getTargetInfo().getDataLayoutString()); } const llvm::Triple &TBDGenDescriptor::getTarget() const { diff --git a/lib/TBDGen/TBDGenVisitor.h b/lib/TBDGen/TBDGenVisitor.h index 63d6970926840..0febc874a7838 100644 --- a/lib/TBDGen/TBDGenVisitor.h +++ b/lib/TBDGen/TBDGenVisitor.h @@ -92,7 +92,9 @@ class TBDGenVisitor : public ASTVisitor { llvm::StringSet<> DuplicateSymbolChecker; #endif - const llvm::DataLayout &DataLayout; + Optional DataLayout = None; + const StringRef DataLayoutDescription; + UniversalLinkageInfo UniversalLinkInfo; ModuleDecl *SwiftModule; const TBDGenOptions &Opts; @@ -167,10 +169,10 @@ class TBDGenVisitor : public ASTVisitor { const AutoDiffConfig &config); public: - TBDGenVisitor(const llvm::Triple &target, const llvm::DataLayout &dataLayout, + TBDGenVisitor(const llvm::Triple &target, const StringRef dataLayoutString, ModuleDecl *swiftModule, const TBDGenOptions &opts, APIRecorder &recorder) - : DataLayout(dataLayout), + : DataLayoutDescription(dataLayoutString), UniversalLinkInfo(target, opts.HasMultipleIGMs, /*forcePublic*/ false), SwiftModule(swiftModule), Opts(opts), recorder(recorder), previousInstallNameMap(parsePreviousModuleInstallNameMap()) {} From 45f2229789a119c3131fcd90c06c7e48264f0db9 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Fri, 25 Jun 2021 15:15:38 -0700 Subject: [PATCH 040/116] Provide withNullAsEmptyStringRef impl We only see this failure in one file, so I've added a static implementation there. Should take care of that issue. --- lib/Serialization/Serialization.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp index 02d92e36a5a5d..69d7919616319 100644 --- a/lib/Serialization/Serialization.cpp +++ b/lib/Serialization/Serialization.cpp @@ -78,6 +78,10 @@ using llvm::BCBlockRAII; ASTContext &SerializerBase::getASTContext() const { return M->getASTContext(); } +static StringRef withNullAsEmptyStringRef(const char *data) { + return StringRef(data ? data : ""); +} + /// Used for static_assert. static constexpr bool declIDFitsIn32Bits() { using Int32Info = std::numeric_limits; @@ -5554,7 +5558,7 @@ void swift::serializeToBuffers( std::unique_ptr *moduleSourceInfoBuffer, const SILModule *M) { - assert(!StringRef::withNullAsEmpty(options.OutputPath).empty()); + assert(!withNullAsEmptyStringRef(options.OutputPath).empty()); { FrontendStatsTracer tracer(getContext(DC).Stats, "Serialization, swiftmodule, to buffer"); @@ -5575,7 +5579,7 @@ void swift::serializeToBuffers( std::move(buf), options.OutputPath); } - if (!StringRef::withNullAsEmpty(options.DocOutputPath).empty()) { + if (!withNullAsEmptyStringRef(options.DocOutputPath).empty()) { FrontendStatsTracer tracer(getContext(DC).Stats, "Serialization, swiftdoc, to buffer"); llvm::SmallString<1024> buf; @@ -5592,7 +5596,7 @@ void swift::serializeToBuffers( std::move(buf), options.DocOutputPath); } - if (!StringRef::withNullAsEmpty(options.SourceInfoOutputPath).empty()) { + if (!withNullAsEmptyStringRef(options.SourceInfoOutputPath).empty()) { FrontendStatsTracer tracer(getContext(DC).Stats, "Serialization, swiftsourceinfo, to buffer"); llvm::SmallString<1024> buf; @@ -5614,12 +5618,12 @@ void swift::serialize(ModuleOrSourceFile DC, const SerializationOptions &options, const SILModule *M, const fine_grained_dependencies::SourceFileDepGraph *DG) { - assert(!StringRef::withNullAsEmpty(options.OutputPath).empty()); + assert(!withNullAsEmptyStringRef(options.OutputPath).empty()); if (StringRef(options.OutputPath) == "-") { // Special-case writing to stdout. Serializer::writeToStream(llvm::outs(), DC, M, options, DG); - assert(StringRef::withNullAsEmpty(options.DocOutputPath).empty()); + assert(withNullAsEmptyStringRef(options.DocOutputPath).empty()); return; } @@ -5634,7 +5638,7 @@ void swift::serialize(ModuleOrSourceFile DC, if (hadError) return; - if (!StringRef::withNullAsEmpty(options.DocOutputPath).empty()) { + if (!withNullAsEmptyStringRef(options.DocOutputPath).empty()) { (void)withOutputFile(getContext(DC).Diags, options.DocOutputPath, [&](raw_ostream &out) { @@ -5645,7 +5649,7 @@ void swift::serialize(ModuleOrSourceFile DC, }); } - if (!StringRef::withNullAsEmpty(options.SourceInfoOutputPath).empty()) { + if (!withNullAsEmptyStringRef(options.SourceInfoOutputPath).empty()) { (void)withOutputFile(getContext(DC).Diags, options.SourceInfoOutputPath, [&](raw_ostream &out) { From 29509d16edf806553e4b308973014a71f4fda34c Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Fri, 25 Jun 2021 15:57:08 -0700 Subject: [PATCH 041/116] Add Format.h to swift-syntax-parser-test Something happened so that's not being transitively included. Adding it in explicitly. --- tools/swift-syntax-parser-test/swift-syntax-parser-test.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/swift-syntax-parser-test/swift-syntax-parser-test.cpp b/tools/swift-syntax-parser-test/swift-syntax-parser-test.cpp index f1e5eb3e71fe8..5f0e55c8d2d21 100644 --- a/tools/swift-syntax-parser-test/swift-syntax-parser-test.cpp +++ b/tools/swift-syntax-parser-test/swift-syntax-parser-test.cpp @@ -18,9 +18,10 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/LLVMInitialize.h" #include "llvm/Support/CommandLine.h" +#include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/Timer.h" #include "llvm/Support/SourceMgr.h" +#include "llvm/Support/Timer.h" using namespace swift; using namespace llvm; From 5a1b0f82e1578b73fe77d547181bb8c3c0ae293c Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Fri, 25 Jun 2021 17:05:42 -0700 Subject: [PATCH 042/116] Fix call to `collectUsedGlobalVariables` LLVM commit 3adb89bb9f8e73c82787babb2f877fece7394770 updated the API of this function to take a reference to a `SmallVectorImpl` instead of a set to ensure that it behaves deterministically. --- lib/IRGen/IRGen.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/IRGen/IRGen.cpp b/lib/IRGen/IRGen.cpp index 09dd430bcfa1d..2c55e09150197 100644 --- a/lib/IRGen/IRGen.cpp +++ b/lib/IRGen/IRGen.cpp @@ -824,7 +824,7 @@ static void embedBitcode(llvm::Module *M, const IRGenOptions &Opts) // Save llvm.compiler.used and remove it. SmallVector UsedArray; - SmallSet UsedGlobals; + SmallVector UsedGlobals; auto *UsedElementType = llvm::Type::getInt8Ty(M->getContext())->getPointerTo(0); llvm::GlobalVariable *Used = From 9597eebcd9c8ddaa747bcfa6df1905625a1b5d6b Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Fri, 2 Jul 2021 12:53:16 -0700 Subject: [PATCH 043/116] Merge pull request #38230 from etcwilde/ewilde/swift-next/fix-sil-writing [Swift Next] Fix SIL writing --- lib/Serialization/SerializeSIL.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/Serialization/SerializeSIL.cpp b/lib/Serialization/SerializeSIL.cpp index ae706fa67efc3..a3c0caae82162 100644 --- a/lib/Serialization/SerializeSIL.cpp +++ b/lib/Serialization/SerializeSIL.cpp @@ -1565,8 +1565,8 @@ void SILSerializer::writeSILInstruction(const SILInstruction &SI) { Ty = cast(&SI)->getType(); break; case SILInstructionKind::FloatLiteralInst: - cast(&SI)->getValue().toString(Str, 16, - /*signed*/ true); + cast(&SI)->getBits().toString(Str, 16, + /*signed*/ true); Ty = cast(&SI)->getType(); break; } From 569e66c5188fea467ccad65738bccea304c86521 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 30 Jun 2021 13:23:06 -0700 Subject: [PATCH 044/116] Fix TargetInfo::adjust call Adjust now takes the diagnostic engine and the language options. Actually pass those in now too. --- lib/ClangImporter/ClangImporter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp index 950af90c83db5..4ba163c51de70 100644 --- a/lib/ClangImporter/ClangImporter.cpp +++ b/lib/ClangImporter/ClangImporter.cpp @@ -1170,7 +1170,7 @@ ClangImporter::create(ASTContext &ctx, // // FIXME: We shouldn't need to do this, the target should be immutable once // created. This complexity should be lifted elsewhere. - instance.getTarget().adjust(instance.getLangOpts()); + instance.getTarget().adjust(clangDiags, instance.getLangOpts()); if (importerOpts.Mode == ClangImporterOptions::Modes::EmbedBitcode) return importer; From 71129951d84896fde09176e34ffb4d5564b211e8 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Tue, 27 Jul 2021 10:07:55 -0700 Subject: [PATCH 045/116] Fix IRGenFunction.cpp's Builder.CreateAtomicCmpXchg call LLVM changed and requires an alignment argument. rdar://81060394 --- lib/IRGen/IRGenFunction.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/IRGen/IRGenFunction.cpp b/lib/IRGen/IRGenFunction.cpp index 321a2b02b83c1..c2137a443b216 100644 --- a/lib/IRGen/IRGenFunction.cpp +++ b/lib/IRGen/IRGenFunction.cpp @@ -694,7 +694,7 @@ void IRGenFunction::emitAwaitAsyncContinuation( contAwaitSyncAddr->getType()->getPointerElementType(), unsigned(ContinuationStatus::Awaited)); auto results = Builder.CreateAtomicCmpXchg( - contAwaitSyncAddr, pendingV, awaitedV, + contAwaitSyncAddr, pendingV, awaitedV, llvm::MaybeAlign(), llvm::AtomicOrdering::Release /*success ordering*/, llvm::AtomicOrdering::Acquire /* failure ordering */, llvm::SyncScope::System); From de0218bf0957af618252f52e2bc1010848cffd61 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Tue, 3 Aug 2021 12:56:15 -0700 Subject: [PATCH 046/116] Adjust to LLVM's DarwinSDKInfo.h changes --- include/swift/Basic/Platform.h | 4 +-- lib/Basic/Platform.cpp | 47 +++++++-------------------------- lib/Driver/DarwinToolChains.cpp | 4 +-- lib/Driver/ToolChains.h | 4 +-- 4 files changed, 15 insertions(+), 44 deletions(-) diff --git a/include/swift/Basic/Platform.h b/include/swift/Basic/Platform.h index a5f13d915883b..36c70baf255d0 100644 --- a/include/swift/Basic/Platform.h +++ b/include/swift/Basic/Platform.h @@ -16,7 +16,7 @@ #include "swift/Basic/LLVM.h" #include "swift/Config.h" #include "llvm/ADT/StringRef.h" -#include "clang/Driver/DarwinSDKInfo.h" +#include "clang/Basic/DarwinSDKInfo.h" namespace llvm { class Triple; @@ -104,7 +104,7 @@ namespace swift { getSwiftRuntimeCompatibilityVersionForTarget(const llvm::Triple &Triple); /// Retrieve the target SDK version for the given SDKInfo and target triple. - llvm::VersionTuple getTargetSDKVersion(clang::driver::DarwinSDKInfo &SDKInfo, + llvm::VersionTuple getTargetSDKVersion(clang::DarwinSDKInfo &SDKInfo, const llvm::Triple &triple); /// Get SDK build version. diff --git a/lib/Basic/Platform.cpp b/lib/Basic/Platform.cpp index 380b47e135526..b421e04786bed 100644 --- a/lib/Basic/Platform.cpp +++ b/lib/Basic/Platform.cpp @@ -421,44 +421,12 @@ swift::getSwiftRuntimeCompatibilityVersionForTarget( } -/// Remap the given version number via the version map, or produce \c None if -/// there is no mapping for this version. -static Optional remapVersion( - const llvm::StringMap &versionMap, - llvm::VersionTuple version) { - // The build number is never used in the lookup. - version = version.withoutBuild(); - - // Look for this specific version. - auto known = versionMap.find(version.getAsString()); - if (known != versionMap.end()) - return known->second; - - // If an extra ".0" was specified (in the subminor version), drop that - // and look again. - if (!version.getSubminor() || *version.getSubminor() != 0) - return None; - - version = llvm::VersionTuple(version.getMajor(), *version.getMinor()); - known = versionMap.find(version.getAsString()); - if (known != versionMap.end()) - return known->second; - - // If another extra ".0" wa specified (in the minor version), drop that - // and look again. - if (!version.getMinor() || *version.getMinor() != 0) - return None; - - version = llvm::VersionTuple(version.getMajor()); - known = versionMap.find(version.getAsString()); - if (known != versionMap.end()) - return known->second; - - return None; +static const llvm::VersionTuple minimumMacCatalystDeploymentTarget() { + return llvm::VersionTuple(13, 1); } llvm::VersionTuple -swift::getTargetSDKVersion(clang::driver::DarwinSDKInfo &SDKInfo, +swift::getTargetSDKVersion(clang::DarwinSDKInfo &SDKInfo, const llvm::Triple &triple) { // Retrieve the SDK version. auto SDKVersion = SDKInfo.getVersion(); @@ -467,9 +435,12 @@ swift::getTargetSDKVersion(clang::driver::DarwinSDKInfo &SDKInfo, // SDK version. Map that to the corresponding iOS version number to pass // down to the linker. if (tripleIsMacCatalystEnvironment(triple)) { - return remapVersion( - SDKInfo.getVersionMap().MacOS2iOSMacMapping, SDKVersion) - .getValueOr(llvm::VersionTuple(0, 0, 0)); + if (const auto *MacOStoMacCatalystMapping = SDKInfo.getVersionMapping( + clang::DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) { + return MacOStoMacCatalystMapping->map( + SDKVersion, minimumMacCatalystDeploymentTarget(), None).getValueOr(llvm::VersionTuple(0, 0, 0)); + } + return llvm::VersionTuple(0, 0, 0); } return SDKVersion; diff --git a/lib/Driver/DarwinToolChains.cpp b/lib/Driver/DarwinToolChains.cpp index e4047e2839ed4..b70acc53bbdc9 100644 --- a/lib/Driver/DarwinToolChains.cpp +++ b/lib/Driver/DarwinToolChains.cpp @@ -22,7 +22,7 @@ #include "swift/Basic/TaskQueue.h" #include "swift/Config.h" #include "swift/Driver/Compilation.h" -#include "clang/Driver/DarwinSDKInfo.h" +#include "clang/Basic/DarwinSDKInfo.h" #include "swift/Driver/Driver.h" #include "swift/Driver/Job.h" #include "swift/Option/Options.h" @@ -954,7 +954,7 @@ toolchains::Darwin::validateOutputInfo(DiagnosticEngine &diags, const OutputInfo &outputInfo) const { // If we have been provided with an SDK, go read the SDK information. if (!outputInfo.SDKPath.empty()) { - auto SDKInfoOrErr = clang::driver::parseDarwinSDKInfo( + auto SDKInfoOrErr = clang::parseDarwinSDKInfo( *llvm::vfs::getRealFileSystem(), outputInfo.SDKPath); if (SDKInfoOrErr) { SDKInfo = *SDKInfoOrErr; diff --git a/lib/Driver/ToolChains.h b/lib/Driver/ToolChains.h index 6421de437072d..442c555b76fea 100644 --- a/lib/Driver/ToolChains.h +++ b/lib/Driver/ToolChains.h @@ -15,7 +15,7 @@ #include "swift/Basic/LLVM.h" #include "swift/Driver/ToolChain.h" -#include "clang/Driver/DarwinSDKInfo.h" +#include "clang/Basic/DarwinSDKInfo.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/Compiler.h" @@ -81,7 +81,7 @@ class LLVM_LIBRARY_VISIBILITY Darwin : public ToolChain { /// Information about the SDK that the application is being built against. /// This information is only used by the linker, so it is only populated /// when there will be a linker job. - mutable Optional SDKInfo; + mutable Optional SDKInfo; const Optional TargetVariant; From f958804cdc4fab7bdedf690963c19c406ffd3d7f Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Tue, 3 Aug 2021 12:57:21 -0700 Subject: [PATCH 047/116] OrcRPCTargetProcessControl.h -> OrcRPCExecutorProcessControl.h --- lib/Immediate/Immediate.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Immediate/Immediate.cpp b/lib/Immediate/Immediate.cpp index 4dd5c98d4ad99..27c4632245db8 100644 --- a/lib/Immediate/Immediate.cpp +++ b/lib/Immediate/Immediate.cpp @@ -34,7 +34,7 @@ #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/LLJIT.h" #include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h" -#include "llvm/ExecutionEngine/Orc/OrcRPCTargetProcessControl.h" +#include "llvm/ExecutionEngine/Orc/OrcRPCExecutorProcessControl.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" From f1d68507f8db9ca1e16919d345f4660191f61844 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Tue, 3 Aug 2021 12:57:44 -0700 Subject: [PATCH 048/116] IRGen: Add type to gep instructions --- lib/IRGen/GenDecl.cpp | 35 +++++++++++++++++++++-------------- lib/IRGen/GenHeap.cpp | 2 +- lib/IRGen/GenKeyPath.cpp | 3 ++- lib/IRGen/GenMeta.cpp | 5 +++-- lib/IRGen/GenProto.cpp | 4 ++-- lib/IRGen/GenReflection.cpp | 3 ++- lib/IRGen/MetadataRequest.cpp | 9 ++++++--- 7 files changed, 37 insertions(+), 24 deletions(-) diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp index a2efb7d3a66d4..61dc879f03b01 100644 --- a/lib/IRGen/GenDecl.cpp +++ b/lib/IRGen/GenDecl.cpp @@ -688,13 +688,13 @@ void IRGenModule::emitRuntimeRegistration() { llvm::ConstantInt::get(Int32Ty, 0), }; auto begin = llvm::ConstantExpr::getGetElementPtr( - /*Ty=*/nullptr, protocols, beginIndices); + protocols->getType()->getPointerElementType(), protocols, beginIndices); llvm::Constant *endIndices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, SwiftProtocols.size()), }; auto end = llvm::ConstantExpr::getGetElementPtr( - /*Ty=*/nullptr, protocols, endIndices); + protocols->getType()->getPointerElementType() , protocols, endIndices); RegIGF.Builder.CreateCall(getRegisterProtocolsFn(), {begin, end}); } @@ -706,13 +706,15 @@ void IRGenModule::emitRuntimeRegistration() { llvm::ConstantInt::get(Int32Ty, 0), }; auto begin = llvm::ConstantExpr::getGetElementPtr( - /*Ty=*/nullptr, conformances, beginIndices); + conformances->getType()->getPointerElementType(), + conformances, beginIndices); llvm::Constant *endIndices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, ProtocolConformances.size()), }; auto end = llvm::ConstantExpr::getGetElementPtr( - /*Ty=*/nullptr, conformances, endIndices); + conformances->getType()->getPointerElementType(), + conformances, endIndices); RegIGF.Builder.CreateCall(getRegisterProtocolConformancesFn(), {begin, end}); } @@ -725,13 +727,13 @@ void IRGenModule::emitRuntimeRegistration() { llvm::ConstantInt::get(Int32Ty, 0), }; auto begin = llvm::ConstantExpr::getGetElementPtr( - /*Ty=*/nullptr, records, beginIndices); + records->getType()->getPointerElementType(), records, beginIndices); llvm::Constant *endIndices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, RuntimeResolvableTypes.size()), }; auto end = llvm::ConstantExpr::getGetElementPtr( - /*Ty=*/nullptr, records, endIndices); + records->getType()->getPointerElementType(), records, endIndices); RegIGF.Builder.CreateCall(getRegisterTypeMetadataRecordsFn(), {begin, end}); } @@ -1621,7 +1623,7 @@ static llvm::GlobalVariable *getChainEntryForDynamicReplacement( llvm::Constant *indices[] = {llvm::ConstantInt::get(IGM.Int32Ty, 0), llvm::ConstantInt::get(IGM.Int32Ty, 0)}; auto *storageAddr = llvm::ConstantExpr::getInBoundsGetElementPtr( - nullptr, linkEntry, indices); + linkEntry->getType()->getPointerElementType(), linkEntry, indices); bool isAsyncFunction = entity.hasSILFunction() && entity.getSILFunction()->isAsync(); auto &schema = @@ -2466,7 +2468,8 @@ Address IRGenModule::getAddrOfSILGlobalVariable(SILGlobalVariable *var, }; // Return the address of the initialized object itself (and not the address // to a reference to it). - addr = llvm::ConstantExpr::getGetElementPtr(nullptr, gvar, Indices); + addr = llvm::ConstantExpr::getGetElementPtr( + gvar->getType()->getPointerElementType(), gvar, Indices); } addr = llvm::ConstantExpr::getBitCast( addr, @@ -2600,7 +2603,8 @@ void IRGenModule::createReplaceableProlog(IRGenFunction &IGF, SILFunction *f) { llvm::ConstantInt::get(Int32Ty, 0)}; auto *fnPtrAddr = - llvm::ConstantExpr::getInBoundsGetElementPtr(nullptr, linkEntry, indices); + llvm::ConstantExpr::getInBoundsGetElementPtr( + linkEntry->getType()->getPointerElementType(), linkEntry, indices); auto *ReplAddr = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(fnPtrAddr, @@ -2815,7 +2819,8 @@ static void emitDynamicallyReplaceableThunk(IRGenModule &IGM, llvm::ConstantInt::get(IGM.Int32Ty, 0)}; auto *fnPtrAddr = - llvm::ConstantExpr::getInBoundsGetElementPtr(nullptr, linkEntry, indices); + llvm::ConstantExpr::getInBoundsGetElementPtr( + linkEntry->getType()->getPointerElementType(), linkEntry, indices); auto *fnPtr = IGF.Builder.CreateLoad(fnPtrAddr, IGM.getPointerAlignment()); auto *typeFnPtr = IGF.Builder.CreateBitOrPointerCast(fnPtr, implFn->getType()); @@ -2934,7 +2939,8 @@ void IRGenModule::emitDynamicReplacementOriginalFunctionThunk(SILFunction *f) { auto *fnPtrAddr = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( - llvm::ConstantExpr::getInBoundsGetElementPtr(nullptr, linkEntry, indices), + llvm::ConstantExpr::getInBoundsGetElementPtr( + linkEntry->getType()->getPointerElementType(), linkEntry, indices), FunctionPtrTy->getPointerTo()); auto *OrigFn = @@ -4258,8 +4264,8 @@ llvm::GlobalValue *IRGenModule::defineTypeMetadata(CanType concreteType, llvm::Constant *indices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, adjustmentIndex)}; - auto addr = llvm::ConstantExpr::getInBoundsGetElementPtr(/*Ty=*/nullptr, var, - indices); + auto addr = llvm::ConstantExpr::getInBoundsGetElementPtr( + var->getType()->getPointerElementType(), var, indices); addr = llvm::ConstantExpr::getBitCast(addr, TypeMetadataPtrTy); // For concrete metadata, declare the alias to its address point. @@ -4379,7 +4385,8 @@ IRGenModule::getAddrOfTypeMetadata(CanType concreteType, }; addr = ConstantReference( llvm::ConstantExpr::getInBoundsGetElementPtr( - /*Ty=*/nullptr, addr.getValue(), indices), + addr.getValue()->getType()->getPointerElementType(), + addr.getValue(), indices), addr.isIndirect()); } diff --git a/lib/IRGen/GenHeap.cpp b/lib/IRGen/GenHeap.cpp index f8f992452b9d6..6a596aa4cc501 100644 --- a/lib/IRGen/GenHeap.cpp +++ b/lib/IRGen/GenHeap.cpp @@ -517,7 +517,7 @@ static llvm::Constant *buildPrivateMetadata(IRGenModule &IGM, llvm::ConstantInt::get(IGM.Int32Ty, 2) }; return llvm::ConstantExpr::getInBoundsGetElementPtr( - /*Ty=*/nullptr, var, indices); + var->getType()->getPointerElementType(), var, indices); } llvm::Constant * diff --git a/lib/IRGen/GenKeyPath.cpp b/lib/IRGen/GenKeyPath.cpp index 47eac770c18ba..f571e623b21f3 100644 --- a/lib/IRGen/GenKeyPath.cpp +++ b/lib/IRGen/GenKeyPath.cpp @@ -678,7 +678,8 @@ emitMetadataTypeRefForKeyPath(IRGenModule &IGM, CanType type, // Mask the bottom bit to tell the key path runtime this is a mangled name // rather than a direct reference. auto bitConstant = llvm::ConstantInt::get(IGM.IntPtrTy, 1); - return llvm::ConstantExpr::getGetElementPtr(nullptr, constant, bitConstant); + return llvm::ConstantExpr::getGetElementPtr( + constant->getType()->getPointerElementType(), constant, bitConstant); } static unsigned getClassFieldIndex(ClassDecl *classDecl, VarDecl *property) { diff --git a/lib/IRGen/GenMeta.cpp b/lib/IRGen/GenMeta.cpp index 60cd5ae9279da..0089fada7e35f 100644 --- a/lib/IRGen/GenMeta.cpp +++ b/lib/IRGen/GenMeta.cpp @@ -847,8 +847,9 @@ namespace { B.getAddrOfCurrentPosition(IGM.ProtocolRequirementStructTy); int offset = WitnessTableFirstRequirementOffset; auto firstReqAdjustment = llvm::ConstantInt::get(IGM.Int32Ty, -offset); - address = llvm::ConstantExpr::getGetElementPtr(nullptr, address, - firstReqAdjustment); + address = llvm::ConstantExpr::getGetElementPtr( + address->getType()->getPointerElementType(), address, + firstReqAdjustment); IGM.defineProtocolRequirementsBaseDescriptor(Proto, address); } diff --git a/lib/IRGen/GenProto.cpp b/lib/IRGen/GenProto.cpp index 21efbaec2d307..97fae096349da 100644 --- a/lib/IRGen/GenProto.cpp +++ b/lib/IRGen/GenProto.cpp @@ -1498,8 +1498,8 @@ llvm::Constant *IRGenModule::getAssociatedTypeWitness(Type type, auto witness = llvm::ConstantExpr::getBitCast(typeRef, Int8PtrTy); unsigned bit = ProtocolRequirementFlags::AssociatedTypeMangledNameBit; auto bitConstant = llvm::ConstantInt::get(IntPtrTy, bit); - return llvm::ConstantExpr::getInBoundsGetElementPtr(nullptr, witness, - bitConstant); + return llvm::ConstantExpr::getInBoundsGetElementPtr( + witness->getType()->getPointerElementType(), witness, bitConstant); } static void buildAssociatedTypeValueName(CanType depAssociatedType, diff --git a/lib/IRGen/GenReflection.cpp b/lib/IRGen/GenReflection.cpp index 2a61ccb6a36ce..ba24ea5eeb22e 100644 --- a/lib/IRGen/GenReflection.cpp +++ b/lib/IRGen/GenReflection.cpp @@ -476,7 +476,8 @@ llvm::Constant *IRGenModule::getMangledAssociatedConformance( // Set the low bit. unsigned bit = ProtocolRequirementFlags::AssociatedTypeMangledNameBit; auto bitConstant = llvm::ConstantInt::get(IntPtrTy, bit); - addr = llvm::ConstantExpr::getGetElementPtr(nullptr, addr, bitConstant); + addr = llvm::ConstantExpr::getGetElementPtr( + addr->getType()->getPointerElementType(), addr, bitConstant); // Update the entry. entry = {var, addr}; diff --git a/lib/IRGen/MetadataRequest.cpp b/lib/IRGen/MetadataRequest.cpp index afef91defab51..09f4b73fd3d11 100644 --- a/lib/IRGen/MetadataRequest.cpp +++ b/lib/IRGen/MetadataRequest.cpp @@ -269,7 +269,8 @@ llvm::Constant *IRGenModule::getAddrOfStringForMetadataRef( return addr; auto bitConstant = llvm::ConstantInt::get(IntPtrTy, 1); - return llvm::ConstantExpr::getGetElementPtr(nullptr, addr, bitConstant); + return llvm::ConstantExpr::getGetElementPtr( + addr->getType()->getPointerElementType(), addr, bitConstant); }; // Check whether we already have an entry with this name. @@ -1114,7 +1115,8 @@ static llvm::Constant *emitEmptyTupleTypeMetadataRef(IRGenModule &IGM) { llvm::ConstantInt::get(IGM.Int32Ty, 1) }; return llvm::ConstantExpr::getInBoundsGetElementPtr( - /*Ty=*/nullptr, fullMetadata, indices); + fullMetadata->getType()->getPointerElementType(), fullMetadata, + indices); } using GetElementMetadataFn = @@ -1661,7 +1663,8 @@ namespace { }; return MetadataResponse::forComplete( llvm::ConstantExpr::getInBoundsGetElementPtr( - /*Ty=*/nullptr, singletonMetadata, indices)); + singletonMetadata->getType()->getPointerElementType(), + singletonMetadata, indices)); } auto layout = type.getExistentialLayout(); From b5a5d387568f62e84c89c7acb90482c3b2dd3a5d Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Tue, 3 Aug 2021 12:58:50 -0700 Subject: [PATCH 049/116] Adjust to LLVM's llvm_execute_on_thread removal --- tools/SourceKit/lib/Support/Concurrency-libdispatch.cpp | 6 ++++-- tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/tools/SourceKit/lib/Support/Concurrency-libdispatch.cpp b/tools/SourceKit/lib/Support/Concurrency-libdispatch.cpp index 6ff46f9ba530c..b158e66ce989f 100644 --- a/tools/SourceKit/lib/Support/Concurrency-libdispatch.cpp +++ b/tools/SourceKit/lib/Support/Concurrency-libdispatch.cpp @@ -14,7 +14,7 @@ #include "SourceKit/Config/config.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/Threading.h" +#include "llvm/Support/thread.h" #include #include @@ -104,7 +104,9 @@ static void executeBlock(void *Data) { static void executeOnLargeStackThread(void *Data) { static const size_t ThreadStackSize = 8 << 20; // 8 MB. - llvm::llvm_execute_on_thread(executeBlock, Data, ThreadStackSize); + llvm::thread Thread(llvm::Optional(ThreadStackSize), + executeBlock, Data); + Thread.join(); } static std::pair diff --git a/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp b/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp index 5838d04b46c6b..67fb882de48e1 100644 --- a/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp +++ b/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp @@ -29,7 +29,7 @@ #include "llvm/Support/Program.h" #include "llvm/Support/Regex.h" #include "llvm/Support/Signals.h" -#include "llvm/Support/Threading.h" +#include "llvm/Support/thread.h" #include "llvm/Support/raw_ostream.h" #include #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) @@ -206,7 +206,9 @@ static void skt_main(skt_args *args); int main(int argc, const char **argv) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ skt_args args = {argc, argv, 0}; - llvm::llvm_execute_on_thread((void (*)(void *))skt_main, &args); + llvm::thread Thread(llvm::thread::DefaultStackSize, + skt_main, &args); + Thread.join(); exit(args.ret); }); From aeff1080723067a29e640057b0ab1758f054a08a Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Tue, 3 Aug 2021 12:59:12 -0700 Subject: [PATCH 050/116] TYPED_TEST_CASE -> TYPED_TEST_SUITE --- unittests/Basic/BlotMapVectorTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/unittests/Basic/BlotMapVectorTest.cpp b/unittests/Basic/BlotMapVectorTest.cpp index ce0acb85857a5..2ccfd4654ef51 100644 --- a/unittests/Basic/BlotMapVectorTest.cpp +++ b/unittests/Basic/BlotMapVectorTest.cpp @@ -367,7 +367,7 @@ typedef ::testing::Types< CtorTester, CtorTester, 4, llvm::SmallDenseMap>> BlotMapVectorTestTypes; -TYPED_TEST_CASE(BlotMapVectorTest, BlotMapVectorTestTypes); +TYPED_TEST_SUITE(BlotMapVectorTest, BlotMapVectorTestTypes, ); // Empty map tests TYPED_TEST(BlotMapVectorTest, EmptyIntMapTest) { From 076150f5687ea4963db4c8f3203fdc33e9409206 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Tue, 3 Aug 2021 12:59:32 -0700 Subject: [PATCH 051/116] Fix IRGen tests --- test/IRGen/newtype.swift | 6 ++---- test/IRGen/object_type.swift | 2 +- test/IRGen/undef.sil | 6 +++--- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/test/IRGen/newtype.swift b/test/IRGen/newtype.swift index c913c9593e26c..35e092fa970fd 100644 --- a/test/IRGen/newtype.swift +++ b/test/IRGen/newtype.swift @@ -129,11 +129,9 @@ class ObjCTest { // CHECK: {{^}$}} // OPT-LABEL: define hidden %0* @"$s7newtype8ObjCTestC19optionalPassThroughySo14SNTErrorDomainaSgAGFTo" - // OPT: [[ARG_CASTED:%.*]] = bitcast %0* %2 to %objc_object* - // OPT: [[ARG_RECASTED:%.*]] = bitcast %objc_object* [[ARG_CASTED]] to i8* // OPT: [[ARG_CASTED2:%.*]] = bitcast %0* %2 to i8* - // OPT: tail call i8* @llvm.objc.retainAutoreleaseReturnValue(i8* [[ARG_RECASTED]]) - // OPT: [[CAST_FOR_RETURN:%.*]] = bitcast i8* [[ARG_CASTED2]] to %0* + // OPT: [[RES:%.*]] = tail call i8* @llvm.objc.retainAutoreleaseReturnValue(i8* [[ARG_CASTED2]]) + // OPT: [[CAST_FOR_RETURN:%.*]] = bitcast i8* [[RES]] to %0* // OPT: ret %0* [[CAST_FOR_RETURN]] // OPT: {{^}$}} @objc func optionalPassThrough(_ ed: ErrorDomain?) -> ErrorDomain? { diff --git a/test/IRGen/object_type.swift b/test/IRGen/object_type.swift index 15a1c8ed041b9..36697cbecb265 100644 --- a/test/IRGen/object_type.swift +++ b/test/IRGen/object_type.swift @@ -34,7 +34,7 @@ func work() { } // CHECK-IR: call {{.*}} @swift_getObjectType({{.*}}) #[[M:[0-9]]] -// CHECK-IR: declare {{.*}} @swift_getObjectType{{.*}} #[[M]] +// CHECK-IR: declare {{.*}} @swift_getObjectType{{.*}} local_unnamed_addr #[[M]] // CHECK-IR: attributes #[[M]] = { nounwind readonly } // CHECK: okay diff --git a/test/IRGen/undef.sil b/test/IRGen/undef.sil index f5b234e5c6bc1..d66d1c882453d 100644 --- a/test/IRGen/undef.sil +++ b/test/IRGen/undef.sil @@ -6,9 +6,9 @@ import Builtin // CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @undefined() {{.*}} { // CHECK: entry: -// CHECK: store i64 undef, i64* undef, align 8 -// CHECK: store i8 undef, i8* undef, align 8 -// CHECK: store i8* undef, i8** undef, align 8 +// CHECK: store i64 undef, i64* poison, align 8 +// CHECK: store i8 undef, i8* poison, align 8 +// CHECK: store i8* undef, i8** poison, align 8 // CHECK: ret void // CHECK: } sil @undefined : $() -> () { From 8a0eb42a3420cac1d590ae4b80490ea23bae6dfe Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Tue, 3 Aug 2021 12:59:51 -0700 Subject: [PATCH 052/116] Add --allow-unused-prefixes to FileCheck --- test/lit.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/lit.cfg b/test/lit.cfg index 2564b12a4ff37..566d33fa037e9 100644 --- a/test/lit.cfg +++ b/test/lit.cfg @@ -2179,7 +2179,7 @@ if hasattr(config, 'target_link_sdk_future_version'): config.substitutions.append(('%target-link-sdk-future-version', config.target_link_sdk_future_version)) -run_filecheck = '%s %s --sanitize BUILD_DIR=%s --sanitize SOURCE_DIR=%s --use-filecheck %s %s' % ( +run_filecheck = '%s %s --allow-unused-prefixes --sanitize BUILD_DIR=%s --sanitize SOURCE_DIR=%s --use-filecheck %s %s' % ( shell_quote(sys.executable), shell_quote(config.PathSanitizingFileCheck), # LLVM Lit performs realpath with the config path, so all paths are relative From a202c8fc720c2334240636f168c9850f7757cd6f Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Wed, 4 Aug 2021 07:11:16 -0700 Subject: [PATCH 053/116] Fix swift_symbolgraph_extract_main.cpp SmallVector --- lib/DriverTool/swift_symbolgraph_extract_main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/DriverTool/swift_symbolgraph_extract_main.cpp b/lib/DriverTool/swift_symbolgraph_extract_main.cpp index 29cb48ef6db4e..36451d9020a61 100644 --- a/lib/DriverTool/swift_symbolgraph_extract_main.cpp +++ b/lib/DriverTool/swift_symbolgraph_extract_main.cpp @@ -235,7 +235,7 @@ int swift_symbolgraph_extract_main(ArrayRef Args, // don't need to print these errors. CI.removeDiagnosticConsumer(&DiagPrinter); - SmallVector Overlays; + SmallVector Overlays; M->findDeclaredCrossImportOverlaysTransitive(Overlays); for (const auto *OM : Overlays) { auto CIM = CI.getASTContext().getModuleByName(OM->getNameStr()); From c288cbb6ab095ee42edef81ba18f71c5457d8fb1 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Wed, 4 Aug 2021 08:38:25 -0700 Subject: [PATCH 054/116] Fix some more SmallVector usage without an on stack size --- lib/SILOptimizer/Transforms/SILMem2Reg.cpp | 2 +- lib/Serialization/Deserialization.cpp | 2 +- tools/swift-refactor/swift-refactor.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/SILOptimizer/Transforms/SILMem2Reg.cpp b/lib/SILOptimizer/Transforms/SILMem2Reg.cpp index ed69a84584358..b1bd619791773 100644 --- a/lib/SILOptimizer/Transforms/SILMem2Reg.cpp +++ b/lib/SILOptimizer/Transforms/SILMem2Reg.cpp @@ -574,7 +574,7 @@ void StackAllocationPromoter::propagateLiveness( // If liveness has not been propagated, go over the incoming operands and mark // any operand values that are proactivePhis as live livePhis.insert(proactivePhi); - SmallVector incomingPhiVals; + SmallVector incomingPhiVals; proactivePhi->getIncomingPhiValues(incomingPhiVals); for (auto &inVal : incomingPhiVals) { auto *inPhi = dyn_cast(inVal); diff --git a/lib/Serialization/Deserialization.cpp b/lib/Serialization/Deserialization.cpp index ba3a897e1124f..4b13c0d9d1760 100644 --- a/lib/Serialization/Deserialization.cpp +++ b/lib/Serialization/Deserialization.cpp @@ -1550,7 +1550,7 @@ ModuleFile::resolveCrossReference(ModuleID MID, uint32_t pathLen) { // Look for types and value decls in other modules. This extra information // is mostly for compiler engineers to understand a likely solution at a // quick glance. - SmallVector strScratch; + SmallVector strScratch; SmallVector notes; auto declName = getXRefDeclNameForError(); if (recordID == XREF_TYPE_PATH_PIECE || diff --git a/tools/swift-refactor/swift-refactor.cpp b/tools/swift-refactor/swift-refactor.cpp index f86930e4220ba..0ef3c3587fe9d 100644 --- a/tools/swift-refactor/swift-refactor.cpp +++ b/tools/swift-refactor/swift-refactor.cpp @@ -425,7 +425,7 @@ int main(int argc, char *argv[]) { return 1; } - SmallVector> Consumers; + SmallVector, 32> Consumers; if (!options::RewrittenOutputFile.empty() || options::DumpIn == options::DumpType::REWRITTEN) { Consumers.emplace_back(new SourceEditOutputConsumer( From c8aa5d5f1753d27a8dc572cb7fa117c1ddbae643 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Wed, 4 Aug 2021 09:06:10 -0700 Subject: [PATCH 055/116] Fix test/IRGen/object_type.swift --- test/IRGen/object_type.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/IRGen/object_type.swift b/test/IRGen/object_type.swift index 36697cbecb265..af5993360580b 100644 --- a/test/IRGen/object_type.swift +++ b/test/IRGen/object_type.swift @@ -33,8 +33,9 @@ func work() { myProtocolType.printit() } -// CHECK-IR: call {{.*}} @swift_getObjectType({{.*}}) #[[M:[0-9]]] -// CHECK-IR: declare {{.*}} @swift_getObjectType{{.*}} local_unnamed_addr #[[M]] +// CHECK-IR: call {{.*}} @swift_getObjectType({{.*}}) #[[M:[0-9]+]] +// CHECK-IR: declare {{.*}} @swift_getObjectType{{.*}} local_unnamed_addr #[[N:[0-9]+]] +// CHECK-IR: attributes #[[N]] = { nofree nounwind readonly } // CHECK-IR: attributes #[[M]] = { nounwind readonly } // CHECK: okay From a45e11622142153a0d113dc2c3c13bfc010313a3 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Wed, 4 Aug 2021 09:13:33 -0700 Subject: [PATCH 056/116] Fix test/ClangImporter/CoreGraphics_test.swift --- test/ClangImporter/CoreGraphics_test.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/ClangImporter/CoreGraphics_test.swift b/test/ClangImporter/CoreGraphics_test.swift index f0490eb5c3a1e..a48322867d61b 100644 --- a/test/ClangImporter/CoreGraphics_test.swift +++ b/test/ClangImporter/CoreGraphics_test.swift @@ -24,7 +24,8 @@ public func testEnums(_ model: CGColorSpaceModel) -> Int { } // CHECK: [[GEP:%.+]] = getelementptr inbounds [8 x i64], [8 x i64]* [[SWITCHTABLE]], i64 0, i64 %{{.*}} // CHECK: [[LOAD:%.+]] = load i64, i64* [[GEP]], align 8 -// CHECK: ret i64 [[LOAD]] +// CHECK: [[PHI:%.*]] = phi i64 [ [[LOAD]], %{{.*}} ], [ -1, %{{.*}} ] +// CHECK: ret i64 [[PHI]] } // CHECK-LABEL: define swiftcc void {{.*}}rotationAround{{.*}} { From a9b6c0f2ef11773241f7663407873ef063629bc7 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Wed, 4 Aug 2021 10:26:42 -0700 Subject: [PATCH 057/116] Fix emit-called-inline-function-irgen.swift test --- test/Interop/C/function/emit-called-inline-function-irgen.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Interop/C/function/emit-called-inline-function-irgen.swift b/test/Interop/C/function/emit-called-inline-function-irgen.swift index a0bee81c63c54..fa8d395f53925 100644 --- a/test/Interop/C/function/emit-called-inline-function-irgen.swift +++ b/test/Interop/C/function/emit-called-inline-function-irgen.swift @@ -15,7 +15,7 @@ import EmitCalledInlineFunction // CXX-DAG: define linkonce_odr{{( dso_local)?}} i32 @{{_Z15calledFromSwiftv|"\?calledFromSwift@@YAHXZ"}}() // CXX-DAG: define linkonce_odr{{( dso_local)?}} i32 @{{_Z18calledTransitivelyv|"\?calledTransitively@@YAHXZ"}}() -// CXX-DAG: define linkonce_odr{{( dso_local)?}} i32 @{{_ZN1C32memberFunctionCalledTransitivelyEv|"\?memberFunctionCalledTransitively@C@@QEAAHXZ"}}(%class.C* nonnull dereferenceable(1) %this) +// CXX-DAG: define linkonce_odr{{( dso_local)?}} i32 @{{_ZN1C32memberFunctionCalledTransitivelyEv|"\?memberFunctionCalledTransitively@C@@QEAAHXZ"}}(%class.C* nonnull align 1 dereferenceable(1) %this) // CXX-DAG: define linkonce_odr{{( dso_local)?}} i32 @{{_Z29calledTransitivelyFromVarInitv|"\?calledTransitivelyFromVarInit@@YAHXZ"}}() calledFromSwift() From ee6441c4d217212a1e06131b67861b7cca6b1060 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Wed, 4 Aug 2021 10:50:51 -0700 Subject: [PATCH 058/116] Fix test/Interop/Cxx --- test/Interop/Cxx/class/constructors-irgen.swift | 6 +++--- .../constructor-calls-method-irgen.swift | 2 +- ...ethod-calls-method-from-nested-struct-irgen.swift | 2 +- .../method-calls-method-irgen.swift | 2 +- test/Interop/Cxx/operators/member-inline-irgen.swift | 12 ++++++------ .../Cxx/operators/member-out-of-line-irgen.swift | 2 +- test/Interop/Cxx/static/static-var-irgen.swift | 4 ++-- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/test/Interop/Cxx/class/constructors-irgen.swift b/test/Interop/Cxx/class/constructors-irgen.swift index 85f2603feae42..7888cdde9832e 100644 --- a/test/Interop/Cxx/class/constructors-irgen.swift +++ b/test/Interop/Cxx/class/constructors-irgen.swift @@ -99,7 +99,7 @@ public func createTemplatedConstructor() { // ITANIUM_X64: call void @_ZN20TemplatedConstructorC1I7ArgTypeEET_(%struct.TemplatedConstructor* [[OBJ_AS_STRUCT]], i32 [[IVAL]]) // ITANIUM_X64: ret void - // ITANIUM_X64-LABEL: define linkonce_odr void @_ZN20TemplatedConstructorC1I7ArgTypeEET_(%struct.TemplatedConstructor* nonnull dereferenceable(4) {{.*}}, i32 {{.*}}) + // ITANIUM_X64-LABEL: define linkonce_odr void @_ZN20TemplatedConstructorC1I7ArgTypeEET_(%struct.TemplatedConstructor* nonnull align 4 dereferenceable(4) {{.*}}, i32 {{.*}}) // ITANIUM_ARM-LABEL: define protected swiftcc void @"$ss26createTemplatedConstructoryyF"() // ITANIUM_ARM: [[OBJ:%.*]] = alloca %TSo20TemplatedConstructorV @@ -108,7 +108,7 @@ public func createTemplatedConstructor() { // ITANIUM_ARM: call %struct.TemplatedConstructor* @_ZN20TemplatedConstructorC2I7ArgTypeEET_(%struct.TemplatedConstructor* [[OBJ_AS_STRUCT]], [1 x i32] [[IVAL]]) // ITANIUM_ARM: ret void - // ITANIUM_ARM-LABEL: define linkonce_odr %struct.TemplatedConstructor* @_ZN20TemplatedConstructorC2I7ArgTypeEET_(%struct.TemplatedConstructor* nonnull returned dereferenceable(4) {{.*}}, [1 x i32] {{.*}}) + // ITANIUM_ARM-LABEL: define linkonce_odr %struct.TemplatedConstructor* @_ZN20TemplatedConstructorC2I7ArgTypeEET_(%struct.TemplatedConstructor* nonnull returned align 4 dereferenceable(4) {{.*}}, [1 x i32] {{.*}}) // MICROSOFT_X64-LABEL: define dllexport swiftcc void @"$ss26createTemplatedConstructoryyF"() // MICROSOFT_X64: [[OBJ:%.*]] = alloca %TSo20TemplatedConstructorV @@ -117,6 +117,6 @@ public func createTemplatedConstructor() { // MICROSOFT_X64: call %struct.TemplatedConstructor* @"??$?0UArgType@@@TemplatedConstructor@@QEAA@UArgType@@@Z"(%struct.TemplatedConstructor* [[OBJ_AS_STRUCT]], i32 [[IVAL]]) // MICROSOFT_X64: ret void - // MICROSOFT_X64-LABEL: define linkonce_odr dso_local %struct.TemplatedConstructor* @"??$?0UArgType@@@TemplatedConstructor@@QEAA@UArgType@@@Z"(%struct.TemplatedConstructor* nonnull returned dereferenceable(4) {{.*}}, i32 {{.*}}) + // MICROSOFT_X64-LABEL: define linkonce_odr dso_local %struct.TemplatedConstructor* @"??$?0UArgType@@@TemplatedConstructor@@QEAA@UArgType@@@Z"(%struct.TemplatedConstructor* nonnull returned align 4 dereferenceable(4) {{.*}}, i32 {{.*}}) let templated = TemplatedConstructor(ArgType()) } diff --git a/test/Interop/Cxx/class/inline-function-codegen/constructor-calls-method-irgen.swift b/test/Interop/Cxx/class/inline-function-codegen/constructor-calls-method-irgen.swift index 853cfa4319056..3cc710101a1ce 100644 --- a/test/Interop/Cxx/class/inline-function-codegen/constructor-calls-method-irgen.swift +++ b/test/Interop/Cxx/class/inline-function-codegen/constructor-calls-method-irgen.swift @@ -6,4 +6,4 @@ public func getIncrementorValue() -> CInt { return callConstructor(41) } -// CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_ZN11Incrementor9incrementEi|"\?increment@Incrementor@@QEAAHH@Z"}}(%struct.Incrementor* nonnull dereferenceable(1) %this, i32 %t) +// CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_ZN11Incrementor9incrementEi|"\?increment@Incrementor@@QEAAHH@Z"}}(%struct.Incrementor* nonnull align 1 dereferenceable(1) %this, i32 %t) diff --git a/test/Interop/Cxx/class/inline-function-codegen/method-calls-method-from-nested-struct-irgen.swift b/test/Interop/Cxx/class/inline-function-codegen/method-calls-method-from-nested-struct-irgen.swift index e79a1832753a0..391c6050f233e 100644 --- a/test/Interop/Cxx/class/inline-function-codegen/method-calls-method-from-nested-struct-irgen.swift +++ b/test/Interop/Cxx/class/inline-function-codegen/method-calls-method-from-nested-struct-irgen.swift @@ -6,4 +6,4 @@ public func getValueFromMethod() -> CInt { return callMethod(41) } -// CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_ZN13IncrementUser11Incrementor9incrementEi|"\?increment@Incrementor@IncrementUser@@QEAAHH@Z"}}(%"struct.IncrementUser::Incrementor"* nonnull dereferenceable(1) %this, i32 %t) +// CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_ZN13IncrementUser11Incrementor9incrementEi|"\?increment@Incrementor@IncrementUser@@QEAAHH@Z"}}(%"struct.IncrementUser::Incrementor"* nonnull align 1 dereferenceable(1) %this, i32 %t) diff --git a/test/Interop/Cxx/class/inline-function-codegen/method-calls-method-irgen.swift b/test/Interop/Cxx/class/inline-function-codegen/method-calls-method-irgen.swift index 768e2175fa959..44f8b7c04173b 100644 --- a/test/Interop/Cxx/class/inline-function-codegen/method-calls-method-irgen.swift +++ b/test/Interop/Cxx/class/inline-function-codegen/method-calls-method-irgen.swift @@ -6,4 +6,4 @@ public func getValueFromMethod() -> CInt { return callMethod(41) } -// CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_ZN11Incrementor9incrementEi|"\?increment@Incrementor@@QEAAHH@Z"}}(%struct.Incrementor* nonnull dereferenceable(1) %this, i32 %t) +// CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_ZN11Incrementor9incrementEi|"\?increment@Incrementor@@QEAAHH@Z"}}(%struct.Incrementor* nonnull align 1 dereferenceable(1) %this, i32 %t) diff --git a/test/Interop/Cxx/operators/member-inline-irgen.swift b/test/Interop/Cxx/operators/member-inline-irgen.swift index f738a5a264b9f..2e0bb83875507 100644 --- a/test/Interop/Cxx/operators/member-inline-irgen.swift +++ b/test/Interop/Cxx/operators/member-inline-irgen.swift @@ -8,22 +8,22 @@ import MemberInline public func sub(_ lhs: inout LoadableIntWrapper, _ rhs: LoadableIntWrapper) -> LoadableIntWrapper { lhs - rhs } // CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN18LoadableIntWrappermiES_|"\?\?GLoadableIntWrapper@@QEAA\?AU0@U0@@Z")]](%struct.LoadableIntWrapper* {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\) align 4}} {{%[0-9]+}}) -// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.LoadableIntWrapper* nonnull dereferenceable(4) {{.*}}, {{i32 %.*.coerce|\[1 x i32\] %.*.coerce|i64 %.*.coerce|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\) align 4 %.*}}) +// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.LoadableIntWrapper* nonnull align 4 dereferenceable(4) {{.*}}, {{i32 %.*.coerce|\[1 x i32\] %.*.coerce|i64 %.*.coerce|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\) align 4 %.*}}) public func call(_ wrapper: inout LoadableIntWrapper, _ arg: Int32) -> Int32 { wrapper(arg) } // CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN18LoadableIntWrapperclEi|"\?\?GLoadableIntWrapper@@QEAAHH@Z")]](%struct.LoadableIntWrapper* {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\) align 4}} {{%[0-9]+}}) -// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.LoadableIntWrapper* nonnull dereferenceable(4) {{.*}}, {{i32 %.*|\[1 x i32\] %.*|i64 %.*|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\) align 4 %.*}}) +// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.LoadableIntWrapper* nonnull align 4 dereferenceable(4) {{.*}}, {{i32 %.*|\[1 x i32\] %.*|i64 %.*|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\) align 4 %.*}}) public func call(_ wrapper: inout AddressOnlyIntWrapper) -> Int32 { wrapper() } // CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN21AddressOnlyIntWrapperclEv|"\?\?GAddressOnlyIntWrapper@@QEAAHXZ")]](%struct.AddressOnlyIntWrapper* {{%[0-9]+}}) -// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.AddressOnlyIntWrapper* nonnull dereferenceable(4) {{.*}}) +// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.AddressOnlyIntWrapper* nonnull align 4 dereferenceable(4) {{.*}}) public func index(_ arr: inout ReadOnlyIntArray, _ arg: Int32) -> Int32 { arr[arg] } // CHECK: call [[RES:i32|i64]]* [[NAME:@(_ZNK16ReadOnlyIntArrayixEi|"\?\?AReadOnlyIntArray@@QEBAAEBHH@Z")]](%struct.ReadOnlyIntArray* {{%[0-9]+}}, {{i32|i64}} {{%[0-9]+}}) -// CHECK: define linkonce_odr nonnull align 4 dereferenceable(4) [[RES]]* [[NAME]](%struct.ReadOnlyIntArray* nonnull dereferenceable(20) {{.*}}, {{i32 %.*|\[1 x i32\] %.*|i64 %.*|%struct.ReadOnlyIntArray\* byval\(%struct.ReadOnlyIntArray\) align 2 %.*}}) +// CHECK: define linkonce_odr nonnull align 4 dereferenceable(4) [[RES]]* [[NAME]](%struct.ReadOnlyIntArray* nonnull align 4 dereferenceable(20) {{.*}}, {{i32 %.*|\[1 x i32\] %.*|i64 %.*|%struct.ReadOnlyIntArray\* byval\(%struct.ReadOnlyIntArray\) align 2 %.*}}) // CHECK: [[THIS:%.*]] = load %struct.ReadOnlyIntArray*, %struct.ReadOnlyIntArray** // CHECK: [[VALUES:%.*]] = getelementptr inbounds %struct.ReadOnlyIntArray, %struct.ReadOnlyIntArray* [[THIS]] // CHECK: [[VALUE:%.*]] = getelementptr inbounds [5 x {{i32|i64}}], [5 x {{i32|i64}}]* [[VALUES]] @@ -32,7 +32,7 @@ public func index(_ arr: inout ReadOnlyIntArray, _ arg: Int32) -> Int32 { arr[ar public func index(_ arr: inout ReadWriteIntArray, _ arg: Int32, _ val: Int32) { arr[arg] = val } // CHECK: call [[RES:i32|i64]]* [[NAME:@(_ZN17ReadWriteIntArrayixEi|"\?\?AReadWriteIntArray@@QEAAAEAHH@Z")]](%struct.ReadWriteIntArray* {{%[0-9]+}}, {{i32|i64}} {{%[0-9]+}}) -// CHECK: define linkonce_odr nonnull align 4 dereferenceable(4) [[RES]]* [[NAME]](%struct.ReadWriteIntArray* nonnull dereferenceable(20) {{.*}}, {{i32 %.*|\[1 x i32\] %.*|i64 %.*|%struct.ReadWriteIntArray\* byval\(%struct.ReadWriteIntArray\) align 2 %.*}}) +// CHECK: define linkonce_odr nonnull align 4 dereferenceable(4) [[RES]]* [[NAME]](%struct.ReadWriteIntArray* nonnull align 4 dereferenceable(20) {{.*}}, {{i32 %.*|\[1 x i32\] %.*|i64 %.*|%struct.ReadWriteIntArray\* byval\(%struct.ReadWriteIntArray\) align 2 %.*}}) // CHECK: [[THIS:%.*]] = load %struct.ReadWriteIntArray*, %struct.ReadWriteIntArray** // CHECK: [[VALUES:%.*]] = getelementptr inbounds %struct.ReadWriteIntArray, %struct.ReadWriteIntArray* [[THIS]] // CHECK: [[VALUE:%.*]] = getelementptr inbounds [5 x {{i32|i64}}], [5 x {{i32|i64}}]* [[VALUES]] @@ -41,7 +41,7 @@ public func index(_ arr: inout ReadWriteIntArray, _ arg: Int32, _ val: Int32) { public func index(_ arr: inout NonTrivialIntArrayByVal, _ arg: Int32) -> Int32 { arr[arg] } // CHECK: call [[RES:i32|i64]] [[NAME:@(_ZNK23NonTrivialIntArrayByValixEi|"\?\?ANonTrivialIntArrayByVal@@QEBAAEBHH@Z")]](%struct.NonTrivialIntArrayByVal* {{%[0-9]+}}, {{i32|i64}} {{%[0-9]+}}) -// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.NonTrivialIntArrayByVal* nonnull dereferenceable(20) {{.*}}, {{i32 %.*|\[1 x i32\] %.*|i64 %.*|%struct.NonTrivialIntArrayByVal\* byval\(%struct.NonTrivialIntArrayByVal\) align 2 %.*}}) +// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.NonTrivialIntArrayByVal* nonnull align 4 dereferenceable(20) {{.*}}, {{i32 %.*|\[1 x i32\] %.*|i64 %.*|%struct.NonTrivialIntArrayByVal\* byval\(%struct.NonTrivialIntArrayByVal\) align 2 %.*}}) // CHECK: [[THIS:%.*]] = load %struct.NonTrivialIntArrayByVal*, %struct.NonTrivialIntArrayByVal** // CHECK: [[VALUES:%.*]] = getelementptr inbounds %struct.NonTrivialIntArrayByVal, %struct.NonTrivialIntArrayByVal* [[THIS]] // CHECK: [[VALUE:%.*]] = getelementptr inbounds [5 x {{i32|i64}}], [5 x {{i32|i64}}]* [[VALUES]] diff --git a/test/Interop/Cxx/operators/member-out-of-line-irgen.swift b/test/Interop/Cxx/operators/member-out-of-line-irgen.swift index 75bb3fbab4122..83e7b58fac963 100644 --- a/test/Interop/Cxx/operators/member-out-of-line-irgen.swift +++ b/test/Interop/Cxx/operators/member-out-of-line-irgen.swift @@ -8,4 +8,4 @@ import MemberOutOfLine public func add(_ lhs: inout LoadableIntWrapper, _ rhs: LoadableIntWrapper) -> LoadableIntWrapper { lhs + rhs } // CHECK: call {{i32|i64}} [[NAME:@_ZNK18LoadableIntWrapperplES_]](%struct.LoadableIntWrapper* %{{[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\) align 4}} %{{[0-9]+}}) -// CHECK: declare {{(dso_local )?}}{{i32|i64}} [[NAME]](%struct.LoadableIntWrapper* nonnull dereferenceable(4), {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\) align 4}}) +// CHECK: declare {{(dso_local )?}}{{i32|i64}} [[NAME]](%struct.LoadableIntWrapper* nonnull align 4 dereferenceable(4), {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\) align 4}}) diff --git a/test/Interop/Cxx/static/static-var-irgen.swift b/test/Interop/Cxx/static/static-var-irgen.swift index 0166214effcf4..1cdada69e85b3 100644 --- a/test/Interop/Cxx/static/static-var-irgen.swift +++ b/test/Interop/Cxx/static/static-var-irgen.swift @@ -49,10 +49,10 @@ public func initStaticVars() -> CInt { // CHECK: ret i32 16 // CHECK: define internal void @{{__cxx_global_var_init.4|"\?\?__EstaticNonTrivial@@YAXXZ"}}() -// CHECK: call {{void|%class.NonTrivial\*}} {{@_ZN10NonTrivialC[12]Ei\(%class.NonTrivial\* nonnull dereferenceable\(4\) @_ZL16staticNonTrivial, i32 1024\)|@"\?\?0NonTrivial@@QEAA@H@Z"\(%class.NonTrivial\* nonnull dereferenceable\(4\) @staticNonTrivial, i32 1024\)}} +// CHECK: call {{void|%class.NonTrivial\*}} {{@_ZN10NonTrivialC[12]Ei\(%class.NonTrivial\* nonnull align 4 dereferenceable\(4\) @_ZL16staticNonTrivial, i32 1024\)|@"\?\?0NonTrivial@@QEAA@H@Z"\(%class.NonTrivial\* nonnull align 4 dereferenceable\(4\) @staticNonTrivial, i32 1024\)}} // CHECK: define internal void @{{__cxx_global_var_init.5|"\?\?__EstaticConstNonTrivial@@YAXXZ"}}() -// CHECK: call {{void|%class.NonTrivial\*}} {{@_ZN10NonTrivialC[12]Ei\(%class.NonTrivial\* nonnull dereferenceable\(4\) @_ZL21staticConstNonTrivial, i32 2048\)|@"\?\?0NonTrivial@@QEAA@H@Z"\(%class.NonTrivial\* nonnull dereferenceable\(4\) @staticConstNonTrivial, i32 2048\)}} +// CHECK: call {{void|%class.NonTrivial\*}} {{@_ZN10NonTrivialC[12]Ei\(%class.NonTrivial\* nonnull align 4 dereferenceable\(4\) @_ZL21staticConstNonTrivial, i32 2048\)|@"\?\?0NonTrivial@@QEAA@H@Z"\(%class.NonTrivial\* nonnull align 4 dereferenceable\(4\) @staticConstNonTrivial, i32 2048\)}} public func readStaticVar() -> CInt { return staticVar From 63bd700d70896b119fe637de2d051eafbb1414bf Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 13 Aug 2021 14:31:38 -0700 Subject: [PATCH 059/116] Updated async debug info tests for upstream IR changes --- lib/IRGen/IRGenSIL.cpp | 3 --- test/DebugInfo/async-args.swift | 15 +++++++-------- test/DebugInfo/async-let-await.swift | 2 +- test/DebugInfo/async-lifetime-extension.swift | 8 ++++---- 4 files changed, 12 insertions(+), 16 deletions(-) diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp index 2eaea7349f480..18c4496f5a3b5 100644 --- a/lib/IRGen/IRGenSIL.cpp +++ b/lib/IRGen/IRGenSIL.cpp @@ -952,9 +952,6 @@ class IRGenSILFunction : if (ValueVariables.insert(shadow).second) ValueDomPoints.push_back({shadow, getActiveDominancePoint()}); } - auto inst = cast(shadow); - llvm::IRBuilder<> builder(inst->getNextNode()); - shadow = builder.CreateLoad(shadow); } return shadow; diff --git a/test/DebugInfo/async-args.swift b/test/DebugInfo/async-args.swift index dd41325c8cda8..a67a25ec4e4b0 100644 --- a/test/DebugInfo/async-args.swift +++ b/test/DebugInfo/async-args.swift @@ -10,17 +10,15 @@ func withGenericArg(_ msg: T) async { // This odd debug info is part of a contract with CoroSplit/CoroFrame to fix // this up after coroutine splitting. // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYalF"(%swift.context* swiftasync %0 - // CHECK: call void @llvm.dbg.declare(metadata %swift.context* %0, - // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression( - // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) - // CHECK: call void @llvm.dbg.declare(metadata %swift.context* %0, - // CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression( - // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}})) + // CHECK: call void @llvm.dbg.declare(metadata %swift.type** % + // CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression() + // CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** % + // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression(DW_OP_deref)) await forceSplit() // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYalFTQ0_"(i8* swiftasync %0) // CHECK: call void @llvm.dbg.declare(metadata i8* %0, - // CHECK-SAME: metadata ![[MSG_R:[0-9]+]], metadata !DIExpression(DW_OP_deref, + // CHECK-SAME: metadata ![[MSG_R:[0-9]+]], metadata !DIExpression( // CHECK-SAME: DW_OP_plus_uconst, [[OFFSET:[0-9]+]], // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) // CHECK: call void @llvm.dbg.declare(metadata i8* %0, @@ -35,7 +33,8 @@ func withGenericArg(_ msg: T) async { await withGenericArg("hello (asynchronously)") } } -// CHECK: ![[MSG]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[TAU]] = !DILocalVariable(name: "$\CF\84_0_0", +// CHECK: ![[MSG]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[MSG_R]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[TAU_R]] = !DILocalVariable(name: "$\CF\84_0_0", + diff --git a/test/DebugInfo/async-let-await.swift b/test/DebugInfo/async-let-await.swift index 37450e90685b1..15a85e1b61568 100644 --- a/test/DebugInfo/async-let-await.swift +++ b/test/DebugInfo/async-let-await.swift @@ -11,7 +11,7 @@ public func getVegetables() async -> [String] { public func chopVegetables() async throws -> [String] { let veggies = await getVegetables() // CHECK-NOT: {{^define }} - // CHECK: call void @llvm.dbg.declare(metadata i8* %0, metadata ![[V:[0-9]+]], metadata !DIExpression(DW_OP_deref + // CHECK: call void @llvm.dbg.declare(metadata i8* %0, metadata ![[V:[0-9]+]], metadata !DIExpression( // CHECK: ![[V]] = !DILocalVariable(name: "veggies" return veggies.map { "chopped \($0)" } } diff --git a/test/DebugInfo/async-lifetime-extension.swift b/test/DebugInfo/async-lifetime-extension.swift index 4006e0bd371d5..24b0f0b299686 100644 --- a/test/DebugInfo/async-lifetime-extension.swift +++ b/test/DebugInfo/async-lifetime-extension.swift @@ -8,16 +8,16 @@ // CHECK-LABEL: define {{.*}} void @"$s1a4fiboyS2iYaFTQ0_" // CHECK-NEXT: entryresume.0: -// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[RHS:[0-9]+]], {{.*}}!DIExpression(DW_OP -// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LHS:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[R:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[N:[0-9]+]], {{.*}}!DIExpression(DW_OP +// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LHS:[0-9]+]], {{.*}}!DIExpression(DW_OP +// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[RHS:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NOT: {{ ret }} // CHECK: call void asm sideeffect "" -// CHECK: ![[RHS]] = !DILocalVariable(name: "rhs" -// CHECK: ![[LHS]] = !DILocalVariable(name: "lhs" // CHECK: ![[R]] = !DILocalVariable(name: "retval" // CHECK: ![[N]] = !DILocalVariable(name: "n" +// CHECK: ![[LHS]] = !DILocalVariable(name: "lhs" +// CHECK: ![[RHS]] = !DILocalVariable(name: "rhs" public func fibo(_ n: Int) async -> Int { var retval = n if retval < 2 { return 1 } From 4445bc6fcfe47802636dba233b493373db964178 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 13 Aug 2021 14:35:04 -0700 Subject: [PATCH 060/116] Update test to use dwarfdump instead of readobj --- test/DebugInfo/apple-names-accel.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/DebugInfo/apple-names-accel.swift b/test/DebugInfo/apple-names-accel.swift index ff28e6e45d2e9..a7f3fb4f69aa2 100644 --- a/test/DebugInfo/apple-names-accel.swift +++ b/test/DebugInfo/apple-names-accel.swift @@ -1,7 +1,7 @@ // Check that the apple-names section is emitted on Darwin. // Adapted from llvm/test/DebugInfo/X86/debugger-tune.ll // RUN: %target-swiftc_driver -emit-object -g %s -o %t -// RUN: llvm-readobj -sections %t | %FileCheck --check-prefix=CHECK-LLDB %s +// RUN: %llvm-dwarfdump -a %t | %FileCheck --check-prefix=CHECK-LLDB %s // CHECK-LLDB-NOT: debug_pubnames // CHECK-LLDB: apple_names From ec913af4291e81fd0c5c75ccd4c71333b79afec3 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 13 Aug 2021 14:37:20 -0700 Subject: [PATCH 061/116] Revert "Updated async debug info tests for upstream IR changes" This reverts commit 63bd700d70896b119fe637de2d051eafbb1414bf. --- lib/IRGen/IRGenSIL.cpp | 3 +++ test/DebugInfo/async-args.swift | 15 ++++++++------- test/DebugInfo/async-let-await.swift | 2 +- test/DebugInfo/async-lifetime-extension.swift | 8 ++++---- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp index 18c4496f5a3b5..2eaea7349f480 100644 --- a/lib/IRGen/IRGenSIL.cpp +++ b/lib/IRGen/IRGenSIL.cpp @@ -952,6 +952,9 @@ class IRGenSILFunction : if (ValueVariables.insert(shadow).second) ValueDomPoints.push_back({shadow, getActiveDominancePoint()}); } + auto inst = cast(shadow); + llvm::IRBuilder<> builder(inst->getNextNode()); + shadow = builder.CreateLoad(shadow); } return shadow; diff --git a/test/DebugInfo/async-args.swift b/test/DebugInfo/async-args.swift index a67a25ec4e4b0..dd41325c8cda8 100644 --- a/test/DebugInfo/async-args.swift +++ b/test/DebugInfo/async-args.swift @@ -10,15 +10,17 @@ func withGenericArg(_ msg: T) async { // This odd debug info is part of a contract with CoroSplit/CoroFrame to fix // this up after coroutine splitting. // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYalF"(%swift.context* swiftasync %0 - // CHECK: call void @llvm.dbg.declare(metadata %swift.type** % - // CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression() - // CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** % - // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression(DW_OP_deref)) + // CHECK: call void @llvm.dbg.declare(metadata %swift.context* %0, + // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression( + // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) + // CHECK: call void @llvm.dbg.declare(metadata %swift.context* %0, + // CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression( + // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}})) await forceSplit() // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYalFTQ0_"(i8* swiftasync %0) // CHECK: call void @llvm.dbg.declare(metadata i8* %0, - // CHECK-SAME: metadata ![[MSG_R:[0-9]+]], metadata !DIExpression( + // CHECK-SAME: metadata ![[MSG_R:[0-9]+]], metadata !DIExpression(DW_OP_deref, // CHECK-SAME: DW_OP_plus_uconst, [[OFFSET:[0-9]+]], // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) // CHECK: call void @llvm.dbg.declare(metadata i8* %0, @@ -33,8 +35,7 @@ func withGenericArg(_ msg: T) async { await withGenericArg("hello (asynchronously)") } } -// CHECK: ![[TAU]] = !DILocalVariable(name: "$\CF\84_0_0", // CHECK: ![[MSG]] = !DILocalVariable(name: "msg", arg: 1, +// CHECK: ![[TAU]] = !DILocalVariable(name: "$\CF\84_0_0", // CHECK: ![[MSG_R]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[TAU_R]] = !DILocalVariable(name: "$\CF\84_0_0", - diff --git a/test/DebugInfo/async-let-await.swift b/test/DebugInfo/async-let-await.swift index 15a85e1b61568..37450e90685b1 100644 --- a/test/DebugInfo/async-let-await.swift +++ b/test/DebugInfo/async-let-await.swift @@ -11,7 +11,7 @@ public func getVegetables() async -> [String] { public func chopVegetables() async throws -> [String] { let veggies = await getVegetables() // CHECK-NOT: {{^define }} - // CHECK: call void @llvm.dbg.declare(metadata i8* %0, metadata ![[V:[0-9]+]], metadata !DIExpression( + // CHECK: call void @llvm.dbg.declare(metadata i8* %0, metadata ![[V:[0-9]+]], metadata !DIExpression(DW_OP_deref // CHECK: ![[V]] = !DILocalVariable(name: "veggies" return veggies.map { "chopped \($0)" } } diff --git a/test/DebugInfo/async-lifetime-extension.swift b/test/DebugInfo/async-lifetime-extension.swift index 24b0f0b299686..4006e0bd371d5 100644 --- a/test/DebugInfo/async-lifetime-extension.swift +++ b/test/DebugInfo/async-lifetime-extension.swift @@ -8,16 +8,16 @@ // CHECK-LABEL: define {{.*}} void @"$s1a4fiboyS2iYaFTQ0_" // CHECK-NEXT: entryresume.0: +// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[RHS:[0-9]+]], {{.*}}!DIExpression(DW_OP +// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LHS:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[R:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[N:[0-9]+]], {{.*}}!DIExpression(DW_OP -// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LHS:[0-9]+]], {{.*}}!DIExpression(DW_OP -// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[RHS:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NOT: {{ ret }} // CHECK: call void asm sideeffect "" +// CHECK: ![[RHS]] = !DILocalVariable(name: "rhs" +// CHECK: ![[LHS]] = !DILocalVariable(name: "lhs" // CHECK: ![[R]] = !DILocalVariable(name: "retval" // CHECK: ![[N]] = !DILocalVariable(name: "n" -// CHECK: ![[LHS]] = !DILocalVariable(name: "lhs" -// CHECK: ![[RHS]] = !DILocalVariable(name: "rhs" public func fibo(_ n: Int) async -> Int { var retval = n if retval < 2 { return 1 } From cbb89c78de25bc0a541725e4fefb76fbd0b22da6 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 13 Aug 2021 14:31:38 -0700 Subject: [PATCH 062/116] Remove an extra load that was generated for coro shadow copies. emitShadowCopyIfNeeded has some extra code that was added when function arguments were moved out of the async context to ensure that they are being lifetime-extended, and there is also code that generates an incorrect load from the shadow copy. However, emitShadowCopyIfNeeded is supposed return either an alloca or the value, and IRGenDebugInfo knows to describe the value in the alloca already. The load is counterproductive it's only valid until whatever register it ends up in is clobbered, whereas the alloca is valid throughout the function. This patch removes the load and updates the tests accordingly. rdar://81805727 --- lib/IRGen/IRGenSIL.cpp | 3 --- test/DebugInfo/async-args.swift | 15 +++++++-------- test/DebugInfo/async-let-await.swift | 2 +- test/DebugInfo/async-lifetime-extension.swift | 8 ++++---- 4 files changed, 12 insertions(+), 16 deletions(-) diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp index 2eaea7349f480..18c4496f5a3b5 100644 --- a/lib/IRGen/IRGenSIL.cpp +++ b/lib/IRGen/IRGenSIL.cpp @@ -952,9 +952,6 @@ class IRGenSILFunction : if (ValueVariables.insert(shadow).second) ValueDomPoints.push_back({shadow, getActiveDominancePoint()}); } - auto inst = cast(shadow); - llvm::IRBuilder<> builder(inst->getNextNode()); - shadow = builder.CreateLoad(shadow); } return shadow; diff --git a/test/DebugInfo/async-args.swift b/test/DebugInfo/async-args.swift index dd41325c8cda8..a67a25ec4e4b0 100644 --- a/test/DebugInfo/async-args.swift +++ b/test/DebugInfo/async-args.swift @@ -10,17 +10,15 @@ func withGenericArg(_ msg: T) async { // This odd debug info is part of a contract with CoroSplit/CoroFrame to fix // this up after coroutine splitting. // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYalF"(%swift.context* swiftasync %0 - // CHECK: call void @llvm.dbg.declare(metadata %swift.context* %0, - // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression( - // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) - // CHECK: call void @llvm.dbg.declare(metadata %swift.context* %0, - // CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression( - // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}})) + // CHECK: call void @llvm.dbg.declare(metadata %swift.type** % + // CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression() + // CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** % + // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression(DW_OP_deref)) await forceSplit() // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYalFTQ0_"(i8* swiftasync %0) // CHECK: call void @llvm.dbg.declare(metadata i8* %0, - // CHECK-SAME: metadata ![[MSG_R:[0-9]+]], metadata !DIExpression(DW_OP_deref, + // CHECK-SAME: metadata ![[MSG_R:[0-9]+]], metadata !DIExpression( // CHECK-SAME: DW_OP_plus_uconst, [[OFFSET:[0-9]+]], // CHECK-SAME: DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_deref)) // CHECK: call void @llvm.dbg.declare(metadata i8* %0, @@ -35,7 +33,8 @@ func withGenericArg(_ msg: T) async { await withGenericArg("hello (asynchronously)") } } -// CHECK: ![[MSG]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[TAU]] = !DILocalVariable(name: "$\CF\84_0_0", +// CHECK: ![[MSG]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[MSG_R]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[TAU_R]] = !DILocalVariable(name: "$\CF\84_0_0", + diff --git a/test/DebugInfo/async-let-await.swift b/test/DebugInfo/async-let-await.swift index 37450e90685b1..15a85e1b61568 100644 --- a/test/DebugInfo/async-let-await.swift +++ b/test/DebugInfo/async-let-await.swift @@ -11,7 +11,7 @@ public func getVegetables() async -> [String] { public func chopVegetables() async throws -> [String] { let veggies = await getVegetables() // CHECK-NOT: {{^define }} - // CHECK: call void @llvm.dbg.declare(metadata i8* %0, metadata ![[V:[0-9]+]], metadata !DIExpression(DW_OP_deref + // CHECK: call void @llvm.dbg.declare(metadata i8* %0, metadata ![[V:[0-9]+]], metadata !DIExpression( // CHECK: ![[V]] = !DILocalVariable(name: "veggies" return veggies.map { "chopped \($0)" } } diff --git a/test/DebugInfo/async-lifetime-extension.swift b/test/DebugInfo/async-lifetime-extension.swift index 4006e0bd371d5..24b0f0b299686 100644 --- a/test/DebugInfo/async-lifetime-extension.swift +++ b/test/DebugInfo/async-lifetime-extension.swift @@ -8,16 +8,16 @@ // CHECK-LABEL: define {{.*}} void @"$s1a4fiboyS2iYaFTQ0_" // CHECK-NEXT: entryresume.0: -// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[RHS:[0-9]+]], {{.*}}!DIExpression(DW_OP -// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LHS:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[R:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[N:[0-9]+]], {{.*}}!DIExpression(DW_OP +// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LHS:[0-9]+]], {{.*}}!DIExpression(DW_OP +// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[RHS:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NOT: {{ ret }} // CHECK: call void asm sideeffect "" -// CHECK: ![[RHS]] = !DILocalVariable(name: "rhs" -// CHECK: ![[LHS]] = !DILocalVariable(name: "lhs" // CHECK: ![[R]] = !DILocalVariable(name: "retval" // CHECK: ![[N]] = !DILocalVariable(name: "n" +// CHECK: ![[LHS]] = !DILocalVariable(name: "lhs" +// CHECK: ![[RHS]] = !DILocalVariable(name: "rhs" public func fibo(_ n: Int) async -> Int { var retval = n if retval < 2 { return 1 } From 92c159ced87dadf24c326a8d982d956ae644e3c3 Mon Sep 17 00:00:00 2001 From: Vedant Kumar Date: Mon, 16 Aug 2021 11:46:12 -0700 Subject: [PATCH 063/116] Revert "[test] Fix a bug in test/Profiler/coverage_smoke.swift" (#38893) This reverts commit 956558f23fed93d10e6754dbf6448a4d7b3ffbe9, due to https://reviews.llvm.org/D85036 being reverted upstream. rdar://81815347 --- test/Profiler/coverage_smoke.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Profiler/coverage_smoke.swift b/test/Profiler/coverage_smoke.swift index 4edf0177839d0..26b6c6b21bf75 100644 --- a/test/Profiler/coverage_smoke.swift +++ b/test/Profiler/coverage_smoke.swift @@ -134,8 +134,8 @@ var g2: Int = 0 class Class3 { var m1 = g2 == 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}2 - ? "false" // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 - : "true"; // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 + ? "false" // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}2 + : "true"; // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}2 } // rdar://34244637: Wrong coverage for do/catch sequence From 9066d9132ebb42727b6b8aa0cc58830fe3d0fa4d Mon Sep 17 00:00:00 2001 From: Vedant Kumar Date: Mon, 16 Aug 2021 11:49:02 -0700 Subject: [PATCH 064/116] Revert "[test] Fix a bug in test/Profiler/coverage_smoke.swift" (#38894) This reverts commit ebdb4d9ace39107d6912a572aaf4d10bd81871a8, due to https://reviews.llvm.org/D85036 being reverted upstream. rdar://81815347 --- test/Profiler/coverage_smoke.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Profiler/coverage_smoke.swift b/test/Profiler/coverage_smoke.swift index 26b6c6b21bf75..b3b3e959a1a9b 100644 --- a/test/Profiler/coverage_smoke.swift +++ b/test/Profiler/coverage_smoke.swift @@ -150,7 +150,7 @@ func throwError(_ b: Bool) throws { func catchError(_ b: Bool) -> Int { do { try throwError(b) // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}2 - } catch { // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 + } catch { // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}2 return 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 let _ = 1 + 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 From c18b50e96d8cbdc2b89ce20f28d6d0d8aac0c850 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Tue, 17 Aug 2021 12:28:49 -0700 Subject: [PATCH 065/116] Fixing flag truncations in llvm-readobj tests It looks like commit 46580d43fc70d migrated the flags from llvm::cl to OptTable. As a result, the flag behaviour changed. Commit e29e30b1397f3e50f3487491f8a77ae08e4e3471 from 2019 went through and changed the llvm tests to consistently use the double-dash for long options so it was undetected. With this info, I'm just going to go ahead and fix these tests cases to get them going again. --- test/Incremental/autolinking-overlay.swift | 6 +++--- test/Incremental/autolinking.swift | 6 +++--- test/multifile/protocol-conformance-member.swift | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/test/Incremental/autolinking-overlay.swift b/test/Incremental/autolinking-overlay.swift index bf76451fa2ed5..9e923bd0ffaba 100644 --- a/test/Incremental/autolinking-overlay.swift +++ b/test/Incremental/autolinking-overlay.swift @@ -9,9 +9,9 @@ // RUN: %target-build-swift-dylib(%t/%target-library-name(AutolinkingTest)) -autolink-force-load -module-link-name swiftAutolinkingTest -incremental -driver-show-incremental -module-name AutolinkingTest -output-file-map ofm.json -F %t -import-underlying-module autolinking-overlay.swift autolinking-other.swift // Make sure `swift_FORCE_LOAD_$_swiftAutolinkingTest` appears in all objects -// RUN: llvm-readobj -symbols -coff-exports %t/autolinking-overlay.o | %FileCheck %s -// RUN: llvm-readobj -symbols -coff-exports %t/autolinking-other.o | %FileCheck %s -// RUN: llvm-readobj -symbols -coff-exports %t/%target-library-name(AutolinkingTest) | %FileCheck %s +// RUN: llvm-readobj --symbols --coff-exports %t/autolinking-overlay.o | %FileCheck %s +// RUN: llvm-readobj --symbols --coff-exports %t/autolinking-other.o | %FileCheck %s +// RUN: llvm-readobj --symbols --coff-exports %t/%target-library-name(AutolinkingTest) | %FileCheck %s // Emulate an overlay build by importing content from the underlying module. extension Test { } diff --git a/test/Incremental/autolinking.swift b/test/Incremental/autolinking.swift index 3537c96726ce5..d23f2ec471901 100644 --- a/test/Incremental/autolinking.swift +++ b/test/Incremental/autolinking.swift @@ -9,8 +9,8 @@ // RUN: %target-build-swift-dylib(%t/%target-library-name(AutolinkingTest)) -autolink-force-load -module-link-name swiftAutolinkingTest -incremental -driver-show-incremental -module-name AutolinkingTest -output-file-map ofm.json autolinking.swift autolinking-other.swift // Make sure `swift_FORCE_LOAD_$_swiftAutolinkingTest` appears in all objects -// RUN: llvm-readobj -symbols -coff-exports %t/autolinking.o | %FileCheck %s -// RUN: llvm-readobj -symbols -coff-exports %t/autolinking-other.o | %FileCheck %s -// RUN: llvm-readobj -symbols -coff-exports %t/%target-library-name(AutolinkingTest) | %FileCheck %s +// RUN: llvm-readobj --symbols --coff-exports %t/autolinking.o | %FileCheck %s +// RUN: llvm-readobj --symbols --coff-exports %t/autolinking-other.o | %FileCheck %s +// RUN: llvm-readobj --symbols --coff-exports %t/%target-library-name(AutolinkingTest) | %FileCheck %s // CHECK: _swift_FORCE_LOAD_$_swiftAutolinkingTest diff --git a/test/multifile/protocol-conformance-member.swift b/test/multifile/protocol-conformance-member.swift index 838e83025af2c..96a2ded38e1b7 100644 --- a/test/multifile/protocol-conformance-member.swift +++ b/test/multifile/protocol-conformance-member.swift @@ -1,6 +1,6 @@ // RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-library %s %S/Inputs/protocol-conformance-member-helper.swift -o %t/%target-library-name(Test) -module-name Test -// RUN: llvm-readobj -symbols -coff-exports %t/%target-library-name(Test) | %FileCheck %s +// RUN: llvm-readobj --symbols --coff-exports %t/%target-library-name(Test) | %FileCheck %s // CHECK: Name: {{_?}}$s4Test10CoolStructV10coolFactorSdvg From b7e2b2a6e7c8750695a81023ee23ae314801490b Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Tue, 17 Aug 2021 16:45:31 -0700 Subject: [PATCH 066/116] Remove an extra load that was generated for coro shadow copies. This commit is similar to cbb89c78d, but for explosions. emitShadowCopyIfNeeded() has some extra code that was added when function arguments were moved out of the async context to ensure that they are being lifetime-extended, and there is also code that generates an incorrect load from the shadow copy. However, emitShadowCopyIfNeeded is supposed return either an alloca or the value, and IRGenDebugInfo knows to describe the value in the alloca already. The load is counterproductive it's only valid until whatever register it ends up in is clobbered, whereas the alloca is valid throughout the function. This patch removes the load and updates the tests accordingly. rdar://81565869 --- lib/IRGen/IRGenSIL.cpp | 9 +-------- test/DebugInfo/async-local-var.swift | 2 +- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp index 18c4496f5a3b5..e563dd1af3632 100644 --- a/lib/IRGen/IRGenSIL.cpp +++ b/lib/IRGen/IRGenSIL.cpp @@ -1024,16 +1024,9 @@ class IRGenSILFunction : LTI.initialize(*this, e, Alloca, false /* isOutlined */); auto shadow = Alloca.getAddress(); // Async functions use the value of the artificial address. - if (CurSILFn->isAsync() && emitLifetimeExtendingUse(shadow)) { + if (CurSILFn->isAsync() && emitLifetimeExtendingUse(shadow)) if (ValueVariables.insert(shadow).second) ValueDomPoints.push_back({shadow, getActiveDominancePoint()}); - auto inst = cast(shadow); - llvm::IRBuilder<> builder(inst->getNextNode()); - shadow = builder.CreateLoad(shadow); - copy.push_back(shadow); - return; - } - } copy.push_back(Alloca.getAddress()); } diff --git a/test/DebugInfo/async-local-var.swift b/test/DebugInfo/async-local-var.swift index 83aeed47ee242..aebc99aa98bb9 100644 --- a/test/DebugInfo/async-local-var.swift +++ b/test/DebugInfo/async-local-var.swift @@ -16,7 +16,7 @@ public func makeDinner() async throws -> String { // CHECK-LABEL: define {{.*}} void @"$s1a10makeDinnerSSyYaKFTQ0_" // CHECK-NEXT: entryresume.0: // CHECK-NOT: {{ ret }} -// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LOCAL:[0-9]+]], {{.*}}!DIExpression(DW_OP_deref +// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LOCAL:[0-9]+]], {{.*}}!DIExpression(DW_OP_plus_uconst // CHECK: ![[LOCAL]] = !DILocalVariable(name: "local" return local } From 26eedd501ca9bd81aed98a133d51d3bf750acf03 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 18 Aug 2021 09:49:59 -0700 Subject: [PATCH 067/116] Remove undefined variables from let_decls FileCheck no longer accepts undefined variables. Removing the ones in let_decls.swift --- test/SILGen/let_decls.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/SILGen/let_decls.swift b/test/SILGen/let_decls.swift index 398c7a9a90503..3e32d00584e4b 100644 --- a/test/SILGen/let_decls.swift +++ b/test/SILGen/let_decls.swift @@ -398,7 +398,6 @@ struct StructMemberTest { // CHECK: debug_value [[ARG]] : $StructMemberTest, let, name "self" // CHECK: [[TRIVIAL_VALUE:%.*]] = struct_extract [[ARG]] : $StructMemberTest, #StructMemberTest.i // CHECK-NOT: destroy_value [[ARG]] : $StructMemberTest - // CHECK-NOT: destroy_value [[BORROWED_ARG]] : $StructMemberTest // CHECK: return [[TRIVIAL_VALUE]] : $Int // Accessing the int member in s should not copy_value the whole struct. @@ -454,7 +453,6 @@ struct GenericStruct { // CHECK-NEXT: debug_value_addr [[SELF_ADDR]] : $*GenericStruct, let, name "self" // CHECK-NEXT: [[PROJ_ADDR:%.*]] = struct_element_addr [[SELF_ADDR]] : $*GenericStruct, #GenericStruct.b // CHECK-NEXT: [[PROJ_VAL:%.*]] = load [trivial] [[PROJ_ADDR]] : $*Int - // CHECK-NOT: destroy_addr [[SELF]] : $*GenericStruct // CHECK-NEXT: return [[PROJ_VAL]] : $Int } From ac295fd39cd9a2d3b391b0ec20166d9b4d7dbae9 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 18 Aug 2021 12:15:07 -0700 Subject: [PATCH 068/116] Remove BORROWED_FN_COPY from unmanaged_ownership This test doesn't define a BORROWED_FN_COPY variable, so it is failing. FileCheck no longer allows undefined variables. --- test/SILGen/unmanaged_ownership.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/test/SILGen/unmanaged_ownership.swift b/test/SILGen/unmanaged_ownership.swift index ee69cfeaeff56..568913c17d225 100644 --- a/test/SILGen/unmanaged_ownership.swift +++ b/test/SILGen/unmanaged_ownership.swift @@ -63,5 +63,4 @@ func project(fn fn: () -> Holder) -> C { // CHECK-NEXT: [[T0:%.*]] = apply [[FN]]() // CHECK-NEXT: [[T1:%.*]] = struct_extract [[T0]] : $Holder, #Holder.value // CHECK-NEXT: [[T2:%.*]] = strong_copy_unmanaged_value [[T1]] -// CHECK-NOT: destroy_value [[BORROWED_FN_COPY]] // CHECK-NEXT: return [[T2]] From 4040ad3680d55be3a43ac8d46dae704b9e6da2a7 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 18 Aug 2021 16:25:36 -0700 Subject: [PATCH 069/116] Disable storage3 check in NewStringAppending The other instances had been disabled in commit 5236224eb16a. FileCheck was recently updated so that it complains about undefined variables, which is why no one noticed until now. storage3 wasn't defined because the place where it got defined was disabled. Disabling that instance now. --- test/stdlib/NewStringAppending.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/stdlib/NewStringAppending.swift b/test/stdlib/NewStringAppending.swift index 8d1f0568095e4..e91e9ac5166e2 100644 --- a/test/stdlib/NewStringAppending.swift +++ b/test/stdlib/NewStringAppending.swift @@ -143,7 +143,7 @@ print("\(repr(s1))") print("(expect copy to trigger reallocation without growth)") // CHECK-NEXT: String(Native(owner: @[[storage4:[x0-9a-f]+]], count: 73, capacity: 87)) = "{{.*}}X" -// CHECK-NOT: @[[storage3]], +// xCHECK-NOT: @[[storage3]], s1 += "X" print("\(repr(s1))") From ad6facb016ffbd75a59a8dd42588ce012c3553bf Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 18 Aug 2021 11:14:04 -0700 Subject: [PATCH 070/116] Remove undefined ACFUN variable Thies removes the ACFUN variable from the array_element_propagation and array_element_propagation_ossa test cases because it isn't defined anywhere. --- test/SILOptimizer/array_element_propagation.sil | 3 ++- test/SILOptimizer/array_element_propagation_ossa.sil | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/test/SILOptimizer/array_element_propagation.sil b/test/SILOptimizer/array_element_propagation.sil index 7a542669823d9..5098b124e90bd 100644 --- a/test/SILOptimizer/array_element_propagation.sil +++ b/test/SILOptimizer/array_element_propagation.sil @@ -222,7 +222,8 @@ sil @unknown_use : $@convention(thin) () -> () { // CHECK: [[ASFUN:%.*]] = function_ref @arrayAdoptStorage // CHECK-NEXT: [[ARR:%.*]] = apply [[ASFUN]] // CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[ARR]]{{.*}}, 0 -// CHECK-NOT: apply [[ACFUN]] +// CHECK: [[ACFUN:%.*]] = function_ref @arrayAppendContentsOf +// CHECK-NOT: apply [[ACFUN]] // CHECK: [[AEFUN:%.*]] = function_ref @$sSa6appendyyxnF // CHECK-NEXT: [[STACK:%.*]] = alloc_stack $MyInt // CHECK-NEXT: store %{{[0-9]+}} to [[STACK]] diff --git a/test/SILOptimizer/array_element_propagation_ossa.sil b/test/SILOptimizer/array_element_propagation_ossa.sil index 63c91d288444e..871a28796df7d 100644 --- a/test/SILOptimizer/array_element_propagation_ossa.sil +++ b/test/SILOptimizer/array_element_propagation_ossa.sil @@ -216,6 +216,7 @@ sil [ossa] @unknown_use : $@convention(thin) () -> () { // CHECK: [[ASFUN:%.*]] = function_ref @arrayAdoptStorage // CHECK-NEXT: [[ARR:%.*]] = apply [[ASFUN]] // CHECK-NEXT: ([[OWNER:%[0-9]+]], [[PTR:%[0-9]+]]) = destructure_tuple [[ARR]]{{.*}} +// CHECK: [[ACFUN:%.*]] = function_ref @arrayAppendContentsOf // CHECK-NOT: apply [[ACFUN]] // CHECK: [[AEFUN:%.*]] = function_ref @$sSa6appendyyxnF // CHECK-NEXT: [[STACK:%.*]] = alloc_stack $MyInt @@ -284,4 +285,4 @@ bb0: destroy_value %7 : $MyArray %23 = tuple () return %23 : $() -} \ No newline at end of file +} From fc366f0e9624cfafde68139e89b52c137e7a58e2 Mon Sep 17 00:00:00 2001 From: Eric Miotto <1094986+edymtt@users.noreply.github.com> Date: Fri, 20 Aug 2021 07:42:13 -0700 Subject: [PATCH 071/116] [rebranch] remove unneeded SingleCommandCompilationDatabase (#38961) This class will now be provided by LLVM as part of apple/llvm-project#3183 --- .../ClangModuleDependencyScanner.cpp | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/lib/ClangImporter/ClangModuleDependencyScanner.cpp b/lib/ClangImporter/ClangModuleDependencyScanner.cpp index 465d436b2365c..45f393844e7ce 100644 --- a/lib/ClangImporter/ClangModuleDependencyScanner.cpp +++ b/lib/ClangImporter/ClangModuleDependencyScanner.cpp @@ -80,26 +80,6 @@ llvm::ErrorOr ClangModuleDependenciesCacheImpl::getImportHackFile(Str return importHackFileCache[moduleName]; } -namespace { - class SingleCommandCompilationDatabase : public CompilationDatabase { - public: - SingleCommandCompilationDatabase(CompileCommand Cmd) - : Command(std::move(Cmd)) {} - - virtual std::vector - getCompileCommands(StringRef FilePath) const override { - return {Command}; - } - - virtual std::vector getAllCompileCommands() const override { - return {Command}; - } - - private: - CompileCommand Command; - }; -} - // Add search paths. // Note: This is handled differently for the Clang importer itself, which // adds search paths to Clang's data structures rather than to its From c40b8f38b8c88033f23043c2e63ca45a14d2ae46 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 20 Aug 2021 12:57:23 -0700 Subject: [PATCH 072/116] Update IRGenDebugInfo for LLVM D95617. In https://reviews.llvm.org/D95617 LLVM stopped to emit debug values without a location as an optimization for inlined functions. Because Swift is emitting dbg.values(undef) for sizeless variables even at -Onone, we need to make sure all local variables are preserved even at -Onone. rdar://82038523 --- lib/IRGen/IRGenDebugInfo.cpp | 7 +++++-- test/DebugInfo/anonymous.swift | 2 +- test/DebugInfo/async-args.swift | 2 +- test/DebugInfo/async-lifetime-extension.swift | 2 +- test/DebugInfo/patternmatching.swift | 3 +-- test/DebugInfo/sroa_mem2reg.sil | 5 +++-- 6 files changed, 12 insertions(+), 9 deletions(-) diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index 7c52b0a5c7e6b..6a791878db0c1 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -2457,13 +2457,16 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( getOrCreateScope(VarInfo.Scope))) VarScope = VS; } + // The llvm.dbg.value(undef) emitted for zero-sized variables get filtered out + // by DwarfDebug::collectEntityInfo() otherwise. + bool Preserve = true; llvm::DILocalVariable *Var = (VarInfo.ArgNo > 0) ? DBuilder.createParameterVariable(VarScope, VarInfo.Name, VarInfo.ArgNo, Unit, DVarLine, - DITy, Optimized, Flags) + DITy, Preserve, Flags) : DBuilder.createAutoVariable(VarScope, VarInfo.Name, Unit, DVarLine, - DITy, Optimized, Flags); + DITy, Preserve, Flags); auto appendDIExpression = [&VarInfo, this](llvm::DIExpression *DIExpr) -> llvm::DIExpression * { diff --git a/test/DebugInfo/anonymous.swift b/test/DebugInfo/anonymous.swift index 4b2e4e1c2763b..c1734d9ad9311 100644 --- a/test/DebugInfo/anonymous.swift +++ b/test/DebugInfo/anonymous.swift @@ -1,9 +1,9 @@ // RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | %FileCheck %s -// CHECK: !DILocalVariable(name: "x4", arg: 4 // CHECK: !DILocalVariable(name: "_0", arg: 1 // CHECK: !DILocalVariable(name: "_1", arg: 2 // CHECK: !DILocalVariable(name: "_2", arg: 3 +// CHECK: !DILocalVariable(name: "x4", arg: 4 public func fourth(_: T, _: T, _: T, x4 : T) -> T { return x4 diff --git a/test/DebugInfo/async-args.swift b/test/DebugInfo/async-args.swift index a67a25ec4e4b0..b7201d6e1d831 100644 --- a/test/DebugInfo/async-args.swift +++ b/test/DebugInfo/async-args.swift @@ -35,6 +35,6 @@ func withGenericArg(_ msg: T) async { } // CHECK: ![[TAU]] = !DILocalVariable(name: "$\CF\84_0_0", // CHECK: ![[MSG]] = !DILocalVariable(name: "msg", arg: 1, -// CHECK: ![[MSG_R]] = !DILocalVariable(name: "msg", arg: 1, // CHECK: ![[TAU_R]] = !DILocalVariable(name: "$\CF\84_0_0", +// CHECK: ![[MSG_R]] = !DILocalVariable(name: "msg", arg: 1, diff --git a/test/DebugInfo/async-lifetime-extension.swift b/test/DebugInfo/async-lifetime-extension.swift index 24b0f0b299686..f7e259c83b580 100644 --- a/test/DebugInfo/async-lifetime-extension.swift +++ b/test/DebugInfo/async-lifetime-extension.swift @@ -14,8 +14,8 @@ // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[RHS:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NOT: {{ ret }} // CHECK: call void asm sideeffect "" -// CHECK: ![[R]] = !DILocalVariable(name: "retval" // CHECK: ![[N]] = !DILocalVariable(name: "n" +// CHECK: ![[R]] = !DILocalVariable(name: "retval" // CHECK: ![[LHS]] = !DILocalVariable(name: "lhs" // CHECK: ![[RHS]] = !DILocalVariable(name: "rhs" public func fibo(_ n: Int) async -> Int { diff --git a/test/DebugInfo/patternmatching.swift b/test/DebugInfo/patternmatching.swift index 365c7ed2e0101..5474412cd215d 100644 --- a/test/DebugInfo/patternmatching.swift +++ b/test/DebugInfo/patternmatching.swift @@ -92,9 +92,8 @@ func classifyPoint2(_ p: (Double, Double)) { // CHECK-SCOPES: ![[X1]] = {{.*}}name: "x", scope: ![[SCOPE1:[0-9]+]], {{.*}}line: 37 // CHECK-SCOPES: ![[SCOPE1]] = distinct !DILexicalBlock(scope: ![[SWITCH1:[0-9]+]], {{.*}}line: 37 // CHECK-SCOPES: ![[SWITCH1]] = distinct !DILexicalBlock({{.*}}, line: 20 -// CHECK-SCOPES: ![[X1LOC]] = {{.*}}line: 37 - // CHECK-SCOPES: ![[Y1]] = {{.*}}name: "y", scope: ![[SCOPE1]], {{.*}}line: 37 +// CHECK-SCOPES: ![[X1LOC]] = {{.*}}line: 37 // CHECK-SCOPES: ![[Y1LOC]] = {{.*}}line: 37 // CHECK: !DILocation(line: [[@LINE+1]], diff --git a/test/DebugInfo/sroa_mem2reg.sil b/test/DebugInfo/sroa_mem2reg.sil index e265ad1390e78..8cfd067d3cb33 100644 --- a/test/DebugInfo/sroa_mem2reg.sil +++ b/test/DebugInfo/sroa_mem2reg.sil @@ -74,13 +74,14 @@ bb0(%0 : $Int64, %1 : $Int64): return %0 : $Int64, loc "sroa.swift":11:5, scope 2 } // end sil function 'foo' -// CHECK-IR: ![[STRUCT_MD]] = !DILocalVariable(name: "my_struct" -// CHECK-IR-SAME: line: 8 // CHECK-IR: ![[ARG1_MD]] = !DILocalVariable(name: "in_x", arg: 1 // CHECK-IR-SAME: line: 7 // CHECK-IR: ![[ARG2_MD]] = !DILocalVariable(name: "in_y", arg: 2 // CHECK-IR-SAME: line: 7 +// CHECK-IR: ![[STRUCT_MD]] = !DILocalVariable(name: "my_struct" +// CHECK-IR-SAME: line: 8 + // CHECK-DWARF-LABEL: DW_AT_name ("foo") // CHECK-DWARF: DW_TAG_variable // CHECK-DWARF: DW_AT_name ("my_struct") From 6961f55a853bdf058e5bf936f40e0a1c020b409d Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 18 Aug 2021 11:15:20 -0700 Subject: [PATCH 073/116] Remove ORIG_SELF from super_init test ORIG_SELF was not defined in the test, so FileCheck is complaining about that. Removing it. --- test/SILOptimizer/super_init.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/SILOptimizer/super_init.swift b/test/SILOptimizer/super_init.swift index a7ae5a4aa8a59..d4316a2a936e7 100644 --- a/test/SILOptimizer/super_init.swift +++ b/test/SILOptimizer/super_init.swift @@ -7,7 +7,7 @@ // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]] // CHECK-LABEL: sil hidden [noinline] @$s10super_init3BarC{{[_0-9a-zA-Z]*}}fc -// CHECK-NOT: super_method [[ORIG_SELF]] : $Bar, #Foo.init!initializer +// CHECK-NOT: super_method // CHECK: function_ref @$s10super_init3FooCACycfc class Foo { From 2bfbded9e3e42af2663ad88ca3dcc0e9c1eb601e Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 18 Aug 2021 11:21:12 -0700 Subject: [PATCH 074/116] Remove STACK variable from mem2reg tests STACK only seems to be defined in a CHECK-NOT. FileCheck doesn't like this and is complaining about undefined variables. Removing the references to STACK. --- test/SILOptimizer/mem2reg.sil | 6 +++--- test/SILOptimizer/mem2reg_ossa.sil | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/SILOptimizer/mem2reg.sil b/test/SILOptimizer/mem2reg.sil index 3452e3c42bfe2..0a6f7f183ac32 100644 --- a/test/SILOptimizer/mem2reg.sil +++ b/test/SILOptimizer/mem2reg.sil @@ -298,7 +298,7 @@ bb2: // CHECK: bb3([[ARG:%.*]] : $@callee_owned () -> Int): bb3: -// CHECK-NOT: load [[STACK]] +// CHECK-NOT: load %13 = load %1 : $*@callee_owned () -> Int // CHECK: strong_retain [[ARG]] strong_retain %13 : $@callee_owned () -> Int @@ -311,10 +311,10 @@ bb3: // block. // CHECK: bb4 bb4: -// CHECK-NOT: destroy_addr [[STACK]] +// CHECK-NOT: destroy_addr // CHECK: strong_release [[ARG]] destroy_addr %1 : $*@callee_owned () -> Int -// CHECK-NOT: dealloc_stack [[STACK]] +// CHECK-NOT: dealloc_stack dealloc_stack %1 : $*@callee_owned () -> Int // CHECK: return [[RESULT]] return %15 : $Int diff --git a/test/SILOptimizer/mem2reg_ossa.sil b/test/SILOptimizer/mem2reg_ossa.sil index 9ccfc15d70f91..bb7abb7483b51 100644 --- a/test/SILOptimizer/mem2reg_ossa.sil +++ b/test/SILOptimizer/mem2reg_ossa.sil @@ -299,7 +299,7 @@ bb2: // CHECK: bb3([[ARG:%.*]] : @owned $@callee_owned () -> Int): bb3: -// CHECK-NOT: load [[STACK]] +// CHECK-NOT: load %13 = load [copy] %1 : $*@callee_owned () -> Int // CHECK: [[COPY:%.*]] = copy_value [[ARG]] // CHECK: [[RESULT:%.*]] = apply [[COPY]] @@ -311,10 +311,10 @@ bb3: // block. // CHECK: bb4 bb4: -// CHECK-NOT: destroy_addr [[STACK]] +// CHECK-NOT: destroy_addr // CHECK: destroy_value [[ARG]] destroy_addr %1 : $*@callee_owned () -> Int -// CHECK-NOT: dealloc_stack [[STACK]] +// CHECK-NOT: dealloc_stack dealloc_stack %1 : $*@callee_owned () -> Int return %15 : $Int } From 47f28ab84a7e7b6f13d039c35f41a27623f1a096 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 20 Aug 2021 17:31:39 -0700 Subject: [PATCH 075/116] Enter a new debug scope for every let binding. This fixes an ambiguity (that leads to a crash further down the pipeline) when compiling optional unwrap bindings that bind the same variable name. rdar://73490741 (cherry picked from commit 173c0b4657584fb545fcfeab4f0323b8b1a3aeb2) --- lib/SILGen/SILGenFunction.h | 15 ++++++++------- lib/SILGen/SILGenStmt.cpp | 3 --- lib/SILGen/SwitchEnumBuilder.cpp | 5 +++++ test/DebugInfo/guard-let-scope.swift | 2 +- test/SILOptimizer/constantprop-wrongscope.swift | 8 ++++---- test/SILOptimizer/definite-init-wrongscope.swift | 14 +++++++------- 6 files changed, 25 insertions(+), 22 deletions(-) diff --git a/lib/SILGen/SILGenFunction.h b/lib/SILGen/SILGenFunction.h index 792fea6f59a5b..6bee2ab912da6 100644 --- a/lib/SILGen/SILGenFunction.h +++ b/lib/SILGen/SILGenFunction.h @@ -305,7 +305,7 @@ class LLVM_LIBRARY_VISIBILITY SILGenFunction std::vector SwitchStack; /// Keep track of our current nested scope. /// - /// The boolean tracks whether this is a 'guard' scope, which should be + /// The boolean tracks whether this is a binding scope, which should be /// popped automatically when we leave the innermost BraceStmt scope. std::vector> DebugScopeStack; @@ -580,11 +580,12 @@ class LLVM_LIBRARY_VISIBILITY SILGenFunction /// Enter the debug scope for \p Loc, creating it if necessary. /// - /// \param isGuardScope If true, this is a scope for the bindings introduced by - /// a 'guard' statement. This scope ends when the next innermost BraceStmt ends. - void enterDebugScope(SILLocation Loc, bool isGuardScope=false) { - auto *Parent = - DebugScopeStack.size() ? DebugScopeStack.back().getPointer() : F.getDebugScope(); + /// \param isBindingScope If true, this is a scope for the bindings introduced + /// by a let expression. This scope ends when the next innermost BraceStmt + /// ends. + void enterDebugScope(SILLocation Loc, bool isBindingScope = false) { + auto *Parent = DebugScopeStack.size() ? DebugScopeStack.back().getPointer() + : F.getDebugScope(); auto *DS = Parent; // Don't create a pointless scope for the function body's BraceStmt. if (!DebugScopeStack.empty()) @@ -592,7 +593,7 @@ class LLVM_LIBRARY_VISIBILITY SILGenFunction if (RegularLocation(DS->getLoc()) != RegularLocation(Loc)) DS = new (SGM.M) SILDebugScope(RegularLocation(Loc), &getFunction(), DS); - DebugScopeStack.emplace_back(DS, isGuardScope); + DebugScopeStack.emplace_back(DS, isBindingScope); B.setCurrentDebugScope(DS); } diff --git a/lib/SILGen/SILGenStmt.cpp b/lib/SILGen/SILGenStmt.cpp index cae6e98291a37..8073a1f110631 100644 --- a/lib/SILGen/SILGenStmt.cpp +++ b/lib/SILGen/SILGenStmt.cpp @@ -743,9 +743,6 @@ void StmtEmitter::visitGuardStmt(GuardStmt *S) { // Emit the condition bindings, branching to the bodyBB if they fail. auto NumFalseTaken = SGF.loadProfilerCount(S->getBody()); auto NumNonTaken = SGF.loadProfilerCount(S); - // Begin a new 'guard' scope, which is popped when the next innermost debug - // scope ends. - SGF.enterDebugScope(S, /*isGuardScope=*/true); SGF.emitStmtCondition(S->getCond(), bodyBB, S, NumNonTaken, NumFalseTaken); } diff --git a/lib/SILGen/SwitchEnumBuilder.cpp b/lib/SILGen/SwitchEnumBuilder.cpp index 25ca9ac13b67b..bf309537aba60 100644 --- a/lib/SILGen/SwitchEnumBuilder.cpp +++ b/lib/SILGen/SwitchEnumBuilder.cpp @@ -137,6 +137,11 @@ void SwitchEnumBuilder::emit() && { // Don't allow cleanups to escape the conditional block. SwitchCaseFullExpr presentScope(builder.getSILGenFunction(), CleanupLocation(loc), branchDest); + // Begin a new binding scope, which is popped when the next innermost debug + // scope ends. The cleanup location loc isn't the perfect source location + // but it's close enough. + builder.getSILGenFunction().enterDebugScope(loc, + /*isBindingScope=*/true); builder.emitBlock(caseBlock); diff --git a/test/DebugInfo/guard-let-scope.swift b/test/DebugInfo/guard-let-scope.swift index 101deb04b89a5..88dcb18b748cf 100644 --- a/test/DebugInfo/guard-let-scope.swift +++ b/test/DebugInfo/guard-let-scope.swift @@ -3,7 +3,7 @@ func f(c: AnyObject?) { let x = c // CHECK: sil_scope [[S1:[0-9]+]] { {{.*}} parent @{{.*}}1f - // CHECK: sil_scope [[S2:[0-9]+]] { loc "{{.*}}":[[@LINE+3]]:3 parent [[S1]] } + // CHECK: sil_scope [[S2:[0-9]+]] { loc "{{.*}}":[[@LINE+3]]:17 parent [[S1]] } // CHECK: debug_value %{{.*}} : $Optional, let, name "x"{{.*}} scope [[S1]] // CHECK: debug_value %{{.*}} : $AnyObject, let, name "x", {{.*}} scope [[S2]] guard let x = x else { diff --git a/test/SILOptimizer/constantprop-wrongscope.swift b/test/SILOptimizer/constantprop-wrongscope.swift index 58f8402428182..12f9d62ba7709 100644 --- a/test/SILOptimizer/constantprop-wrongscope.swift +++ b/test/SILOptimizer/constantprop-wrongscope.swift @@ -12,10 +12,10 @@ // Make sure that the destroy_addr instruction has the same scope of the // instructions surrounding it. -// CHECK: destroy_addr %7 : $*Any, loc {{.*}}:22:19, scope 1 -// CHECK: dealloc_stack %12 : $*Optional, loc {{.*}}:22:23, scope 1 -// CHECK: dealloc_stack %7 : $*Any, loc {{.*}}:22:23, scope 1 -// CHECK: dealloc_stack %6 : $*A, loc {{.*}}:22:7, scope 1 +// CHECK: destroy_addr %7 : $*Any, loc {{.*}}:22:19, scope 2 +// CHECK: dealloc_stack %12 : $*Optional, loc {{.*}}:22:23, scope 2 +// CHECK: dealloc_stack %7 : $*Any, loc {{.*}}:22:23, scope 2 +// CHECK: dealloc_stack %6 : $*A, loc {{.*}}:22:7, scope 2 import Foundation func indexedSubscripting(b b: B, idx: Int, a: A) { diff --git a/test/SILOptimizer/definite-init-wrongscope.swift b/test/SILOptimizer/definite-init-wrongscope.swift index 5e905c69bdcd9..80118253f3c5d 100644 --- a/test/SILOptimizer/definite-init-wrongscope.swift +++ b/test/SILOptimizer/definite-init-wrongscope.swift @@ -33,14 +33,14 @@ public class M { // CHECK-LABEL: sil [ossa] @$s3del1MC4fromAcA12WithDelegate_p_tKcfc : $@convention(method) (@in WithDelegate, @owned M) -> (@owned M, @error Error) -// CHECK: [[I:%.*]] = integer_literal $Builtin.Int2, 1, loc {{.*}}:23:12, scope 2 -// CHECK: [[V:%.*]] = load [trivial] %2 : $*Builtin.Int2, loc {{.*}}:23:12, scope 2 -// CHECK: [[OR:%.*]] = builtin "or_Int2"([[V]] : $Builtin.Int2, [[I]] : $Builtin.Int2) : $Builtin.Int2, loc {{.*}}:23:12, scope 2 -// CHECK: store [[OR]] to [trivial] %2 : $*Builtin.Int2, loc {{.*}}:23:12, scope 2 -// CHECK: store %{{.*}} to [init] %{{.*}} : $*C, loc {{.*}}:26:20, scope 2 +// CHECK: [[I:%.*]] = integer_literal $Builtin.Int2, 1, loc {{.*}}:23:12, scope 4 +// CHECK: [[V:%.*]] = load [trivial] %2 : $*Builtin.Int2, loc {{.*}}:23:12, scope 4 +// CHECK: [[OR:%.*]] = builtin "or_Int2"([[V]] : $Builtin.Int2, [[I]] : $Builtin.Int2) : $Builtin.Int2, loc {{.*}}:23:12, scope 4 +// CHECK: store [[OR]] to [trivial] %2 : $*Builtin.Int2, loc {{.*}}:23:12, scope 4 +// CHECK: store %{{.*}} to [init] %{{.*}} : $*C, loc {{.*}}:26:20, scope 4 // Make sure the dealloc_stack gets the same scope of the instructions surrounding it. -// CHECK: destroy_addr %0 : $*WithDelegate, loc {{.*}}:29:5, scope 2 -// CHECK: dealloc_stack %2 : $*Builtin.Int2, loc {{.*}}:23:12, scope 2 +// CHECK: destroy_addr %0 : $*WithDelegate, loc {{.*}}:29:5, scope 4 +// CHECK: dealloc_stack %2 : $*Builtin.Int2, loc {{.*}}:23:12, scope 4 // CHECK: throw %{{.*}} : $Error, loc {{.*}}:23:12, scope 1 From 1ca692f46b5725268c1516ad9d87e3594561c088 Mon Sep 17 00:00:00 2001 From: Artem Chikin Date: Mon, 30 Aug 2021 17:24:04 -0700 Subject: [PATCH 076/116] [NFC] Adjust `driver-time-compilation.swift` to the new format of `llvm::Timer` Resolves rdar://81809942 --- test/Driver/driver-time-compilation.swift | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/test/Driver/driver-time-compilation.swift b/test/Driver/driver-time-compilation.swift index 78a7555d98fa6..f4e6d5963aec2 100644 --- a/test/Driver/driver-time-compilation.swift +++ b/test/Driver/driver-time-compilation.swift @@ -3,8 +3,11 @@ // CHECK: Driver Compilation Time // CHECK: Total Execution Time: {{[0-9]+}}.{{[0-9]+}} seconds ({{[0-9]+}}.{{[0-9]+}} wall clock) -// CHECK: ---Wall Time--- -// CHECK: --- Name --- -// CHECK: {compile: {{.*}}driver-time-compilation.swift} +// CHECK: ---User Time--- +// CHECK-SAME: --System Time-- +// CHECK-SAME: --User+System-- +// CHECK-SAME: ---Wall Time--- +// CHECK-SAME: ---Instr--- +// CHECK-SAME: --- Name --- // CHECK-MULTIPLE: {compile: {{.*}}empty.swift} -// CHECK: {{[0-9]+}}.{{[0-9]+}} (100.0%) Total +// CHECK: {{[0-9]+}}.{{[0-9]+}} (100.0%) {{[0-9]+}}.{{[0-9]+}} (100.0%) {{[0-9]+}}.{{[0-9]+}} (100.0%) {{[0-9]+}}.{{[0-9]+}} (100.0%) {{.*}} {compile: {{.*}}driver-time-compilation.swift} From e754f5a6c48c9298bec6965a3d28f2d5f6b18f9c Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Tue, 24 Aug 2021 15:52:10 -0700 Subject: [PATCH 077/116] Disable resilience for modules imported by the MemoryBuffer loader. The MemoryBuffer loader is used by LLDB during debugging to import binary Swift modules from .swift_ast sections. Modules imported from .swift_ast sections are never produced from textual interfaces. By disabling resilience the expression evaluator in the debugger can directly access private members. rdar://79462915 --- include/swift/AST/Module.h | 9 +++++ .../Serialization/SerializedModuleLoader.h | 13 +++++--- lib/AST/Decl.cpp | 2 +- lib/IRGen/GenDecl.cpp | 5 ++- lib/SIL/Verifier/SILVerifier.cpp | 33 ++++++++++++------- lib/Serialization/SerializedModuleLoader.cpp | 5 +++ 6 files changed, 48 insertions(+), 19 deletions(-) diff --git a/include/swift/AST/Module.h b/include/swift/AST/Module.h index a5efe092f93a1..6157864f06ef1 100644 --- a/include/swift/AST/Module.h +++ b/include/swift/AST/Module.h @@ -257,6 +257,9 @@ class ModuleDecl AccessNotesFile accessNotes; + /// Used by the debugger to bypass resilient access to fields. + bool BypassResilience = false; + ModuleDecl(Identifier name, ASTContext &ctx, ImplicitImportInfo importInfo); public: @@ -290,6 +293,12 @@ class ModuleDecl AccessNotesFile &getAccessNotes() { return accessNotes; } const AccessNotesFile &getAccessNotes() const { return accessNotes; } + /// Return whether the module was imported with resilience disabled. The + /// debugger does this to access private fields. + bool getBypassResilience() const { return BypassResilience; } + /// Only to be called by MemoryBufferSerializedModuleLoader. + void setBypassResilience() { BypassResilience = true; } + ArrayRef getFiles() { assert(!Files.empty() || failedToLoad()); return Files; diff --git a/include/swift/Serialization/SerializedModuleLoader.h b/include/swift/Serialization/SerializedModuleLoader.h index ad990cc375339..545860e30cec9 100644 --- a/include/swift/Serialization/SerializedModuleLoader.h +++ b/include/swift/Serialization/SerializedModuleLoader.h @@ -261,9 +261,11 @@ class MemoryBufferSerializedModuleLoader : public SerializedModuleLoaderBase { MemoryBufferSerializedModuleLoader(ASTContext &ctx, DependencyTracker *tracker, ModuleLoadingMode loadMode, - bool IgnoreSwiftSourceInfo) + bool IgnoreSwiftSourceInfo, + bool BypassResilience) : SerializedModuleLoaderBase(ctx, tracker, loadMode, - IgnoreSwiftSourceInfo) {} + IgnoreSwiftSourceInfo), + BypassResilience(BypassResilience) {} std::error_code findModuleFilesInDirectory( ImportPath::Element ModuleID, @@ -279,6 +281,7 @@ class MemoryBufferSerializedModuleLoader : public SerializedModuleLoaderBase { StringRef moduleName, const SerializedModuleBaseName &BaseName) override; + bool BypassResilience; public: virtual ~MemoryBufferSerializedModuleLoader(); @@ -308,10 +311,10 @@ class MemoryBufferSerializedModuleLoader : public SerializedModuleLoaderBase { static std::unique_ptr create(ASTContext &ctx, DependencyTracker *tracker = nullptr, ModuleLoadingMode loadMode = ModuleLoadingMode::PreferSerialized, - bool IgnoreSwiftSourceInfo = false) { + bool IgnoreSwiftSourceInfo = false, bool BypassResilience = false) { return std::unique_ptr{ - new MemoryBufferSerializedModuleLoader(ctx, tracker, loadMode, - IgnoreSwiftSourceInfo)}; + new MemoryBufferSerializedModuleLoader( + ctx, tracker, loadMode, IgnoreSwiftSourceInfo, BypassResilience)}; } }; diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index c85507d6093b0..61cc364bf7f4e 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -1879,7 +1879,7 @@ static bool isDirectToStorageAccess(const DeclContext *UseDC, // If the storage is resilient, we cannot access it directly at all. if (var->isResilient(UseDC->getParentModule(), UseDC->getResilienceExpansion())) - return false; + return var->getModuleContext()->getBypassResilience(); if (isa(AFD) || isa(AFD)) { // The access must also be a member access on 'self' in all language modes. diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp index 01807f942c61e..5da433a25802d 100644 --- a/lib/IRGen/GenDecl.cpp +++ b/lib/IRGen/GenDecl.cpp @@ -4968,7 +4968,10 @@ llvm::Constant *IRGenModule::getAddrOfGlobalUTF16String(StringRef utf8) { /// - For enums, new cases can be added /// - For classes, the superclass might change the size or number /// of stored properties -bool IRGenModule::isResilient(NominalTypeDecl *D, ResilienceExpansion expansion) { +bool IRGenModule::isResilient(NominalTypeDecl *D, + ResilienceExpansion expansion) { + if (D->getModuleContext()->getBypassResilience()) + return false; if (expansion == ResilienceExpansion::Maximal && Types.getLoweringMode() == TypeConverter::Mode::CompletelyFragile) { return false; diff --git a/lib/SIL/Verifier/SILVerifier.cpp b/lib/SIL/Verifier/SILVerifier.cpp index 3bfee7edca697..b718948e2bf2f 100644 --- a/lib/SIL/Verifier/SILVerifier.cpp +++ b/lib/SIL/Verifier/SILVerifier.cpp @@ -104,6 +104,15 @@ static bool isArchetypeValidInFunction(ArchetypeType *A, const SILFunction *F) { namespace { +/// When resilience is bypassed, direct access is legal, but the decls are still +/// resilient. +template +bool checkResilience(DeclType *D, ModuleDecl *M, + ResilienceExpansion expansion) { + return !D->getModuleContext()->getBypassResilience() && + D->isResilient(M, expansion); +} + /// Metaprogramming-friendly base class. template class SILVerifierBase : public SILInstructionVisitor { @@ -234,7 +243,7 @@ void verifyKeyPathComponent(SILModule &M, "property decl should be a member of the base with the same type " "as the component"); require(property->hasStorage(), "property must be stored"); - require(!property->isResilient(M.getSwiftModule(), expansion), + require(!checkResilience(property, M.getSwiftModule(), expansion), "cannot access storage of resilient property"); auto propertyTy = loweredBaseTy.getFieldType(property, M, typeExpansionContext); @@ -1970,7 +1979,7 @@ class SILVerifier : public SILVerifierBase { void checkAllocGlobalInst(AllocGlobalInst *AGI) { SILGlobalVariable *RefG = AGI->getReferencedGlobal(); if (auto *VD = RefG->getDecl()) { - require(!VD->isResilient(F.getModule().getSwiftModule(), + require(!checkResilience(VD, F.getModule().getSwiftModule(), F.getResilienceExpansion()), "cannot access storage of resilient global"); } @@ -1989,7 +1998,7 @@ class SILVerifier : public SILVerifierBase { RefG->getLoweredTypeInContext(F.getTypeExpansionContext()), "global_addr/value must be the type of the variable it references"); if (auto *VD = RefG->getDecl()) { - require(!VD->isResilient(F.getModule().getSwiftModule(), + require(!checkResilience(VD, F.getModule().getSwiftModule(), F.getResilienceExpansion()), "cannot access storage of resilient global"); } @@ -2677,8 +2686,8 @@ class SILVerifier : public SILVerifierBase { require(!structDecl->hasUnreferenceableStorage(), "Cannot build a struct with unreferenceable storage from elements " "using StructInst"); - require(!structDecl->isResilient(F.getModule().getSwiftModule(), - F.getResilienceExpansion()), + require(!checkResilience(structDecl, F.getModule().getSwiftModule(), + F.getResilienceExpansion()), "cannot access storage of resilient struct"); require(SI->getType().isObject(), "StructInst must produce an object"); @@ -2879,8 +2888,8 @@ class SILVerifier : public SILVerifierBase { require(cd, "Operand of dealloc_ref must be of class type"); if (!DI->canAllocOnStack()) { - require(!cd->isResilient(F.getModule().getSwiftModule(), - F.getResilienceExpansion()), + require(!checkResilience(cd, F.getModule().getSwiftModule(), + F.getResilienceExpansion()), "cannot directly deallocate resilient class"); } } @@ -2996,7 +3005,7 @@ class SILVerifier : public SILVerifierBase { "result of struct_extract cannot be address"); StructDecl *sd = operandTy.getStructOrBoundGenericStruct(); require(sd, "must struct_extract from struct"); - require(!sd->isResilient(F.getModule().getSwiftModule(), + require(!checkResilience(sd, F.getModule().getSwiftModule(), F.getResilienceExpansion()), "cannot access storage of resilient struct"); require(!EI->getField()->isStatic(), @@ -3045,7 +3054,7 @@ class SILVerifier : public SILVerifierBase { "must derive struct_element_addr from address"); StructDecl *sd = operandTy.getStructOrBoundGenericStruct(); require(sd, "struct_element_addr operand must be struct address"); - require(!sd->isResilient(F.getModule().getSwiftModule(), + require(!checkResilience(sd, F.getModule().getSwiftModule(), F.getResilienceExpansion()), "cannot access storage of resilient struct"); require(EI->getType().isAddress(), @@ -3078,7 +3087,7 @@ class SILVerifier : public SILVerifierBase { SILType operandTy = EI->getOperand()->getType(); ClassDecl *cd = operandTy.getClassOrBoundGenericClass(); require(cd, "ref_element_addr operand must be a class instance"); - require(!cd->isResilient(F.getModule().getSwiftModule(), + require(!checkResilience(cd, F.getModule().getSwiftModule(), F.getResilienceExpansion()), "cannot access storage of resilient class"); @@ -3102,7 +3111,7 @@ class SILVerifier : public SILVerifierBase { SILType operandTy = RTAI->getOperand()->getType(); ClassDecl *cd = operandTy.getClassOrBoundGenericClass(); require(cd, "ref_tail_addr operand must be a class instance"); - require(!cd->isResilient(F.getModule().getSwiftModule(), + require(!checkResilience(cd, F.getModule().getSwiftModule(), F.getResilienceExpansion()), "cannot access storage of resilient class"); require(cd, "ref_tail_addr operand must be a class instance"); @@ -3112,7 +3121,7 @@ class SILVerifier : public SILVerifierBase { SILType operandTy = DSI->getOperand()->getType(); StructDecl *sd = operandTy.getStructOrBoundGenericStruct(); require(sd, "must struct_extract from struct"); - require(!sd->isResilient(F.getModule().getSwiftModule(), + require(!checkResilience(sd, F.getModule().getSwiftModule(), F.getResilienceExpansion()), "cannot access storage of resilient struct"); if (F.hasOwnership()) { diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp index 5ba5de6eeebfc..1682ee21ef7cb 100644 --- a/lib/Serialization/SerializedModuleLoader.cpp +++ b/lib/Serialization/SerializedModuleLoader.cpp @@ -1205,6 +1205,11 @@ MemoryBufferSerializedModuleLoader::loadModule(SourceLoc importLoc, if (!file) return nullptr; + // The MemoryBuffer loader is used by LLDB during debugging. Modules imported + // from .swift_ast sections are never produced from textual interfaces. By + // disabling resilience the debugger can directly access private members. + if (BypassResilience) + M->setBypassResilience(); M->addFile(*file); Ctx.addLoadedModule(M); return M; From fe68662475d71d09f47c60437c9aa61a6b4164fc Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Tue, 31 Aug 2021 09:28:44 -0700 Subject: [PATCH 078/116] Revert "Fixup Coverage Mapping" This reverts commit 40e420641041912dfa970ae9d7e5fcc9eee29aa0. --- lib/IRGen/GenCoverage.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/IRGen/GenCoverage.cpp b/lib/IRGen/GenCoverage.cpp index b2b87ffa7239f..bdedf23c75619 100644 --- a/lib/IRGen/GenCoverage.cpp +++ b/lib/IRGen/GenCoverage.cpp @@ -68,10 +68,12 @@ void IRGenModule::emitCoverageMapping() { auto remapper = getOptions().CoveragePrefixMap; // Awkwardly munge absolute filenames into a vector of StringRefs. llvm::SmallVector FilenameStrs; + llvm::SmallVector FilenameRefs; for (StringRef Name : Files) { llvm::SmallString<256> Path(Name); llvm::sys::fs::make_absolute(Path); FilenameStrs.push_back(remapper.remapPath(Path)); + FilenameRefs.push_back(FilenameStrs.back()); } // Encode the filenames. @@ -79,7 +81,7 @@ void IRGenModule::emitCoverageMapping() { llvm::LLVMContext &Ctx = getLLVMContext(); { llvm::raw_string_ostream OS(Filenames); - llvm::coverage::CoverageFilenamesSectionWriter(FilenameStrs).write(OS); + llvm::coverage::CoverageFilenamesSectionWriter(FilenameRefs).write(OS); } auto *FilenamesVal = llvm::ConstantDataArray::getString(Ctx, Filenames, false); From ef9f6cbe54a1d8da1dbd389ab5b31c89ed4224a0 Mon Sep 17 00:00:00 2001 From: Vedant Kumar Date: Tue, 31 Aug 2021 15:41:04 -0700 Subject: [PATCH 079/116] Revert "Fixup Coverage Mapping" (#39117) This reverts commit 40e420641041912dfa970ae9d7e5fcc9eee29aa0, due to rdar://82543962. It should still remain in effect on next. --- lib/IRGen/GenCoverage.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/IRGen/GenCoverage.cpp b/lib/IRGen/GenCoverage.cpp index b2b87ffa7239f..bdedf23c75619 100644 --- a/lib/IRGen/GenCoverage.cpp +++ b/lib/IRGen/GenCoverage.cpp @@ -68,10 +68,12 @@ void IRGenModule::emitCoverageMapping() { auto remapper = getOptions().CoveragePrefixMap; // Awkwardly munge absolute filenames into a vector of StringRefs. llvm::SmallVector FilenameStrs; + llvm::SmallVector FilenameRefs; for (StringRef Name : Files) { llvm::SmallString<256> Path(Name); llvm::sys::fs::make_absolute(Path); FilenameStrs.push_back(remapper.remapPath(Path)); + FilenameRefs.push_back(FilenameStrs.back()); } // Encode the filenames. @@ -79,7 +81,7 @@ void IRGenModule::emitCoverageMapping() { llvm::LLVMContext &Ctx = getLLVMContext(); { llvm::raw_string_ostream OS(Filenames); - llvm::coverage::CoverageFilenamesSectionWriter(FilenameStrs).write(OS); + llvm::coverage::CoverageFilenamesSectionWriter(FilenameRefs).write(OS); } auto *FilenamesVal = llvm::ConstantDataArray::getString(Ctx, Filenames, false); From 284992beff415c2f19082bd133bda1cefae8b708 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Wed, 1 Sep 2021 11:20:51 -0700 Subject: [PATCH 080/116] Adapt testcase to upstream LLVM changes in coro::salvageDebugInfo --- test/DebugInfo/async-local-var.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/DebugInfo/async-local-var.swift b/test/DebugInfo/async-local-var.swift index aebc99aa98bb9..80f0d3ca46d1a 100644 --- a/test/DebugInfo/async-local-var.swift +++ b/test/DebugInfo/async-local-var.swift @@ -16,7 +16,7 @@ public func makeDinner() async throws -> String { // CHECK-LABEL: define {{.*}} void @"$s1a10makeDinnerSSyYaKFTQ0_" // CHECK-NEXT: entryresume.0: // CHECK-NOT: {{ ret }} -// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LOCAL:[0-9]+]], {{.*}}!DIExpression(DW_OP_plus_uconst +// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LOCAL:[0-9]+]], {{.*}}!DIExpression(DW_OP_deref, DW_OP_plus_uconst // CHECK: ![[LOCAL]] = !DILocalVariable(name: "local" return local } From 2a74582de4b286ef139e6e5170c8386023250862 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Wed, 1 Sep 2021 18:18:44 -0700 Subject: [PATCH 081/116] Update test for llvm change D109119 rdar://82037718 --- test/DebugInfo/async-args.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/DebugInfo/async-args.swift b/test/DebugInfo/async-args.swift index b7201d6e1d831..c287307b4eae2 100644 --- a/test/DebugInfo/async-args.swift +++ b/test/DebugInfo/async-args.swift @@ -10,10 +10,10 @@ func withGenericArg(_ msg: T) async { // This odd debug info is part of a contract with CoroSplit/CoroFrame to fix // this up after coroutine splitting. // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYalF"(%swift.context* swiftasync %0 - // CHECK: call void @llvm.dbg.declare(metadata %swift.type** % - // CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression() - // CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** % - // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression(DW_OP_deref)) + // CHECK: call void @llvm.dbg.declare(metadata %swift.context* %0 + // CHECK-SAME: metadata ![[MSG:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, {{.*}}DW_OP_deref)) + // CHECK: call void @llvm.dbg.declare(metadata %swift.context* %0 + // CHECK-SAME: metadata ![[TAU:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, await forceSplit() // CHECK-LABEL: {{^define .*}} @"$s1M14withGenericArgyyxYalFTQ0_"(i8* swiftasync %0) From 2bbea54dc0bf95d2622f71ecc3e100eff3a19183 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Fri, 3 Sep 2021 08:36:57 -0700 Subject: [PATCH 082/116] IRGen: Use llvm.compiler.used instead of llvm.used on ELF As of "ELF: Create unique SHF_GNU_RETAIN sections for llvm.used global objects" (https://reviews.llvm.org/D97448) LLVM will create separate sections for symbols marked as llvm.used. Use llvm.compiler.used instead. rdar://82681143 --- lib/IRGen/GenDecl.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp index 01807f942c61e..f2f33f29cb562 100644 --- a/lib/IRGen/GenDecl.cpp +++ b/lib/IRGen/GenDecl.cpp @@ -886,6 +886,15 @@ IRGenModule::getAddrOfParentContextDescriptor(DeclContext *from, /// /// This value must have a definition by the time the module is finalized. void IRGenModule::addUsedGlobal(llvm::GlobalValue *global) { + + // As of reviews.llvm.org/D97448 "ELF: Create unique SHF_GNU_RETAIN sections + // for llvm.used global objects" LLVM creates separate sections for globals in + // llvm.used on ELF. Therefore we use llvm.compiler.used on ELF instead. + if (TargetInfo.OutputObjectFormat == llvm::Triple::ELF) { + addCompilerUsedGlobal(global); + return; + } + LLVMUsed.push_back(global); } From b9de9a96ed89da459043554c10cf37d1d0baf264 Mon Sep 17 00:00:00 2001 From: Arnold Schwaighofer Date: Fri, 3 Sep 2021 11:17:57 -0700 Subject: [PATCH 083/116] Fix elf tests --- test/IRGen/autolink_elf.swift | 2 +- test/IRGen/objc_protocol_vars.sil | 5 +++-- test/IRGen/unused.sil | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/test/IRGen/autolink_elf.swift b/test/IRGen/autolink_elf.swift index 06caf06d81a47..df4a10dc4e0a5 100644 --- a/test/IRGen/autolink_elf.swift +++ b/test/IRGen/autolink_elf.swift @@ -10,5 +10,5 @@ import Empty // as used. // CHECK-DAG: @_swift1_autolink_entries = private constant [26 x i8] c"-lswiftEmpty\00-lanotherLib\00", section ".swift1_autolink_entries", align 8 -// CHECK-DAG: @llvm.used = appending global [{{.*}} x i8*] [{{.*}}i8* getelementptr inbounds ([26 x i8], [26 x i8]* @_swift1_autolink_entries, i32 0, i32 0){{.*}}], section "llvm.metadata" +// CHECK-DAG: @llvm.compiler.used = appending global [{{.*}} x i8*] [{{.*}}i8* getelementptr inbounds ([26 x i8], [26 x i8]* @_swift1_autolink_entries, i32 0, i32 0){{.*}}], section "llvm.metadata" diff --git a/test/IRGen/objc_protocol_vars.sil b/test/IRGen/objc_protocol_vars.sil index d3ac4b7822c78..7d00b48695916 100644 --- a/test/IRGen/objc_protocol_vars.sil +++ b/test/IRGen/objc_protocol_vars.sil @@ -1,4 +1,4 @@ -// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -parse-as-library -emit-ir %s | %FileCheck %s +// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -parse-as-library -emit-ir %s | %FileCheck %s --check-prefix=CHECK-%target-object-format // It tests whether the vars @"\01l_OBJC_LABEL_PROTOCOL_$__TtP18objc_protocol_vars1T_" // and @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP18objc_protocol_vars1T_" are in llvm.used. @@ -25,5 +25,6 @@ import Foundation @objc func clone() -> T } -// CHECK: @llvm.used = appending global [{{.*}}] [{{.*}}, i8* bitcast (i8** @"\01l_OBJC_LABEL_PROTOCOL_$__TtP18objc_protocol_vars1T_" to i8*), i8* bitcast (i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP18objc_protocol_vars1T_" to i8*), {{.*}}], {{.*}} +// CHECK-macho: @llvm.used = appending global [{{.*}}] [{{.*}}, i8* bitcast (i8** @"\01l_OBJC_LABEL_PROTOCOL_$__TtP18objc_protocol_vars1T_" to i8*), i8* bitcast (i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP18objc_protocol_vars1T_" to i8*), {{.*}}], {{.*}} +// CHECK-elf: @llvm.compiler.used = appending global [{{.*}}] [{{.*}}, i8* bitcast (i8** @"\01l_OBJC_LABEL_PROTOCOL_$__TtP18objc_protocol_vars1T_" to i8*), i8* bitcast (i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP18objc_protocol_vars1T_" to i8*), {{.*}}], {{.*}} diff --git a/test/IRGen/unused.sil b/test/IRGen/unused.sil index 52f0d14711662..7eb4e36e34575 100644 --- a/test/IRGen/unused.sil +++ b/test/IRGen/unused.sil @@ -56,7 +56,7 @@ bb0(%0 : $Int32, %1 : $UnsafeMutablePointer> // CHECK-elf: @"\01l_entry_point" = private constant { i32 } { i32 trunc (i64 sub (i64 ptrtoint (i32 (i32, i8**)* @main to i64), i64 ptrtoint ({ i32 }* @"\01l_entry_point" to i64)) to i32) }, section "swift5_entry", align 4 // CHECK-macho: @llvm.used = appending global [4 x i8*] [i8* bitcast (void ()* @frieda to i8*), i8* bitcast (i32 (i32, i8**)* @main to i8*), i8* bitcast ({ i32 }* @"\01l_entry_point" to i8*), i8* bitcast (i16* @__swift_reflection_version to i8*)], section "llvm.metadata" -// CHECK-elf: @llvm.used = appending global [5 x i8*] [i8* bitcast (void ()* @frieda to i8*), i8* bitcast (i32 (i32, i8**)* @main to i8*), i8* bitcast ({ i32 }* @"\01l_entry_point" to i8*), i8* bitcast (i16* @__swift_reflection_version to i8*), i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @_swift1_autolink_entries, i32 0, i32 0)], section "llvm.metadata" +// CHECK-elf: @llvm.compiler.used = appending global [5 x i8*] [i8* bitcast (void ()* @frieda to i8*), i8* bitcast (i32 (i32, i8**)* @main to i8*), i8* bitcast ({ i32 }* @"\01l_entry_point" to i8*), i8* bitcast (i16* @__swift_reflection_version to i8*), i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @_swift1_autolink_entries, i32 0, i32 0)], section "llvm.metadata" // CHECK: define linkonce_odr hidden swiftcc void @qux() // CHECK: define hidden swiftcc void @fred() From 06c409d324c50895a277fcb1384af62108e99261 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 3 Sep 2021 12:34:10 -0700 Subject: [PATCH 084/116] IRGenDebugInfo: Unique DILocalVariables. --- lib/IRGen/IRGenDebugInfo.cpp | 47 ++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index 61736a663a1cc..69b3f1f11b8ce 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -108,6 +108,9 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { /// Various caches. /// @{ + using SILVarScope = llvm::PointerUnion; + using VarID = std::tuple; + llvm::DenseMap LocalVarCache; llvm::DenseMap ScopeCache; llvm::DenseMap InlinedAtCache; llvm::DenseMap @@ -2437,15 +2440,18 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( if (!DbgTy.getSize()) DbgTy.setSize(getStorageSize(IGM.DataLayout, Storage)); + SILVarScope KeyScope = DS; auto *Scope = dyn_cast_or_null(getOrCreateScope(DS)); assert(Scope && "variable has no local scope"); auto DInstLoc = getStartLocation(DbgInstLoc); // FIXME: this should be the scope of the type's declaration. // If this is an argument, attach it to the current function scope. - if (VarInfo.ArgNo > 0) { + uint16_t ArgNo = VarInfo.ArgNo; + if (ArgNo > 0) { while (isa(Scope)) Scope = cast(Scope)->getScope(); + KeyScope = DS->getInlinedFunction(); } assert(isa_and_nonnull(Scope) && "variable has no scope"); llvm::DIFile *Unit = getFile(Scope); @@ -2457,16 +2463,13 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( unsigned DInstLine = DInstLoc.line; // Self is always an artificial argument, so are variables without location. - if (!DInstLine || - (VarInfo.ArgNo > 0 && VarInfo.Name == IGM.Context.Id_self.str())) + if (!DInstLine || (ArgNo > 0 && VarInfo.Name == IGM.Context.Id_self.str())) Artificial = ArtificialValue; llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; if (Artificial || DITy->isArtificial() || DITy == InternalType) Flags |= llvm::DINode::FlagArtificial; - // This could be Opts.Optimize if we would also unique DIVariables here. - bool Optimized = false; // Create the descriptor for the variable. unsigned DVarLine = DInstLine; if (VarInfo.Loc) { @@ -2474,21 +2477,33 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( DVarLine = DVarLoc.line; } llvm::DIScope *VarScope = Scope; - if (VarInfo.Scope) { + if (ArgNo == 0 && VarInfo.Scope) { if (auto *VS = dyn_cast_or_null( - getOrCreateScope(VarInfo.Scope))) + getOrCreateScope(VarInfo.Scope))) { VarScope = VS; + KeyScope = VarInfo.Scope; + } } - // The llvm.dbg.value(undef) emitted for zero-sized variables get filtered out - // by DwarfDebug::collectEntityInfo() otherwise. - bool Preserve = true; - llvm::DILocalVariable *Var = - (VarInfo.ArgNo > 0) - ? DBuilder.createParameterVariable(VarScope, VarInfo.Name, - VarInfo.ArgNo, Unit, DVarLine, - DITy, Preserve, Flags) - : DBuilder.createAutoVariable(VarScope, VarInfo.Name, Unit, DVarLine, + + // Get or create the DILocalVariable. + llvm::DILocalVariable *Var; + auto CachedVar = LocalVarCache.find({KeyScope, VarInfo.Name.data(), ArgNo}); + if (CachedVar != LocalVarCache.end()) { + Var = cast(CachedVar->second); + } else { + // The llvm.dbg.value(undef) emitted for zero-sized variables get filtered + // out by DwarfDebug::collectEntityInfo(), so all variables need to be + // preserved even at -Onone. + bool Preserve = true; + if (ArgNo > 0) + Var = DBuilder.createParameterVariable( + VarScope, VarInfo.Name, ArgNo, Unit, DVarLine, DITy, Preserve, Flags); + else + Var = DBuilder.createAutoVariable(VarScope, VarInfo.Name, Unit, DVarLine, DITy, Preserve, Flags); + LocalVarCache.insert( + {{KeyScope, VarInfo.Name.data(), ArgNo}, llvm::TrackingMDNodeRef(Var)}); + } auto appendDIExpression = [&VarInfo, this](llvm::DIExpression *DIExpr) -> llvm::DIExpression * { From 399a8b48646d09b5f3ed5ba10901df088b840401 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 3 Sep 2021 16:20:22 -0700 Subject: [PATCH 085/116] Fix build for older compilers --- lib/IRGen/IRGenDebugInfo.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index 69b3f1f11b8ce..d4505636b978e 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -2487,7 +2487,8 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( // Get or create the DILocalVariable. llvm::DILocalVariable *Var; - auto CachedVar = LocalVarCache.find({KeyScope, VarInfo.Name.data(), ArgNo}); + VarID Key(KeyScope, VarInfo.Name.data(), ArgNo); + auto CachedVar = LocalVarCache.find(Key); if (CachedVar != LocalVarCache.end()) { Var = cast(CachedVar->second); } else { @@ -2501,8 +2502,7 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( else Var = DBuilder.createAutoVariable(VarScope, VarInfo.Name, Unit, DVarLine, DITy, Preserve, Flags); - LocalVarCache.insert( - {{KeyScope, VarInfo.Name.data(), ArgNo}, llvm::TrackingMDNodeRef(Var)}); + LocalVarCache.insert({Key, llvm::TrackingMDNodeRef(Var)}); } auto appendDIExpression = From ea4a5685b931706fcb2af6e3581c4daf22f2979c Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 3 Sep 2021 12:34:51 -0700 Subject: [PATCH 086/116] Simplify code (NFC) --- lib/SILGen/SILGenProlog.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/SILGen/SILGenProlog.cpp b/lib/SILGen/SILGenProlog.cpp index 5203a03ffea0d..f9c2cf2334a2a 100644 --- a/lib/SILGen/SILGenProlog.cpp +++ b/lib/SILGen/SILGenProlog.cpp @@ -275,12 +275,11 @@ struct ArgumentInitHelper { // Emit debug information for the argument. SILLocation loc(PD); loc.markAsPrologue(); + SILDebugVariable DebugVar(PD->isLet(), ArgNo); if (argrv.getType().isAddress()) - SGF.B.createDebugValueAddr(loc, argrv.getValue(), - SILDebugVariable(PD->isLet(), ArgNo)); + SGF.B.createDebugValueAddr(loc, argrv.getValue(), DebugVar); else - SGF.B.createDebugValue(loc, argrv.getValue(), - SILDebugVariable(PD->isLet(), ArgNo)); + SGF.B.createDebugValue(loc, argrv.getValue(), DebugVar); } }; } // end anonymous namespace From 97b07f91cae158eebe9e4a9b0016d646e7d2c46b Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 3 Sep 2021 12:35:21 -0700 Subject: [PATCH 087/116] Delete unnecessary artificial debug function argument debug info. --- lib/SILOptimizer/Utils/InstOptUtils.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/SILOptimizer/Utils/InstOptUtils.cpp b/lib/SILOptimizer/Utils/InstOptUtils.cpp index 6716fa4bdf98b..6e9c7ccf61c56 100644 --- a/lib/SILOptimizer/Utils/InstOptUtils.cpp +++ b/lib/SILOptimizer/Utils/InstOptUtils.cpp @@ -1389,14 +1389,12 @@ static bool keepArgsOfPartialApplyAlive(PartialApplyInst *pai, for (Operand *argOp : argsToHandle) { SILValue arg = argOp->get(); - int argIdx = argOp->getOperandNumber() - pai->getArgumentOperandNumber(); - SILDebugVariable dbgVar(/*Constant*/ true, argIdx); SILValue tmp = arg; if (arg->getType().isAddress()) { // Move the value to a stack-allocated temporary. SILBuilderWithScope builder(pai, builderCtxt); - tmp = builder.createAllocStack(pai->getLoc(), arg->getType(), dbgVar); + tmp = builder.createAllocStack(pai->getLoc(), arg->getType()); builder.createCopyAddr(pai->getLoc(), arg, tmp, IsTake_t::IsTake, IsInitialization_t::IsInitialization); } From 6c996056fa77bb498c3980a7298d21f527c4beb6 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 3 Sep 2021 12:35:56 -0700 Subject: [PATCH 088/116] Assign variable names for anonymous function arguments in SILGen. Later stages use the name to disambiguate variables and this amgiguity can lead to incorrect debug info that crashes LLVM. This also makes the artificial variable names visible in textual SIL output. rdar://82313550 --- include/swift/SIL/SILInstruction.h | 14 +++--- lib/IRGen/IRGenSIL.cpp | 2 +- lib/SIL/IR/SILInstructions.cpp | 44 ++++++++++++------- lib/SIL/Verifier/SILVerifier.cpp | 5 ++- lib/SILGen/SILGenProlog.cpp | 6 +-- test/DebugInfo/anonymous.swift | 5 +++ test/DebugInfo/inout.swift | 5 +-- ...onformance_basic_conformances_future.swift | 2 +- 8 files changed, 50 insertions(+), 33 deletions(-) diff --git a/include/swift/SIL/SILInstruction.h b/include/swift/SIL/SILInstruction.h index 57991dc768e79..2d17b4e9f1ba7 100644 --- a/include/swift/SIL/SILInstruction.h +++ b/include/swift/SIL/SILInstruction.h @@ -1785,7 +1785,7 @@ class TailAllocatedDebugVariable { } Bits; public: TailAllocatedDebugVariable(Optional, char *buf, - SILType *AuxVarType = nullptr, + bool HasDeclName, SILType *AuxVarType = nullptr, SILLocation *DeclLoc = nullptr, const SILDebugScope **DeclScope = nullptr, SILDIExprElement *DIExprOps = nullptr); @@ -1810,13 +1810,11 @@ class TailAllocatedDebugVariable { if (!Bits.Data.HasValue) return None; - if (VD) - return SILDebugVariable(VD->getName().empty() ? "" : VD->getName().str(), - VD->isLet(), getArgNo(), isImplicit(), AuxVarType, - DeclLoc, DeclScope, DIExprElements); - else - return SILDebugVariable(getName(buf), isLet(), getArgNo(), isImplicit(), - AuxVarType, DeclLoc, DeclScope, DIExprElements); + StringRef name = getName(buf); + if (VD && name.empty()) + name = VD->getName().str(); + return SILDebugVariable(name, isLet(), getArgNo(), isImplicit(), AuxVarType, + DeclLoc, DeclScope, DIExprElements); } }; static_assert(sizeof(TailAllocatedDebugVariable) == 4, diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp index 4091fa5e2fe96..21a1afcf6b399 100644 --- a/lib/IRGen/IRGenSIL.cpp +++ b/lib/IRGen/IRGenSIL.cpp @@ -649,7 +649,7 @@ class IRGenSILFunction : if (Name.empty()) { { llvm::raw_svector_ostream S(Name); - S << '_' << NumAnonVars++; + S << "$_" << NumAnonVars++; } AnonymousVariables.insert({Decl, Name}); } diff --git a/lib/SIL/IR/SILInstructions.cpp b/lib/SIL/IR/SILInstructions.cpp index b0a656f5db9d0..fc8cd58ed6aec 100644 --- a/lib/SIL/IR/SILInstructions.cpp +++ b/lib/SIL/IR/SILInstructions.cpp @@ -127,14 +127,23 @@ static void *allocateDebugVarCarryingInst(SILModule &M, } TailAllocatedDebugVariable::TailAllocatedDebugVariable( - Optional Var, char *buf, SILType *AuxVarType, - SILLocation *DeclLoc, const SILDebugScope **DeclScope, + Optional Var, char *buf, bool HasDeclName, + SILType *AuxVarType, SILLocation *DeclLoc, const SILDebugScope **DeclScope, SILDIExprElement *DIExprOps) { if (!Var) { Bits.RawValue = 0; return; } + // Substitute anonymous function arguments with "_$ArgNo". This is an odd + // function to do this, but because SILDebugVariable uses a StringRef for Name + // there isn't really a better one. + llvm::SmallString<4> Name; + if (!HasDeclName && Var->Name.size() == 0 && Var->ArgNo) { + llvm::raw_svector_ostream(Name) << '_' << (Var->ArgNo - 1); + Var->Name = Name; + } + Bits.Data.HasValue = true; Bits.Data.Constant = Var->Constant; Bits.Data.ArgNo = Var->ArgNo; @@ -202,14 +211,15 @@ AllocStackInst::AllocStackInst(SILDebugLocation Loc, SILType elementType, TypeDependentOperands.size(); assert(SILNode::Bits.AllocStackInst.NumOperands == TypeDependentOperands.size() && "Truncation"); + auto *VD = Loc.getLocation().getAsASTNode(); SILNode::Bits.AllocStackInst.VarInfo = - TailAllocatedDebugVariable(Var, getTrailingObjects(), - getTrailingObjects(), - getTrailingObjects(), - getTrailingObjects(), - getTrailingObjects()) + TailAllocatedDebugVariable( + Var, getTrailingObjects(), VD ? !VD->getName().empty() : false, + getTrailingObjects(), getTrailingObjects(), + getTrailingObjects(), + getTrailingObjects()) .getRawValue(); - if (auto *VD = Loc.getLocation().getAsASTNode()) { + if (Var && VD) { TailAllocatedDebugVariable DbgVar(SILNode::Bits.AllocStackInst.VarInfo); DbgVar.setImplicit(VD->isImplicit() || DbgVar.isImplicit()); SILNode::Bits.AllocStackInst.VarInfo = DbgVar.getRawValue(); @@ -305,15 +315,19 @@ AllocRefDynamicInst::create(SILDebugLocation DebugLoc, SILFunction &F, AllocRefDynamicInst(DebugLoc, ty, objc, ElementTypes, AllOperands); } +static bool hasDeclName(SILDebugLocation Loc) { + auto *VD = Loc.getLocation().getAsASTNode(); + return VD ? !VD->getName().empty() : false; +} + AllocBoxInst::AllocBoxInst(SILDebugLocation Loc, CanSILBoxType BoxType, ArrayRef TypeDependentOperands, SILFunction &F, Optional Var, bool hasDynamicLifetime) - : InstructionBaseWithTrailingOperands(TypeDependentOperands, Loc, - SILType::getPrimitiveObjectType(BoxType)), - VarInfo(Var, getTrailingObjects()), - dynamicLifetime(hasDynamicLifetime) { -} + : InstructionBaseWithTrailingOperands( + TypeDependentOperands, Loc, SILType::getPrimitiveObjectType(BoxType)), + VarInfo(Var, getTrailingObjects(), hasDeclName(Loc)), + dynamicLifetime(hasDynamicLifetime) {} AllocBoxInst *AllocBoxInst::create(SILDebugLocation Loc, CanSILBoxType BoxType, @@ -341,8 +355,8 @@ DebugValueInst::DebugValueInst(SILDebugLocation DebugLoc, SILValue Operand, SILDebugVariableSupplement(Var.DIExpr.getNumElements(), Var.Type.hasValue(), Var.Loc.hasValue(), Var.Scope), - VarInfo(Var, getTrailingObjects(), getTrailingObjects(), - getTrailingObjects(), + VarInfo(Var, getTrailingObjects(), hasDeclName(DebugLoc), + getTrailingObjects(), getTrailingObjects(), getTrailingObjects(), getTrailingObjects()) { if (auto *VD = DebugLoc.getLocation().getAsASTNode()) diff --git a/lib/SIL/Verifier/SILVerifier.cpp b/lib/SIL/Verifier/SILVerifier.cpp index b6ce63c36c3d4..1a2bb3691a3a7 100644 --- a/lib/SIL/Verifier/SILVerifier.cpp +++ b/lib/SIL/Verifier/SILVerifier.cpp @@ -1224,6 +1224,8 @@ class SILVerifier : public SILVerifierBase { return; auto *debugScope = inst->getDebugScope(); + if (varInfo->ArgNo) + require(!varInfo->Name.empty(), "function argument without a name"); // Check that there is at most one debug variable defined for each argument // slot if our debug scope is not an inlined call site. @@ -1234,8 +1236,7 @@ class SILVerifier : public SILVerifierBase { if (debugScope && !debugScope->InlinedCallSite) if (unsigned argNum = varInfo->ArgNo) { // It is a function argument. - if (argNum < DebugVars.size() && !DebugVars[argNum].empty() && - !varInfo->Name.empty()) { + if (argNum < DebugVars.size() && !DebugVars[argNum].empty()) { require(DebugVars[argNum] == varInfo->Name, "Scope contains conflicting debug variables for one function " "argument"); diff --git a/lib/SILGen/SILGenProlog.cpp b/lib/SILGen/SILGenProlog.cpp index f9c2cf2334a2a..c3a8a3984a405 100644 --- a/lib/SILGen/SILGenProlog.cpp +++ b/lib/SILGen/SILGenProlog.cpp @@ -363,7 +363,7 @@ static void emitCaptureArguments(SILGenFunction &SGF, if (auto *AllocStack = dyn_cast(val)) AllocStack->setArgNo(ArgNo); else { - SILDebugVariable DbgVar(/*Constant*/ true, ArgNo); + SILDebugVariable DbgVar(VD->isLet(), ArgNo); SGF.B.createDebugValue(Loc, val, DbgVar); } @@ -388,7 +388,7 @@ static void emitCaptureArguments(SILGenFunction &SGF, SILType::getPrimitiveObjectType(boxTy), VD); SILValue addr = SGF.B.createProjectBox(VD, box, 0); SGF.VarLocs[VD] = SILGenFunction::VarLoc::get(addr, box); - SILDebugVariable DbgVar(/*Constant*/ false, ArgNo); + SILDebugVariable DbgVar(VD->isLet(), ArgNo); SGF.B.createDebugValueAddr(Loc, addr, DbgVar); break; } @@ -399,7 +399,7 @@ static void emitCaptureArguments(SILGenFunction &SGF, SILType ty = SGF.getLoweredType(type).getAddressType(); SILValue addr = SGF.F.begin()->createFunctionArgument(ty, VD); SGF.VarLocs[VD] = SILGenFunction::VarLoc::get(addr); - SILDebugVariable DbgVar(/*Constant*/ true, ArgNo); + SILDebugVariable DbgVar(VD->isLet(), ArgNo); SGF.B.createDebugValueAddr(Loc, addr, DbgVar); break; } diff --git a/test/DebugInfo/anonymous.swift b/test/DebugInfo/anonymous.swift index c1734d9ad9311..21fa079f41be3 100644 --- a/test/DebugInfo/anonymous.swift +++ b/test/DebugInfo/anonymous.swift @@ -1,5 +1,10 @@ +// RUN: %target-swift-frontend %s -emit-sil -g -o - | %FileCheck --check-prefix=SIL %s // RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | %FileCheck %s +// SIL: debug_value %1 : $*T, let, name "_0", argno 1, expr op_deref +// SIL: debug_value %2 : $*T, let, name "_1", argno 2, expr op_deref +// SIL: debug_value %3 : $*T, let, name "_2", argno 3, expr op_deref +// SIL: debug_value %4 : $*T, let, name "x4", argno 4, expr op_deref // CHECK: !DILocalVariable(name: "_0", arg: 1 // CHECK: !DILocalVariable(name: "_1", arg: 2 // CHECK: !DILocalVariable(name: "_2", arg: 3 diff --git a/test/DebugInfo/inout.swift b/test/DebugInfo/inout.swift index 8ebc2b6d0796c..2a92bbeedd353 100644 --- a/test/DebugInfo/inout.swift +++ b/test/DebugInfo/inout.swift @@ -18,9 +18,8 @@ typealias MyFloat = Float // PROMO-CHECK: call void @llvm.dbg.declare(metadata %Ts5Int64V** % // PROMO-CHECK-SAME: metadata ![[A1:[0-9]+]], metadata !DIExpression(DW_OP_deref)) -// PROMO-CHECK-DAG: ![[INT:.*]] = !DICompositeType({{.*}}identifier: "$ss5Int64VD" -// PROMO-CHECK: ![[A1]] = !DILocalVariable(name: "a", arg: 1 -// PROMO-CHECK-SAME: type: ![[INT]] +// PROMO-CHECK: ![[INT:.*]] = !DICompositeType({{.*}}identifier: "$ss5Int64VD" +// PROMO-CHECK: ![[A1]] = !DILocalVariable(name: "a", arg: 1,{{.*}} type: ![[INT]] func modifyFooHeap(_ a: inout Int64, // CHECK-DAG: ![[A]] = !DILocalVariable(name: "a", arg: 1{{.*}} line: [[@LINE-1]],{{.*}} type: ![[RINT:[0-9]+]] // CHECK-DAG: ![[RINT]] = !DICompositeType({{.*}}identifier: "$ss5Int64VD" diff --git a/test/Inputs/conditional_conformance_basic_conformances_future.swift b/test/Inputs/conditional_conformance_basic_conformances_future.swift index 9f6d5cc683bec..9f77ec8d419d7 100644 --- a/test/Inputs/conditional_conformance_basic_conformances_future.swift +++ b/test/Inputs/conditional_conformance_basic_conformances_future.swift @@ -311,7 +311,7 @@ public func double_generic_concrete(_: X.Type) { // CHECK-SAME: @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlMc" // CHECK-SAME: to %swift.protocol_conformance_descriptor* // CHECK-SAME: ), -// CHECK-SAME: %swift.type* %2, +// CHECK-SAME: %swift.type* %3, // CHECK-SAME: i8*** [[CONDITIONAL_REQUIREMENTS]] // CHECK-SAME: ) From 2673256a0caaceca714deb1d3a2bed3454e45e79 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Sat, 4 Sep 2021 09:45:17 -0700 Subject: [PATCH 089/116] Remove spurious anonymous function arguments introduced by PartialApplyCombiner. Looks like this was a well-intentioned, but counterproductive attempt to introduce new debug info in for partial applies. SILVerifier is now stricter about finding clashing anonymous arguments so this becomes a SIL verifier error rather than a late LLVM crash. --- lib/SILOptimizer/Utils/PartialApplyCombiner.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/SILOptimizer/Utils/PartialApplyCombiner.cpp b/lib/SILOptimizer/Utils/PartialApplyCombiner.cpp index cbc9ff8ee9e82..3c81442b9e0cf 100644 --- a/lib/SILOptimizer/Utils/PartialApplyCombiner.cpp +++ b/lib/SILOptimizer/Utils/PartialApplyCombiner.cpp @@ -98,16 +98,13 @@ bool PartialApplyCombiner::copyArgsToTemporaries( for (Operand *argOp : argsToHandle) { SILValue arg = argOp->get(); - int argIdx = ApplySite(pai).getAppliedArgIndex(*argOp); - SILDebugVariable dbgVar(/*Constant*/ true, argIdx); - SILValue tmp = arg; SILBuilderWithScope builder(pai, builderCtxt); if (arg->getType().isObject()) { tmp = builder.emitCopyValueOperation(pai->getLoc(), arg); } else { // Copy address-arguments into a stack-allocated temporary. - tmp = builder.createAllocStack(pai->getLoc(), arg->getType(), dbgVar); + tmp = builder.createAllocStack(pai->getLoc(), arg->getType()); builder.createCopyAddr(pai->getLoc(), arg, tmp, IsTake_t::IsNotTake, IsInitialization_t::IsInitialization); } From 259480a7d01a0e84c1931a6faeac74dec242ed92 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Sat, 4 Sep 2021 17:16:01 -0700 Subject: [PATCH 090/116] Update debuginfo tests for slightly shuffled i386 output --- test/DebugInfo/ErrorVar.swift | 6 ++---- test/DebugInfo/Errors.swift | 5 ++--- test/DebugInfo/async-let-await.swift | 2 +- test/DebugInfo/async-local-var.swift | 2 +- 4 files changed, 6 insertions(+), 9 deletions(-) diff --git a/test/DebugInfo/ErrorVar.swift b/test/DebugInfo/ErrorVar.swift index ca921180dce4a..bc186ac95c125 100644 --- a/test/DebugInfo/ErrorVar.swift +++ b/test/DebugInfo/ErrorVar.swift @@ -17,10 +17,8 @@ func simple(_ placeholder: Int64) throws -> () { // CHECK-SAME: %swift.error** noalias nocapture dereferenceable(4) // CHECK: call void @llvm.dbg.declare // CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[ERROR:[0-9]+]], metadata !DIExpression(DW_OP_deref)) - // CHECK: ![[ERRTY:.*]] = !DICompositeType({{.*}}identifier: "$ss5Error_pD" - // CHECK: ![[ERROR]] = !DILocalVariable(name: "$error", arg: 2, - // CHECK-SAME: type: ![[ERRTY]], - // CHECK-SAME: flags: DIFlagArtificial) + // CHECK-DAG: ![[ERRTY:.*]] = !DICompositeType({{.*}}identifier: "$ss5Error_pD" + // CHECK-DAG: ![[ERROR]] = !DILocalVariable(name: "$error", arg: 2, {{.*}}, type: ![[ERRTY]], flags: DIFlagArtificial) throw MyError.Simple } diff --git a/test/DebugInfo/Errors.swift b/test/DebugInfo/Errors.swift index 819873042da78..ffe704a1a8678 100644 --- a/test/DebugInfo/Errors.swift +++ b/test/DebugInfo/Errors.swift @@ -4,9 +4,8 @@ public enum E : Error { case Err } // Function throws. public func throwError() throws { throw E.Err } // CHECK: !DISubprogram(name: "throwError", {{.*}}thrownTypes: ![[THROWN:.*]]) -// CHECK: ![[THROWN]] = !{![[ERROR:[0-9]+]]} -// CHECK: ![[ERROR]] = !DICompositeType(tag: DW_TAG_structure_type, -// CHECK-SAME: name: "Error" +// CHECK-DAG: ![[THROWN]] = !{![[ERROR:[0-9]+]]} +// CHECK-DAG: ![[ERROR]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Error" // Function rethrows. diff --git a/test/DebugInfo/async-let-await.swift b/test/DebugInfo/async-let-await.swift index 15a85e1b61568..5c71c22a4a7d4 100644 --- a/test/DebugInfo/async-let-await.swift +++ b/test/DebugInfo/async-let-await.swift @@ -11,7 +11,7 @@ public func getVegetables() async -> [String] { public func chopVegetables() async throws -> [String] { let veggies = await getVegetables() // CHECK-NOT: {{^define }} - // CHECK: call void @llvm.dbg.declare(metadata i8* %0, metadata ![[V:[0-9]+]], metadata !DIExpression( + // CHECK: call void @llvm.dbg.declare(metadata i8* %0, metadata ![[V:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_plus_uconst, {{[0-9]+}}) // CHECK: ![[V]] = !DILocalVariable(name: "veggies" return veggies.map { "chopped \($0)" } } diff --git a/test/DebugInfo/async-local-var.swift b/test/DebugInfo/async-local-var.swift index 80f0d3ca46d1a..27c69b75db824 100644 --- a/test/DebugInfo/async-local-var.swift +++ b/test/DebugInfo/async-local-var.swift @@ -16,7 +16,7 @@ public func makeDinner() async throws -> String { // CHECK-LABEL: define {{.*}} void @"$s1a10makeDinnerSSyYaKFTQ0_" // CHECK-NEXT: entryresume.0: // CHECK-NOT: {{ ret }} -// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LOCAL:[0-9]+]], {{.*}}!DIExpression(DW_OP_deref, DW_OP_plus_uconst +// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LOCAL:[0-9]+]], {{.*}}!DIExpression(DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}) // CHECK: ![[LOCAL]] = !DILocalVariable(name: "local" return local } From 6fe11e3430bf6826f4a9b9bf5fb668001e161f73 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Tue, 7 Sep 2021 18:50:37 -0700 Subject: [PATCH 091/116] Fix a buffer overflow when substituting anonymous function arguments in SILBuilder. The size buffer is determined outside of TailAllocatedDebugVariable so of course the substitution must take place outside, too. --- include/swift/SIL/SILBuilder.h | 27 ++++++++++++++++++++---- include/swift/SIL/SILInstruction.h | 2 +- lib/SIL/IR/SILBuilder.cpp | 13 +++++++----- lib/SIL/IR/SILInstructions.cpp | 34 +++++++++--------------------- 4 files changed, 42 insertions(+), 34 deletions(-) diff --git a/include/swift/SIL/SILBuilder.h b/include/swift/SIL/SILBuilder.h index 42c4bba51d8e8..a4ee48c4bdee3 100644 --- a/include/swift/SIL/SILBuilder.h +++ b/include/swift/SIL/SILBuilder.h @@ -363,15 +363,32 @@ class SILBuilder { // SILInstruction Creation Methods //===--------------------------------------------------------------------===// + /// Substitute anonymous function arguments with "_$ArgNo". + Optional + substituteAnonymousArgs(llvm::SmallString<4> Name, + Optional Var, SILLocation Loc) { + if (!Var || !Var->ArgNo || !Var->Name.empty()) + return Var; + + auto *VD = Loc.getAsASTNode(); + if (VD && !VD->getName().empty()) + return Var; + + llvm::raw_svector_ostream(Name) << '_' << (Var->ArgNo - 1); + Var->Name = Name; + return Var; + } + AllocStackInst *createAllocStack(SILLocation Loc, SILType elementType, Optional Var = None, bool hasDynamicLifetime = false) { + llvm::SmallString<4> Name; Loc.markAsPrologue(); assert((!dyn_cast_or_null(Loc.getAsASTNode()) || Var) && "location is a VarDecl, but SILDebugVariable is empty"); - return insert(AllocStackInst::create(getSILDebugLocation(Loc), elementType, - getFunction(), - Var, hasDynamicLifetime)); + return insert(AllocStackInst::create( + getSILDebugLocation(Loc), elementType, getFunction(), + substituteAnonymousArgs(Name, Var, Loc), hasDynamicLifetime)); } AllocRefInst *createAllocRef(SILLocation Loc, SILType ObjectType, @@ -407,11 +424,13 @@ class SILBuilder { AllocBoxInst *createAllocBox(SILLocation Loc, CanSILBoxType BoxType, Optional Var = None, bool hasDynamicLifetime = false) { + llvm::SmallString<4> Name; Loc.markAsPrologue(); assert((!dyn_cast_or_null(Loc.getAsASTNode()) || Var) && "location is a VarDecl, but SILDebugVariable is empty"); return insert(AllocBoxInst::create(getSILDebugLocation(Loc), BoxType, *F, - Var, hasDynamicLifetime)); + substituteAnonymousArgs(Name, Var, Loc), + hasDynamicLifetime)); } AllocExistentialBoxInst * diff --git a/include/swift/SIL/SILInstruction.h b/include/swift/SIL/SILInstruction.h index 2d17b4e9f1ba7..d27fe8e96ac6f 100644 --- a/include/swift/SIL/SILInstruction.h +++ b/include/swift/SIL/SILInstruction.h @@ -1785,7 +1785,7 @@ class TailAllocatedDebugVariable { } Bits; public: TailAllocatedDebugVariable(Optional, char *buf, - bool HasDeclName, SILType *AuxVarType = nullptr, + SILType *AuxVarType = nullptr, SILLocation *DeclLoc = nullptr, const SILDebugScope **DeclScope = nullptr, SILDIExprElement *DIExprOps = nullptr); diff --git a/lib/SIL/IR/SILBuilder.cpp b/lib/SIL/IR/SILBuilder.cpp index 5d8b5071b01b1..b5618a3ab175e 100644 --- a/lib/SIL/IR/SILBuilder.cpp +++ b/lib/SIL/IR/SILBuilder.cpp @@ -569,20 +569,23 @@ void SILBuilder::emitDestructureValueOperation( DebugValueInst *SILBuilder::createDebugValue(SILLocation Loc, SILValue src, SILDebugVariable Var, bool poisonRefs) { + llvm::SmallString<4> Name; // Debug location overrides cannot apply to debug value instructions. DebugLocOverrideRAII LocOverride{*this, None}; - return insert( - DebugValueInst::create(getSILDebugLocation(Loc), src, getModule(), Var, - poisonRefs)); + return insert(DebugValueInst::create( + getSILDebugLocation(Loc), src, getModule(), + *substituteAnonymousArgs(Name, Var, Loc), poisonRefs)); } DebugValueInst *SILBuilder::createDebugValueAddr(SILLocation Loc, SILValue src, SILDebugVariable Var) { + llvm::SmallString<4> Name; // Debug location overrides cannot apply to debug addr instructions. DebugLocOverrideRAII LocOverride{*this, None}; - return insert(DebugValueInst::createAddr(getSILDebugLocation(Loc), src, - getModule(), Var)); + return insert( + DebugValueInst::createAddr(getSILDebugLocation(Loc), src, getModule(), + *substituteAnonymousArgs(Name, Var, Loc))); } void SILBuilder::emitScopedBorrowOperation(SILLocation loc, SILValue original, diff --git a/lib/SIL/IR/SILInstructions.cpp b/lib/SIL/IR/SILInstructions.cpp index fc8cd58ed6aec..9ac797fd16ee0 100644 --- a/lib/SIL/IR/SILInstructions.cpp +++ b/lib/SIL/IR/SILInstructions.cpp @@ -127,23 +127,14 @@ static void *allocateDebugVarCarryingInst(SILModule &M, } TailAllocatedDebugVariable::TailAllocatedDebugVariable( - Optional Var, char *buf, bool HasDeclName, - SILType *AuxVarType, SILLocation *DeclLoc, const SILDebugScope **DeclScope, + Optional Var, char *buf, SILType *AuxVarType, + SILLocation *DeclLoc, const SILDebugScope **DeclScope, SILDIExprElement *DIExprOps) { if (!Var) { Bits.RawValue = 0; return; } - // Substitute anonymous function arguments with "_$ArgNo". This is an odd - // function to do this, but because SILDebugVariable uses a StringRef for Name - // there isn't really a better one. - llvm::SmallString<4> Name; - if (!HasDeclName && Var->Name.size() == 0 && Var->ArgNo) { - llvm::raw_svector_ostream(Name) << '_' << (Var->ArgNo - 1); - Var->Name = Name; - } - Bits.Data.HasValue = true; Bits.Data.Constant = Var->Constant; Bits.Data.ArgNo = Var->ArgNo; @@ -213,11 +204,11 @@ AllocStackInst::AllocStackInst(SILDebugLocation Loc, SILType elementType, TypeDependentOperands.size() && "Truncation"); auto *VD = Loc.getLocation().getAsASTNode(); SILNode::Bits.AllocStackInst.VarInfo = - TailAllocatedDebugVariable( - Var, getTrailingObjects(), VD ? !VD->getName().empty() : false, - getTrailingObjects(), getTrailingObjects(), - getTrailingObjects(), - getTrailingObjects()) + TailAllocatedDebugVariable(Var, getTrailingObjects(), + getTrailingObjects(), + getTrailingObjects(), + getTrailingObjects(), + getTrailingObjects()) .getRawValue(); if (Var && VD) { TailAllocatedDebugVariable DbgVar(SILNode::Bits.AllocStackInst.VarInfo); @@ -315,18 +306,13 @@ AllocRefDynamicInst::create(SILDebugLocation DebugLoc, SILFunction &F, AllocRefDynamicInst(DebugLoc, ty, objc, ElementTypes, AllOperands); } -static bool hasDeclName(SILDebugLocation Loc) { - auto *VD = Loc.getLocation().getAsASTNode(); - return VD ? !VD->getName().empty() : false; -} - AllocBoxInst::AllocBoxInst(SILDebugLocation Loc, CanSILBoxType BoxType, ArrayRef TypeDependentOperands, SILFunction &F, Optional Var, bool hasDynamicLifetime) : InstructionBaseWithTrailingOperands( TypeDependentOperands, Loc, SILType::getPrimitiveObjectType(BoxType)), - VarInfo(Var, getTrailingObjects(), hasDeclName(Loc)), + VarInfo(Var, getTrailingObjects()), dynamicLifetime(hasDynamicLifetime) {} AllocBoxInst *AllocBoxInst::create(SILDebugLocation Loc, @@ -355,8 +341,8 @@ DebugValueInst::DebugValueInst(SILDebugLocation DebugLoc, SILValue Operand, SILDebugVariableSupplement(Var.DIExpr.getNumElements(), Var.Type.hasValue(), Var.Loc.hasValue(), Var.Scope), - VarInfo(Var, getTrailingObjects(), hasDeclName(DebugLoc), - getTrailingObjects(), getTrailingObjects(), + VarInfo(Var, getTrailingObjects(), getTrailingObjects(), + getTrailingObjects(), getTrailingObjects(), getTrailingObjects()) { if (auto *VD = DebugLoc.getLocation().getAsASTNode()) From f6505bccf6445ff19557312efeef4970913df6ad Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Wed, 8 Sep 2021 13:09:06 -0700 Subject: [PATCH 092/116] Remove assertion. The LLDB testsuite on Apple Silicon hits this code path. --- stdlib/public/Reflection/TypeRef.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/stdlib/public/Reflection/TypeRef.cpp b/stdlib/public/Reflection/TypeRef.cpp index d89dae57cccc4..3304229699b01 100644 --- a/stdlib/public/Reflection/TypeRef.cpp +++ b/stdlib/public/Reflection/TypeRef.cpp @@ -784,7 +784,6 @@ class DemanglingForTypeRef Demangle::NodePointer visitGenericTypeParameterTypeRef(const GenericTypeParameterTypeRef *GTP) { - assert(false && "not tested"); auto node = Dem.createNode(Node::Kind::DependentGenericParamType); node->addChild(Dem.createNode(Node::Kind::Index, GTP->getDepth()), Dem); node->addChild(Dem.createNode(Node::Kind::Index, GTP->getIndex()), Dem); @@ -793,7 +792,6 @@ class DemanglingForTypeRef Demangle::NodePointer visitDependentMemberTypeRef(const DependentMemberTypeRef *DM) { - assert(false && "not tested"); assert(DM->getProtocol().empty() && "not implemented"); auto node = Dem.createNode(Node::Kind::DependentMemberType); node->addChild(visit(DM->getBase()), Dem); From 656a91777a7da0ceee3a07bf6c2bd2c0a5465e2f Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 8 Sep 2021 15:44:51 -0700 Subject: [PATCH 093/116] Disabling driver-time-compilation test This test is pretty brittle on such a short file. If a member of the timer output is zero, that member is omitted from the output. With how short the file is, various fields come back zero occasionally. On the Linux CI bot, there was a run with no "System Time", while I was seeing it failing locally due to other missing time fields. --- test/Driver/driver-time-compilation.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/Driver/driver-time-compilation.swift b/test/Driver/driver-time-compilation.swift index f4e6d5963aec2..faca856df18f3 100644 --- a/test/Driver/driver-time-compilation.swift +++ b/test/Driver/driver-time-compilation.swift @@ -1,6 +1,8 @@ // RUN: %target-build-swift -typecheck -driver-time-compilation %s 2>&1 | %FileCheck %s // RUN: %target-build-swift -typecheck -driver-time-compilation %s %S/../Inputs/empty.swift 2>&1 | %FileCheck -check-prefix CHECK-MULTIPLE %s +// REQUIRES: rdar82895550 + // CHECK: Driver Compilation Time // CHECK: Total Execution Time: {{[0-9]+}}.{{[0-9]+}} seconds ({{[0-9]+}}.{{[0-9]+}} wall clock) // CHECK: ---User Time--- From ece59c4718600bc89b5e0cb32587d21ad4a9775e Mon Sep 17 00:00:00 2001 From: Min-Yih Hsu Date: Thu, 2 Sep 2021 14:23:59 -0700 Subject: [PATCH 094/116] (Stash) Add in-memory representation, parsing and printing --- include/swift/SIL/SILDebugInfoExpression.h | 36 ++++++++++++-- lib/SIL/IR/SILDebugInfoExpression.cpp | 8 ++- lib/SIL/IR/SILPrinter.cpp | 57 ++++++++++++++-------- lib/SIL/Parser/ParseSIL.cpp | 23 ++++++++- test/DebugInfo/debug_info_expression.sil | 25 +++++++++- 5 files changed, 121 insertions(+), 28 deletions(-) diff --git a/include/swift/SIL/SILDebugInfoExpression.h b/include/swift/SIL/SILDebugInfoExpression.h index c5d9b42f24912..84a7c2ac59db1 100644 --- a/include/swift/SIL/SILDebugInfoExpression.h +++ b/include/swift/SIL/SILDebugInfoExpression.h @@ -18,6 +18,7 @@ #ifndef SWIFT_SIL_DEBUGINFOEXPRESSION_H #define SWIFT_SIL_DEBUGINFOEXPRESSION_H #include "swift/AST/Decl.h" +#include "llvm/ADT/APInt.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/iterator_range.h" @@ -36,17 +37,30 @@ enum class SILDIExprOperator : unsigned { /// VarDecl operand pointing to the field declaration. /// Note that this directive can only appear at the end of an /// expression. - Fragment + Fragment, + /// Perform arithmetic addition on the top two elements of the + /// expression stack and push the result back to the stack. + Plus, + /// Subtract the top element in expression stack by the second + /// element. Then push the result back to the stack. + Minus, + /// Push an unsigned integer constant onto the stack. + ConstUInt, + /// Push a signed integer constant onto the stack. + ConstSInt }; /// Represents a single component in a debug info expression. /// Including operator and operand. struct SILDIExprElement { enum Kind { - /// A di-expression operator + /// A di-expression operator. OperatorKind, - /// An operand that has declaration type - DeclKind + /// An operand that has declaration type. + DeclKind, + /// An integer constant value. Note that + /// we don't specify its signedness here. + ConstIntKind }; private: @@ -55,6 +69,7 @@ struct SILDIExprElement { union { SILDIExprOperator Operator; Decl *Declaration; + uint64_t ConstantInt; }; explicit SILDIExprElement(Kind OpK) : OpKind(OpK) {} @@ -68,6 +83,13 @@ struct SILDIExprElement { Decl *getAsDecl() const { return OpKind == DeclKind ? Declaration : nullptr; } + Optional getAsConstInt() const { + if (OpKind == ConstIntKind) + return ConstantInt; + else + return {}; + } + static SILDIExprElement createOperator(SILDIExprOperator Op) { SILDIExprElement DIOp(OperatorKind); DIOp.Operator = Op; @@ -79,6 +101,12 @@ struct SILDIExprElement { DIOp.Declaration = D; return DIOp; } + + static SILDIExprElement createConstInt(uint64_t V) { + SILDIExprElement DIOp(ConstIntKind); + DIOp.ConstantInt = V; + return DIOp; + } }; /// For a given SILDIExprOperator, provides information diff --git a/lib/SIL/IR/SILDebugInfoExpression.cpp b/lib/SIL/IR/SILDebugInfoExpression.cpp index 25cd17737d09e..cfea4a24a1fc4 100644 --- a/lib/SIL/IR/SILDebugInfoExpression.cpp +++ b/lib/SIL/IR/SILDebugInfoExpression.cpp @@ -37,7 +37,13 @@ const SILDIExprInfo *SILDIExprInfo::get(SILDIExprOperator Op) { static const std::unordered_map Infos = { {SILDIExprOperator::Fragment, {"op_fragment", {SILDIExprElement::DeclKind}}}, - {SILDIExprOperator::Dereference, {"op_deref", {}}}}; + {SILDIExprOperator::Dereference, {"op_deref", {}}}, + {SILDIExprOperator::Plus, {"op_plus", {}}}, + {SILDIExprOperator::Minus, {"op_minus", {}}}, + {SILDIExprOperator::ConstUInt, + {"op_constu", {SILDIExprElement::ConstIntKind}}}, + {SILDIExprOperator::ConstSInt, + {"op_consts", {SILDIExprElement::ConstIntKind}}}}; return Infos.count(Op) ? &Infos.at(Op) : nullptr; } diff --git a/lib/SIL/IR/SILPrinter.cpp b/lib/SIL/IR/SILPrinter.cpp index d7e042d30b45f..83f70fcb7a88c 100644 --- a/lib/SIL/IR/SILPrinter.cpp +++ b/lib/SIL/IR/SILPrinter.cpp @@ -606,6 +606,7 @@ class SILPrinter : public SILInstructionVisitor { SIMPLE_PRINTER(char) SIMPLE_PRINTER(unsigned) SIMPLE_PRINTER(uint64_t) + SIMPLE_PRINTER(int64_t) SIMPLE_PRINTER(StringRef) SIMPLE_PRINTER(Identifier) SIMPLE_PRINTER(ID) @@ -1190,32 +1191,46 @@ class SILPrinter : public SILInstructionVisitor { assert(DIExpr && "DIExpression empty?"); *this << ", expr "; bool IsFirst = true; - for (const auto &E : DIExpr.elements()) { + for (const auto &Operand : DIExpr.operands()) { if (IsFirst) IsFirst = false; else *this << ":"; - switch (E.getKind()) { - case SILDIExprElement::OperatorKind: { - SILDIExprOperator Op = E.getAsOperator(); - assert(Op != SILDIExprOperator::INVALID && - "Invalid SILDIExprOperator kind"); - *this << SILDIExprInfo::get(Op)->OpText; - break; - } - case SILDIExprElement::DeclKind: { - const Decl *D = E.getAsDecl(); - // FIXME: Can we generalize this special handling for VarDecl - // to other kinds of Decl? - if (const auto *VD = dyn_cast(D)) { - *this << "#"; - printFullContext(VD->getDeclContext(), PrintState.OS); - *this << VD->getName().get(); - } else - D->print(PrintState.OS, PrintState.ASTOptions); - break; - } + // Print the operator + SILDIExprOperator Op = Operand.getOperator(); + assert(Op != SILDIExprOperator::INVALID && + "Invalid SILDIExprOperator kind"); + *this << SILDIExprInfo::get(Op)->OpText; + + // Print arguments + for (const auto &Arg : Operand.args()) { + *this << ":"; + switch (Arg.getKind()) { + case SILDIExprElement::OperatorKind: + llvm_unreachable("Cannot use operator as argument"); + break; + case SILDIExprElement::DeclKind: { + const Decl *D = Arg.getAsDecl(); + // FIXME: Can we generalize this special handling for VarDecl + // to other kinds of Decl? + if (const auto *VD = dyn_cast(D)) { + *this << "#"; + printFullContext(VD->getDeclContext(), PrintState.OS); + *this << VD->getName().get(); + } else + D->print(PrintState.OS, PrintState.ASTOptions); + break; + } + case SILDIExprElement::ConstIntKind: { + uint64_t V = *Arg.getAsConstInt(); + if (Op == SILDIExprOperator::ConstSInt) + *this << static_cast(V); + else + *this << V; + break; + } + } } } } diff --git a/lib/SIL/Parser/ParseSIL.cpp b/lib/SIL/Parser/ParseSIL.cpp index 1e9ce2d4e32b6..7a24cfb0ed324 100644 --- a/lib/SIL/Parser/ParseSIL.cpp +++ b/lib/SIL/Parser/ParseSIL.cpp @@ -1656,7 +1656,11 @@ bool SILParser::parseSILDebugInfoExpression(SILDebugInfoExpression &DIExpr) { // All operators that we currently support static const SILDIExprOperator AllOps[] = { SILDIExprOperator::Dereference, - SILDIExprOperator::Fragment + SILDIExprOperator::Fragment, + SILDIExprOperator::Plus, + SILDIExprOperator::Minus, + SILDIExprOperator::ConstUInt, + SILDIExprOperator::ConstSInt }; do { @@ -1690,6 +1694,23 @@ bool SILParser::parseSILDebugInfoExpression(SILDebugInfoExpression &DIExpr) { DIExpr.push_back(NewOperand); break; } + case SILDIExprElement::ConstIntKind: { + bool IsNegative = false; + if (P.Tok.is(tok::oper_prefix) && P.Tok.getRawText() == "-") { + P.consumeToken(); + IsNegative = true; + } + int64_t Val; + // FIXME: Use the correct diagnostic + if (parseInteger(Val, diag::sil_invalid_scope_slot)) + return true; + if (IsNegative) + Val = -Val; + auto NewOperand = + SILDIExprElement::createConstInt(static_cast(Val)); + DIExpr.push_back(NewOperand); + break; + } default: P.diagnose(P.Tok.getLoc(), diag::sil_dbg_unknown_expr_part, "operand kind"); diff --git a/test/DebugInfo/debug_info_expression.sil b/test/DebugInfo/debug_info_expression.sil index c7104f045545a..fc53d4c9b3726 100644 --- a/test/DebugInfo/debug_info_expression.sil +++ b/test/DebugInfo/debug_info_expression.sil @@ -14,7 +14,7 @@ struct SmallStruct { sil_scope 1 { loc "file.swift":7:6 parent @test_fragment : $@convention(thin) () -> () } -// Testing op_fragment w/ debug_value_addr +// Testing op_fragment w/ debug_value sil hidden @test_fragment : $@convention(thin) () -> () { bb0: %2 = alloc_stack $MyStruct, var, name "my_struct", loc "file.swift":8:9, scope 1 @@ -67,3 +67,26 @@ bb0: %r = tuple() return %r : $() } + +sil_scope 3 { loc "file.swift":16:7 parent @test_op_const : $@convention(thin) (Int64, Int64) -> () } + +// Testing op_constu and op_consts +sil hidden @test_op_const : $@convention(thin) (Int64, Int64) -> () { +bb0(%arg : $Int64, %arg2 : $Int64): + debug_value %arg : $Int64, let, name "the_arg", argno 1, expr op_constu:77, loc "file.swift":17:2, scope 3 + debug_value %arg2 : $Int64, let, name "the_2nd_arg", argno 2, expr op_consts:-87, loc "file.swift":17:4, scope 3 + %r = tuple() + return %r : $() +} + +sil_scope 4 { loc "file.swift":18:8 parent @test_arithmetic : $@convention(thin) (Int64, Int64) -> () } + +// Testing basic arithmetic operators like op_plus and op_minus +sil hidden @test_arithmetic : $@convention(thin) (Int64, Int64) -> () { +bb0(%arg : $Int64, %arg2 : $Int64): + debug_value %arg : $Int64, let, name "the_arg", argno 1, expr op_constu:3:op_plus, loc "file.swift":19:2, scope 4 + debug_value %arg2 : $Int64, let, name "the_2nd_arg", argno 2, expr op_constu:5:op_minus, loc "file.swift":19:4, scope 4 + %r = tuple() + return %r : $() +} + From a9cb668170232aa6f64e09ef0612e25d4a7534d1 Mon Sep 17 00:00:00 2001 From: Min-Yih Hsu Date: Thu, 2 Sep 2021 15:29:36 -0700 Subject: [PATCH 095/116] (Stash) basic IRGen support --- lib/IRGen/IRGenDebugInfo.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index d4505636b978e..0c47d85453629 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -2416,6 +2416,24 @@ bool IRGenDebugInfoImpl::buildDebugInfoExpression( case SILDIExprOperator::Dereference: Operands.push_back(llvm::dwarf::DW_OP_deref); break; + case SILDIExprOperator::ConstUInt: + case SILDIExprOperator::ConstSInt: { + auto Args = ExprOperand.args(); + assert(Args.size() == 1 && + "Incorrect number of argument for op_constu/op_consts"); + if (ExprOperand.getOperator() == SILDIExprOperator::ConstUInt) + Operands.push_back(llvm::dwarf::DW_OP_constu); + else + Operands.push_back(llvm::dwarf::DW_OP_consts); + Operands.push_back(*Args[0].getAsConstInt()); + break; + } + case SILDIExprOperator::Plus: + Operands.push_back(llvm::dwarf::DW_OP_plus); + break; + case SILDIExprOperator::Minus: + Operands.push_back(llvm::dwarf::DW_OP_minus); + break; default: llvm_unreachable("Unrecognized operator"); } From b52fdc6628854dd882bc7abbd161b06e4f23ba9e Mon Sep 17 00:00:00 2001 From: Min-Yih Hsu Date: Tue, 7 Sep 2021 13:47:32 -0700 Subject: [PATCH 096/116] (Stash) Salvaging debug info from deleted `struct` instruction --- include/swift/SIL/SILDebugInfoExpression.h | 13 ++++++ lib/SILOptimizer/Utils/InstOptUtils.cpp | 42 +++++++++++++++++++ test/DebugInfo/constant_propagation.sil | 40 ++++++++++++++++++ .../SILOptimizer/no_size_specialization.swift | 6 +-- .../specialize_opaque_type_archetypes.swift | 8 ++-- 5 files changed, 102 insertions(+), 7 deletions(-) create mode 100644 test/DebugInfo/constant_propagation.sil diff --git a/include/swift/SIL/SILDebugInfoExpression.h b/include/swift/SIL/SILDebugInfoExpression.h index 84a7c2ac59db1..ea9639b577192 100644 --- a/include/swift/SIL/SILDebugInfoExpression.h +++ b/include/swift/SIL/SILDebugInfoExpression.h @@ -259,6 +259,19 @@ class SILDebugInfoExpression { /// Create a op_fragment expression static SILDebugInfoExpression createFragment(VarDecl *Field); + + /// Return true if this DIExpression starts with op_deref + bool startsWithDeref() const { + return Elements.size() && + Elements[0].getAsOperator() == SILDIExprOperator::Dereference; + } + + /// Return true if this DIExpression has op_fragment (at the end) + bool hasFragment() const { + return Elements.size() >= 2 && + Elements[Elements.size() - 2].getAsOperator() == + SILDIExprOperator::Fragment; + } }; } // end namespace swift #endif diff --git a/lib/SILOptimizer/Utils/InstOptUtils.cpp b/lib/SILOptimizer/Utils/InstOptUtils.cpp index d2b54d90f1584..f57a4e89882ed 100644 --- a/lib/SILOptimizer/Utils/InstOptUtils.cpp +++ b/lib/SILOptimizer/Utils/InstOptUtils.cpp @@ -22,6 +22,7 @@ #include "swift/SIL/InstructionUtils.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILBuilder.h" +#include "swift/SIL/SILDebugInfoExpression.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILUndef.h" #include "swift/SIL/TypeLowering.h" @@ -2127,4 +2128,45 @@ void swift::salvageDebugInfo(SILInstruction *I) { .createDebugValue(SI->getLoc(), SI->getSrc(), *VarInfo); } } + + // If a `struct` SIL instruction is "unwrapped" and removed, + // for instance, in favor of using its enclosed value directly, + // we need to make sure any of its related `debug_value` instruction + // is preserved. + if (auto *STI = dyn_cast(I)) { + auto STVal = STI->getResult(0); + llvm::ArrayRef FieldDecls = + STI->getStructDecl()->getStoredProperties(); + for (Operand *U : getDebugUses(STVal)) { + auto *DbgInst = cast(U->getUser()); + auto VarInfo = DbgInst->getVarInfo(); + if (!VarInfo) + continue; + if (VarInfo->DIExpr.hasFragment()) + // Since we can't merge two different op_fragment + // now, we're simply bailing out if there is an + // existing op_fragment in DIExpresison. + // TODO: Try to merge two op_fragment expressions here. + continue; + for (VarDecl *FD : FieldDecls) { + SILDebugVariable NewVarInfo = *VarInfo; + auto FieldVal = STI->getFieldValue(FD); + // Build the corresponding fragment DIExpression + auto FragDIExpr = SILDebugInfoExpression::createFragment(FD); + NewVarInfo.DIExpr.append(FragDIExpr); + + // Coalesce auxiliary debug variable info + if (!NewVarInfo.Type) + NewVarInfo.Type = STI->getType(); + if (!NewVarInfo.Loc) + NewVarInfo.Loc = DbgInst->getLoc(); + if (!NewVarInfo.Scope) + NewVarInfo.Scope = DbgInst->getDebugScope(); + + // Create a new debug_value + SILBuilder(DbgInst, DbgInst->getDebugScope()) + .createDebugValue(DbgInst->getLoc(), FieldVal, NewVarInfo); + } + } + } } diff --git a/test/DebugInfo/constant_propagation.sil b/test/DebugInfo/constant_propagation.sil new file mode 100644 index 0000000000000..6e83c8e19ad75 --- /dev/null +++ b/test/DebugInfo/constant_propagation.sil @@ -0,0 +1,40 @@ +// RUN: %target-sil-opt -enable-sil-verify-all -sil-print-debuginfo -diagnostic-constant-propagation %s | %FileCheck %s + +sil_stage canonical + +import Builtin +import Swift +import SwiftShims + +func foo(x: Int, y: Int) -> Int + +sil_scope 1 { loc "file.swift":1:6 parent @foo : $@convention(thin) (Int, Int) -> Int } + +// Test if debug_value got preserved when %16 is removed in favor of directly using %13 +// CHECK-LABEL: sil {{.*}} @foo +sil hidden @foo : $@convention(thin) (Int, Int) -> Int { +bb0(%0 : $Int, %1 : $Int): + %4 = integer_literal $Builtin.Int64, 87, loc "file.swift":2:17, scope 1 + %9 = struct_extract %0 : $Int, #Int._value, loc "file.swift":2:15, scope 1 + %11 = integer_literal $Builtin.Int1, -1, loc "file.swift":2:15, scope 1 + // CHECK: %[[ADD:.+]] = builtin "sadd_with_overflow + %12 = builtin "sadd_with_overflow_Int64"(%9 : $Builtin.Int64, %4 : $Builtin.Int64, %11 : $Builtin.Int1) : $(Builtin.Int64, Builtin.Int1), loc "file.swift":2:15, scope 1 + // CHECK: (%[[RESULT:.+]], %{{.*}}) = destructure_tuple %[[ADD]] + (%13, %14) = destructure_tuple %12 : $(Builtin.Int64, Builtin.Int1), loc "file.swift":2:15, scope 1 + %16 = struct $Int (%13 : $Builtin.Int64), loc "file.swift":2:15, scope 1 + // In addition to checking if `op_fragment` is generated, we're also checking if "z"'s declared + // source location, as well as `debug_value`'s instruction source location are preserved. + // CHECK: debug_value %[[RESULT]] : $Builtin.Int{{[0-9]+}}, let, (name "z", loc "file.swift":2:9, scope 1) + // CHECK-SAME: type $Int + // CHECK-SAME: expr op_fragment:#Int._value + // CHECK-SAME: loc "file.swift":2:9, scope 1 + debug_value %16 : $Int, let, name "z", loc "file.swift":2:9, scope 1 + %19 = struct_extract %16 : $Int, #Int._value, loc "file.swift":3:14, scope 1 + %20 = struct_extract %1 : $Int, #Int._value, loc "file.swift":3:14, scope 1 + %21 = integer_literal $Builtin.Int1, -1, loc "file.swift":3:14, scope 1 + %22 = builtin "sadd_with_overflow_Int64"(%19 : $Builtin.Int64, %20 : $Builtin.Int64, %21 : $Builtin.Int1) : $(Builtin.Int64, Builtin.Int1), loc "file.swift":3:14, scope 1 + (%23, %24) = destructure_tuple %22 : $(Builtin.Int64, Builtin.Int1), loc "file.swift":3:14, scope 1 + %26 = struct $Int (%23 : $Builtin.Int64), loc "file.swift":3:14, scope 1 + return %26 : $Int, loc "file.swift":3:5, scope 1 +} // end sil function 'foo' + diff --git a/test/SILOptimizer/no_size_specialization.swift b/test/SILOptimizer/no_size_specialization.swift index 27e5b8b8f361d..42451179d771d 100644 --- a/test/SILOptimizer/no_size_specialization.swift +++ b/test/SILOptimizer/no_size_specialization.swift @@ -7,9 +7,9 @@ func foo(_ t: T) -> T { } // CHECK-O-LABEL: sil @{{.*}}test -// CHECK-O: %0 = integer_literal -// CHECK-O: %1 = struct $Int -// CHECK-O: return %1 +// CHECK-O: %[[LITERAL:.+]] = integer_literal $Builtin.Int{{[0-9]+}}, 27 +// CHECK-O: %[[STRUCT:.+]] = struct $Int (%[[LITERAL]] : $Builtin.Int{{[0-9]+}}) +// CHECK-O: return %[[STRUCT]] // CHECK-OSIZE-LABEL: sil {{.*}} @{{.*}}foo diff --git a/test/SILOptimizer/specialize_opaque_type_archetypes.swift b/test/SILOptimizer/specialize_opaque_type_archetypes.swift index 1a371d47c0481..7041b7ecfddf1 100644 --- a/test/SILOptimizer/specialize_opaque_type_archetypes.swift +++ b/test/SILOptimizer/specialize_opaque_type_archetypes.swift @@ -435,10 +435,10 @@ func createTrivial(_ t: T) -> Trivial { } // CHECK: sil @$s1A11testTrivialyyF : $@convention(thin) () -> () -// CHECK: %0 = integer_literal $Builtin.Int64, 1 -// CHECK: %1 = struct $Int64 (%0 : $Builtin.Int64) -// CHECK: %2 = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () -// CHECK: %3 = apply %2(%1) +// CHECK: %[[LITERAL:.+]] = integer_literal $Builtin.Int64, 1 +// CHECK: %[[STRUCT:.+]] = struct $Int64 (%[[LITERAL]] : $Builtin.Int64) +// CHECK: %[[FUNC:.+]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () +// CHECK: apply %[[FUNC]](%[[STRUCT]]) public func testTrivial() { let s = bar(10) let t = createTrivial(s) From 69ffafe14623aa343674bc0a30bbf8a5b766fec9 Mon Sep 17 00:00:00 2001 From: Min-Yih Hsu Date: Wed, 8 Sep 2021 14:47:30 -0700 Subject: [PATCH 097/116] (Stash) Salvage debug info from deleted `index_addr` instruction And calling `swift::salvageDebugInfo` in more places. NOTE: The latter change seems to break stdlib build. --- include/swift/SIL/SILInstructionWorklist.h | 5 +++- lib/IRGen/IRGenDebugInfo.cpp | 20 ++++++++------ lib/SILOptimizer/Utils/InstOptUtils.cpp | 32 ++++++++++++++++++---- test/DebugInfo/constant_propagation.sil | 2 +- test/DebugInfo/sil_combine.sil | 28 +++++++++++++++++++ 5 files changed, 71 insertions(+), 16 deletions(-) create mode 100644 test/DebugInfo/sil_combine.sil diff --git a/include/swift/SIL/SILInstructionWorklist.h b/include/swift/SIL/SILInstructionWorklist.h index 790f3f9fc5b06..58025ee529019 100644 --- a/include/swift/SIL/SILInstructionWorklist.h +++ b/include/swift/SIL/SILInstructionWorklist.h @@ -37,6 +37,7 @@ #include "swift/SIL/SILInstruction.h" #include "swift/SIL/InstructionUtils.h" #include "swift/SIL/SILValue.h" +#include "swift/SILOptimizer/Utils/DebugOptUtils.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" @@ -309,7 +310,9 @@ class SILInstructionWorklist : SILInstructionWorklistBase { void eraseInstFromFunction(SILInstruction &instruction, SILBasicBlock::iterator &iterator, bool addOperandsToWorklist = true) { - // Delete any debug users first. + // Try to salvage debug info first. + swift::salvageDebugInfo(&instruction); + // Then delete old debug users. for (auto result : instruction.getResults()) { while (!result->use_empty()) { auto *user = result->use_begin()->getUser(); diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index 0c47d85453629..a2d74f5942fa2 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -2547,6 +2547,7 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( if (Indirection == IndirectValue || Indirection == CoroIndirectValue) Operands.push_back(llvm::dwarf::DW_OP_deref); + bool HasFragment = false; if (IsPiece) { // Advance the offset and align it for the next piece. OffsetInBits += llvm::alignTo(SizeInBits, AlignInBits); @@ -2557,18 +2558,19 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( // Sanity checks. assert(SizeInBits && "zero-sized piece"); - assert(SizeInBits < getSizeInBits(Var) && "piece covers entire var"); - assert(OffsetInBits + SizeInBits <= getSizeInBits(Var) && "pars > totum"); - - // Add the piece DWARF expression. - Operands.push_back(llvm::dwarf::DW_OP_LLVM_fragment); - Operands.push_back(OffsetInBits); - Operands.push_back(SizeInBits); + if (SizeInBits < getSizeInBits(Var) && + OffsetInBits + SizeInBits <= getSizeInBits(Var)) { + HasFragment = true; + // Add the piece DWARF expression. + Operands.push_back(llvm::dwarf::DW_OP_LLVM_fragment); + Operands.push_back(OffsetInBits); + Operands.push_back(SizeInBits); + } } llvm::DIExpression *DIExpr = DBuilder.createExpression(Operands); // DW_OP_LLVM_fragment must be the last part of an DIExpr - // so we can't append more if IsPiece is true. - if (!IsPiece) + // so we can't append more if there is already one. + if (!HasFragment) DIExpr = appendDIExpression(DIExpr); if (DIExpr) emitDbgIntrinsic( diff --git a/lib/SILOptimizer/Utils/InstOptUtils.cpp b/lib/SILOptimizer/Utils/InstOptUtils.cpp index f57a4e89882ed..21b80fdaddbce 100644 --- a/lib/SILOptimizer/Utils/InstOptUtils.cpp +++ b/lib/SILOptimizer/Utils/InstOptUtils.cpp @@ -2155,13 +2155,8 @@ void swift::salvageDebugInfo(SILInstruction *I) { auto FragDIExpr = SILDebugInfoExpression::createFragment(FD); NewVarInfo.DIExpr.append(FragDIExpr); - // Coalesce auxiliary debug variable info if (!NewVarInfo.Type) NewVarInfo.Type = STI->getType(); - if (!NewVarInfo.Loc) - NewVarInfo.Loc = DbgInst->getLoc(); - if (!NewVarInfo.Scope) - NewVarInfo.Scope = DbgInst->getDebugScope(); // Create a new debug_value SILBuilder(DbgInst, DbgInst->getDebugScope()) @@ -2169,4 +2164,31 @@ void swift::salvageDebugInfo(SILInstruction *I) { } } } + + if (auto *IA = dyn_cast(I)) { + if (IA->getBase() && IA->getIndex()) + // Only handle cases where offset is constant. + if (const auto *LiteralInst = + dyn_cast(IA->getIndex())) { + SILValue Base = IA->getBase(); + SILValue ResultAddr = IA->getResult(0); + APInt OffsetVal = LiteralInst->getValue(); + const SILDIExprElement ExprElements[3] = { + SILDIExprElement::createOperator(OffsetVal.isNegative() ? + SILDIExprOperator::ConstSInt : SILDIExprOperator::ConstUInt), + SILDIExprElement::createConstInt(OffsetVal.getLimitedValue()), + SILDIExprElement::createOperator(SILDIExprOperator::Plus) + }; + for (Operand *U : getDebugUses(ResultAddr)) { + auto *DbgInst = cast(U->getUser()); + auto VarInfo = DbgInst->getVarInfo(); + if (!VarInfo) + continue; + VarInfo->DIExpr.prependElements(ExprElements); + // Create a new debug_value + SILBuilder(DbgInst, DbgInst->getDebugScope()) + .createDebugValue(DbgInst->getLoc(), Base, *VarInfo); + } + } + } } diff --git a/test/DebugInfo/constant_propagation.sil b/test/DebugInfo/constant_propagation.sil index 6e83c8e19ad75..b968500f05a81 100644 --- a/test/DebugInfo/constant_propagation.sil +++ b/test/DebugInfo/constant_propagation.sil @@ -24,7 +24,7 @@ bb0(%0 : $Int, %1 : $Int): %16 = struct $Int (%13 : $Builtin.Int64), loc "file.swift":2:15, scope 1 // In addition to checking if `op_fragment` is generated, we're also checking if "z"'s declared // source location, as well as `debug_value`'s instruction source location are preserved. - // CHECK: debug_value %[[RESULT]] : $Builtin.Int{{[0-9]+}}, let, (name "z", loc "file.swift":2:9, scope 1) + // CHECK: debug_value %[[RESULT]] : $Builtin.Int{{[0-9]+}}, let, name "z" // CHECK-SAME: type $Int // CHECK-SAME: expr op_fragment:#Int._value // CHECK-SAME: loc "file.swift":2:9, scope 1 diff --git a/test/DebugInfo/sil_combine.sil b/test/DebugInfo/sil_combine.sil new file mode 100644 index 0000000000000..4f555bd0d04b4 --- /dev/null +++ b/test/DebugInfo/sil_combine.sil @@ -0,0 +1,28 @@ +// RUN: %target-sil-opt -sil-verify-all -sil-combine %s | %FileCheck %s +// RUN: %target-swift-frontend -g -O -emit-ir -primary-file %s | %FileCheck --check-prefix=CHECK-IR %s + +sil_stage canonical + +import Builtin +import Swift + +// CHECK-LABEL: sil {{.*}} @test_nested_index_addr +// CHECK-IR-LABEL: define {{.*}} @test_nested_index_addr +sil hidden @test_nested_index_addr : $@convention(thin) (Builtin.RawPointer) -> Builtin.RawPointer { +bb0(%0 : $Builtin.RawPointer): + %offset1 = integer_literal $Builtin.Word, 3 + %offset2 = integer_literal $Builtin.Word, 7 + // CHECK: %[[ADDR:.+]] = pointer_to_address %0 + %addr = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*UInt8 + %addr1 = index_addr %addr : $*UInt8, %offset1 : $Builtin.Word + // CHECK: debug_value %[[ADDR]] : $*UInt8, let, name "hello" + // CHECK-SAME: expr op_constu:3:op_plus:op_deref + // CHECK-IR: call void @llvm.dbg.value(metadata i8* %0, metadata ![[DBG_VAR:[0-9]+]], + // CHECK-IR-SAME: !DIExpression(DW_OP_constu, 3, DW_OP_plus, DW_OP_deref) + debug_value %addr1 : $*UInt8, let, name "hello", expr op_deref + %addr2 = index_addr %addr1 : $*UInt8, %offset2 : $Builtin.Word + %ptr = address_to_pointer %addr2 : $*UInt8 to $Builtin.RawPointer + return %ptr : $Builtin.RawPointer +} + +// CHECK-IR: ![[DBG_VAR]] = !DILocalVariable(name: "hello" From e1ba7f4da37472459d9d29dc4cac990ef577b29b Mon Sep 17 00:00:00 2001 From: Min-Yih Hsu Date: Thu, 9 Sep 2021 18:02:04 -0700 Subject: [PATCH 098/116] (Stash) Add SILVerifier rule to prevent conflicting arg DIVariable This rule tries to prevent two DIVariables -- with different types -- conflicting with each other on the same argument number. If this rule fails, it's highly possible that we forgot to add 'inlinedAt' somewhere. --- lib/SIL/Verifier/SILVerifier.cpp | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/lib/SIL/Verifier/SILVerifier.cpp b/lib/SIL/Verifier/SILVerifier.cpp index 9ab0d4747a3f4..a063a0b6bfd10 100644 --- a/lib/SIL/Verifier/SILVerifier.cpp +++ b/lib/SIL/Verifier/SILVerifier.cpp @@ -666,7 +666,7 @@ class SILVerifier : public SILVerifierBase { const SILFunction &F; SILFunctionConventions fnConv; Lowering::TypeConverter &TC; - SmallVector DebugVars; + SmallVector, 16> DebugVars; const SILInstruction *CurInstruction = nullptr; const SILArgument *CurArgument = nullptr; std::unique_ptr Dominance; @@ -1265,6 +1265,25 @@ class SILVerifier : public SILVerifierBase { if (!varInfo) return; + // Retrive debug variable type + SILType DebugVarTy; + if (varInfo->Type) + DebugVarTy = *varInfo->Type; + else { + // Fetch from related SSA value + switch (inst->getKind()) { + case SILInstructionKind::AllocStackInst: + case SILInstructionKind::AllocBoxInst: + DebugVarTy = inst->getResult(0)->getType(); + break; + case SILInstructionKind::DebugValueInst: + DebugVarTy = inst->getOperand(0)->getType(); + break; + default: + llvm_unreachable(""); + } + } + auto *debugScope = inst->getDebugScope(); if (varInfo->ArgNo) require(!varInfo->Name.empty(), "function argument without a name"); @@ -1278,17 +1297,20 @@ class SILVerifier : public SILVerifierBase { if (debugScope && !debugScope->InlinedCallSite) if (unsigned argNum = varInfo->ArgNo) { // It is a function argument. - if (argNum < DebugVars.size() && !DebugVars[argNum].empty()) { - require(DebugVars[argNum] == varInfo->Name, + if (argNum < DebugVars.size() && !DebugVars[argNum].first.empty()) { + require(DebugVars[argNum].first == varInfo->Name, "Scope contains conflicting debug variables for one function " "argument"); + // Check for type + require(DebugVars[argNum].second == DebugVarTy, + "conflicting debug variable type!"); } else { // Reserve enough space. while (DebugVars.size() <= argNum) { - DebugVars.push_back(StringRef()); + DebugVars.push_back({StringRef(), SILType()}); } } - DebugVars[argNum] = varInfo->Name; + DebugVars[argNum] = {varInfo->Name, DebugVarTy}; } // Check the (auxiliary) debug variable scope From ea6dca3e946fd130488ca5ec760fc2923a00f6d7 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 10 Sep 2021 17:07:02 -0700 Subject: [PATCH 099/116] Fix SIL Verifier --- lib/IRGen/IRGenDebugInfo.cpp | 38 ++++++++------------------------ lib/SIL/Verifier/SILVerifier.cpp | 8 ++++++- 2 files changed, 16 insertions(+), 30 deletions(-) diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index a2d74f5942fa2..d4505636b978e 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -2416,24 +2416,6 @@ bool IRGenDebugInfoImpl::buildDebugInfoExpression( case SILDIExprOperator::Dereference: Operands.push_back(llvm::dwarf::DW_OP_deref); break; - case SILDIExprOperator::ConstUInt: - case SILDIExprOperator::ConstSInt: { - auto Args = ExprOperand.args(); - assert(Args.size() == 1 && - "Incorrect number of argument for op_constu/op_consts"); - if (ExprOperand.getOperator() == SILDIExprOperator::ConstUInt) - Operands.push_back(llvm::dwarf::DW_OP_constu); - else - Operands.push_back(llvm::dwarf::DW_OP_consts); - Operands.push_back(*Args[0].getAsConstInt()); - break; - } - case SILDIExprOperator::Plus: - Operands.push_back(llvm::dwarf::DW_OP_plus); - break; - case SILDIExprOperator::Minus: - Operands.push_back(llvm::dwarf::DW_OP_minus); - break; default: llvm_unreachable("Unrecognized operator"); } @@ -2547,7 +2529,6 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( if (Indirection == IndirectValue || Indirection == CoroIndirectValue) Operands.push_back(llvm::dwarf::DW_OP_deref); - bool HasFragment = false; if (IsPiece) { // Advance the offset and align it for the next piece. OffsetInBits += llvm::alignTo(SizeInBits, AlignInBits); @@ -2558,19 +2539,18 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( // Sanity checks. assert(SizeInBits && "zero-sized piece"); - if (SizeInBits < getSizeInBits(Var) && - OffsetInBits + SizeInBits <= getSizeInBits(Var)) { - HasFragment = true; - // Add the piece DWARF expression. - Operands.push_back(llvm::dwarf::DW_OP_LLVM_fragment); - Operands.push_back(OffsetInBits); - Operands.push_back(SizeInBits); - } + assert(SizeInBits < getSizeInBits(Var) && "piece covers entire var"); + assert(OffsetInBits + SizeInBits <= getSizeInBits(Var) && "pars > totum"); + + // Add the piece DWARF expression. + Operands.push_back(llvm::dwarf::DW_OP_LLVM_fragment); + Operands.push_back(OffsetInBits); + Operands.push_back(SizeInBits); } llvm::DIExpression *DIExpr = DBuilder.createExpression(Operands); // DW_OP_LLVM_fragment must be the last part of an DIExpr - // so we can't append more if there is already one. - if (!HasFragment) + // so we can't append more if IsPiece is true. + if (!IsPiece) DIExpr = appendDIExpression(DIExpr); if (DIExpr) emitDbgIntrinsic( diff --git a/lib/SIL/Verifier/SILVerifier.cpp b/lib/SIL/Verifier/SILVerifier.cpp index a063a0b6bfd10..2df7139015ee9 100644 --- a/lib/SIL/Verifier/SILVerifier.cpp +++ b/lib/SIL/Verifier/SILVerifier.cpp @@ -1278,9 +1278,15 @@ class SILVerifier : public SILVerifierBase { break; case SILInstructionKind::DebugValueInst: DebugVarTy = inst->getOperand(0)->getType(); + if (DebugVarTy.isAddress()) { + auto Expr = varInfo->DIExpr.operands(); + if (!Expr.empty() && + Expr.begin()->getOperator() == SILDIExprOperator::Dereference) + DebugVarTy = DebugVarTy.getObjectType(); + } break; default: - llvm_unreachable(""); + llvm_unreachable("impossible instruction kind"); } } From 69f43b33753fcba8602b75eb8eb4f2a382623925 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Fri, 10 Sep 2021 20:54:29 -0700 Subject: [PATCH 100/116] test: repair IRGen.objc_protocol_vars on Windows This has regressed on the rebranch. Add a check for the COFF case. --- test/IRGen/objc_protocol_vars.sil | 1 + 1 file changed, 1 insertion(+) diff --git a/test/IRGen/objc_protocol_vars.sil b/test/IRGen/objc_protocol_vars.sil index 7d00b48695916..c102f3fc4fe21 100644 --- a/test/IRGen/objc_protocol_vars.sil +++ b/test/IRGen/objc_protocol_vars.sil @@ -27,4 +27,5 @@ import Foundation // CHECK-macho: @llvm.used = appending global [{{.*}}] [{{.*}}, i8* bitcast (i8** @"\01l_OBJC_LABEL_PROTOCOL_$__TtP18objc_protocol_vars1T_" to i8*), i8* bitcast (i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP18objc_protocol_vars1T_" to i8*), {{.*}}], {{.*}} // CHECK-elf: @llvm.compiler.used = appending global [{{.*}}] [{{.*}}, i8* bitcast (i8** @"\01l_OBJC_LABEL_PROTOCOL_$__TtP18objc_protocol_vars1T_" to i8*), i8* bitcast (i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP18objc_protocol_vars1T_" to i8*), {{.*}}], {{.*}} +// CHECK-coff: @llvm.used = appending global [{{.*}}] [{{.*}}, i8* bitcast (i8** @"\01l_OBJC_LABEL_PROTOCOL_$__TtP18objc_protocol_vars1T_" to i8*), i8* bitcast (i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP18objc_protocol_vars1T_" to i8*), {{.*}}], {{.*}} From e7965cefc42fb134d6c2f883235f30e761c197de Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Sat, 11 Sep 2021 12:03:35 -0700 Subject: [PATCH 101/116] IRGen: remove ELF autolink discard gadget The ELF autolink section was previously relying on the SHF_EXCLUDE flag being applied through module-level assembly. Remove this gadget and sink the handling down into LLVM. The latest improvements to LLVM now cause this workaround to be insufficient as the section is explicitly marked as SHF_ALLOC, which will implicitly negate the SHF_EXCLUDE. As a result, we no longer discard the metadata. Once this is sunk into LLVM the attribute is unnecessary. Furthermore, due to uniquing, will actually cause a problem as there is no uniform handling for metadata section prefixes. rdar://82640394 --- lib/IRGen/IRGenModule.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/lib/IRGen/IRGenModule.cpp b/lib/IRGen/IRGenModule.cpp index 5f55c8644bf6d..8bf84f8be4a1b 100644 --- a/lib/IRGen/IRGenModule.cpp +++ b/lib/IRGen/IRGenModule.cpp @@ -1465,13 +1465,6 @@ void AutolinkKind::writeEntries(llvm::SetVector Ent } auto EntriesConstant = llvm::ConstantDataArray::getString( IGM.getLLVMContext(), EntriesString, /*AddNull=*/false); - // Mark the swift1_autolink_entries section with the SHF_EXCLUDE attribute - // to get the linker to drop it in the final linked binary. - // LLVM doesn't provide an interface to specify section attributs in the - // IR so we pass the attribute with inline assembly. - if (IGM.TargetInfo.OutputObjectFormat == llvm::Triple::ELF) - IGM.Module.appendModuleInlineAsm(".section .swift1_autolink_entries," - "\"0x80000000\""); auto var = new llvm::GlobalVariable(*IGM.getModule(), EntriesConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, From 857bcb4d250acf46408b23c847343ffb84b2f993 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Sat, 11 Sep 2021 14:58:57 -0700 Subject: [PATCH 102/116] Remove the now obsolete check for the ELF gadget --- test/IRGen/ELF-remove-autolink-section.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/IRGen/ELF-remove-autolink-section.swift b/test/IRGen/ELF-remove-autolink-section.swift index be94f083f40a6..4723f3ed26962 100644 --- a/test/IRGen/ELF-remove-autolink-section.swift +++ b/test/IRGen/ELF-remove-autolink-section.swift @@ -12,8 +12,6 @@ print("Hi from Swift!") -// ELF: module asm ".section .swift1_autolink_entries,\220x80000000\22" - // Find the metadata entry for the denylisting of the metadata symbol // Ensure that it is in the ASAN metadata From 24ba2d1b20c8422e80fcedd0078fda2bf942bb83 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Sat, 11 Sep 2021 16:15:36 -0700 Subject: [PATCH 103/116] Update ELF-remove-autolink-section.swift --- test/IRGen/ELF-remove-autolink-section.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/IRGen/ELF-remove-autolink-section.swift b/test/IRGen/ELF-remove-autolink-section.swift index 4723f3ed26962..5f46d4f2e4aa4 100644 --- a/test/IRGen/ELF-remove-autolink-section.swift +++ b/test/IRGen/ELF-remove-autolink-section.swift @@ -15,7 +15,7 @@ print("Hi from Swift!") // Find the metadata entry for the denylisting of the metadata symbol // Ensure that it is in the ASAN metadata -// ELF-DAG: !llvm.asan.globals = !{ +// ELF: !llvm.asan.globals = !{ // ELF-SAME: [[MD:![0-9]+]] // ELF-SAME: } From e6c25be68419ad10ff15289aabc290124f59c169 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Wed, 15 Sep 2021 16:35:16 -0700 Subject: [PATCH 104/116] fix SingleCommandCompilationDatabase references The SingleCommandCompilationDatabase type was removed from LLVM and the API's that took it were changed to just take the vector of arguments instead. This patch updates the calls to `getFullDependencies` to pass in the argument vector to reflect that change and get things building again. --- lib/ClangImporter/ClangModuleDependencyScanner.cpp | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/lib/ClangImporter/ClangModuleDependencyScanner.cpp b/lib/ClangImporter/ClangModuleDependencyScanner.cpp index 45f393844e7ce..2ed7891d60ded 100644 --- a/lib/ClangImporter/ClangModuleDependencyScanner.cpp +++ b/lib/ClangImporter/ClangModuleDependencyScanner.cpp @@ -306,17 +306,13 @@ Optional ClangImporter::getModuleDependencies( } // Determine the command-line arguments for dependency scanning. - std::vector commandLineArgs = getClangDepScanningInvocationArguments(ctx, *importHackFile); - std::string workingDir = ctx.SourceMgr.getFileSystem()->getCurrentWorkingDirectory().get(); - CompileCommand command(workingDir, *importHackFile, commandLineArgs, "-"); - SingleCommandCompilationDatabase database(command); auto clangDependencies = clangImpl->tool.getFullDependencies( - database, workingDir, clangImpl->alreadySeen); + commandLineArgs, workingDir, clangImpl->alreadySeen); if (!clangDependencies) { // FIXME: Route this to a normal diagnostic. llvm::logAllUnhandledErrors(clangDependencies.takeError(), llvm::errs()); @@ -354,14 +350,11 @@ bool ClangImporter::addBridgingHeaderDependencies( // Determine the command-line arguments for dependency scanning. std::vector commandLineArgs = getClangDepScanningInvocationArguments(ctx, bridgingHeader); - std::string workingDir = ctx.SourceMgr.getFileSystem()->getCurrentWorkingDirectory().get(); - CompileCommand command(workingDir, bridgingHeader, commandLineArgs, "-"); - SingleCommandCompilationDatabase database(command); auto clangDependencies = clangImpl->tool.getFullDependencies( - database, workingDir, clangImpl->alreadySeen); + commandLineArgs, workingDir, clangImpl->alreadySeen); if (!clangDependencies) { // FIXME: Route this to a normal diagnostic. From fd19e4bc071028f499658c68413fb64cf3e80614 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Thu, 16 Sep 2021 17:32:10 -0700 Subject: [PATCH 105/116] Distinguish between storage size of a fragment and storage size for the entire type in DebugTypeInfo. --- lib/IRGen/DebugTypeInfo.cpp | 59 +++++++++++++++++++--------------- lib/IRGen/DebugTypeInfo.h | 43 +++++++++++++++---------- lib/IRGen/IRGenDebugInfo.cpp | 61 ++++++++++++++++++++---------------- lib/IRGen/IRGenSIL.cpp | 31 ++++++++++++------ 4 files changed, 115 insertions(+), 79 deletions(-) diff --git a/lib/IRGen/DebugTypeInfo.cpp b/lib/IRGen/DebugTypeInfo.cpp index 9f183d306870f..779f30d9c782a 100644 --- a/lib/IRGen/DebugTypeInfo.cpp +++ b/lib/IRGen/DebugTypeInfo.cpp @@ -24,11 +24,13 @@ using namespace swift; using namespace irgen; -DebugTypeInfo::DebugTypeInfo(swift::Type Ty, llvm::Type *StorageTy, +DebugTypeInfo::DebugTypeInfo(swift::Type Ty, llvm::Type *FragmentStorageTy, Optional size, Alignment align, - bool HasDefaultAlignment, bool IsMetadata) - : Type(Ty.getPointer()), StorageType(StorageTy), size(size), align(align), - DefaultAlignment(HasDefaultAlignment), IsMetadataType(IsMetadata) { + bool HasDefaultAlignment, bool IsMetadata, + bool SizeIsFragmentSize) + : Type(Ty.getPointer()), FragmentStorageType(FragmentStorageTy), size(size), + align(align), DefaultAlignment(HasDefaultAlignment), + IsMetadataType(IsMetadata), SizeIsFragmentSize(SizeIsFragmentSize) { assert(align.getValue() != 0); } @@ -42,7 +44,8 @@ static bool hasDefaultAlignment(swift::Type Ty) { } DebugTypeInfo DebugTypeInfo::getFromTypeInfo(swift::Type Ty, - const TypeInfo &Info) { + const TypeInfo &Info, + bool IsFragmentTypeInfo) { Optional size; if (Info.isFixedSize()) { const FixedTypeInfo &FixTy = *cast(&Info); @@ -51,11 +54,12 @@ DebugTypeInfo DebugTypeInfo::getFromTypeInfo(swift::Type Ty, assert(Info.getStorageType() && "StorageType is a nullptr"); return DebugTypeInfo(Ty.getPointer(), Info.getStorageType(), size, Info.getBestKnownAlignment(), ::hasDefaultAlignment(Ty), - false); + false, IsFragmentTypeInfo); } DebugTypeInfo DebugTypeInfo::getLocalVariable(VarDecl *Decl, swift::Type Ty, - const TypeInfo &Info) { + const TypeInfo &Info, + bool IsFragmentTypeInfo) { auto DeclType = Decl->getInterfaceType(); auto RealType = Ty; @@ -69,30 +73,32 @@ DebugTypeInfo DebugTypeInfo::getLocalVariable(VarDecl *Decl, swift::Type Ty, // the type hasn't been mucked with by an optimization pass. auto *Type = Sugared->isEqual(RealType) ? DeclType.getPointer() : RealType.getPointer(); - return getFromTypeInfo(Type, Info); + return getFromTypeInfo(Type, Info, IsFragmentTypeInfo); } DebugTypeInfo DebugTypeInfo::getMetadata(swift::Type Ty, llvm::Type *StorageTy, Size size, Alignment align) { DebugTypeInfo DbgTy(Ty.getPointer(), StorageTy, size, - align, true, false); + align, true, false, false); assert(StorageTy && "StorageType is a nullptr"); - assert(!DbgTy.isContextArchetype() && "type metadata cannot contain an archetype"); + assert(!DbgTy.isContextArchetype() && + "type metadata cannot contain an archetype"); return DbgTy; } DebugTypeInfo DebugTypeInfo::getArchetype(swift::Type Ty, llvm::Type *StorageTy, Size size, Alignment align) { DebugTypeInfo DbgTy(Ty.getPointer(), StorageTy, size, - align, true, true); + align, true, true, false); assert(StorageTy && "StorageType is a nullptr"); - assert(!DbgTy.isContextArchetype() && "type metadata cannot contain an archetype"); + assert(!DbgTy.isContextArchetype() && + "type metadata cannot contain an archetype"); return DbgTy; } DebugTypeInfo DebugTypeInfo::getForwardDecl(swift::Type Ty) { DebugTypeInfo DbgTy(Ty.getPointer(), nullptr, {}, Alignment(1), true, - false); + false, false); return DbgTy; } @@ -109,8 +115,8 @@ DebugTypeInfo DebugTypeInfo::getGlobal(SILGlobalVariable *GV, Type = DeclType.getPointer(); } DebugTypeInfo DbgTy(Type, StorageTy, size, align, ::hasDefaultAlignment(Type), - false); - assert(StorageTy && "StorageType is a nullptr"); + false, false); + assert(StorageTy && "FragmentStorageType is a nullptr"); assert(!DbgTy.isContextArchetype() && "type of global variable cannot be an archetype"); assert(align.getValue() != 0); @@ -118,20 +124,21 @@ DebugTypeInfo DebugTypeInfo::getGlobal(SILGlobalVariable *GV, } DebugTypeInfo DebugTypeInfo::getObjCClass(ClassDecl *theClass, - llvm::Type *StorageType, Size size, - Alignment align) { - DebugTypeInfo DbgTy(theClass->getInterfaceType().getPointer(), StorageType, - size, align, true, false); - assert(StorageType && "StorageType is a nullptr"); - assert(!DbgTy.isContextArchetype() && "type of objc class cannot be an archetype"); + llvm::Type *FragmentStorageType, + Size size, Alignment align) { + DebugTypeInfo DbgTy(theClass->getInterfaceType().getPointer(), + FragmentStorageType, size, align, true, false, false); + assert(FragmentStorageType && "FragmentStorageType is a nullptr"); + assert(!DbgTy.isContextArchetype() && + "type of objc class cannot be an archetype"); return DbgTy; } DebugTypeInfo DebugTypeInfo::getErrorResult(swift::Type Ty, llvm::Type *StorageType, Size size, Alignment align) { - assert(StorageType && "StorageType is a nullptr"); - return {Ty, StorageType, size, align, true, false}; + assert(StorageType && "FragmentStorageType is a nullptr"); + return {Ty, StorageType, size, align, true, false, false}; } bool DebugTypeInfo::operator==(DebugTypeInfo T) const { @@ -162,9 +169,9 @@ LLVM_DUMP_METHOD void DebugTypeInfo::dump() const { llvm::errs() << "Alignment " << align.getValue() << "] "; getType()->dump(llvm::errs()); - if (StorageType) { - llvm::errs() << "StorageType="; - StorageType->dump(); + if (FragmentStorageType) { + llvm::errs() << "FragmentStorageType="; + FragmentStorageType->dump(); } else llvm::errs() << "forward-declared\n"; } diff --git a/lib/IRGen/DebugTypeInfo.h b/lib/IRGen/DebugTypeInfo.h index aaa5c7e0e4678..abbd2eb4bf005 100644 --- a/lib/IRGen/DebugTypeInfo.h +++ b/lib/IRGen/DebugTypeInfo.h @@ -42,21 +42,24 @@ class DebugTypeInfo { TypeBase *Type = nullptr; /// Needed to determine the size of basic types and to determine /// the storage type for undefined variables. - llvm::Type *StorageType = nullptr; + llvm::Type *FragmentStorageType = nullptr; Optional size; Alignment align; bool DefaultAlignment = true; bool IsMetadataType = false; + bool SizeIsFragmentSize; public: DebugTypeInfo() = default; DebugTypeInfo(swift::Type Ty, llvm::Type *StorageTy, Optional SizeInBytes, Alignment AlignInBytes, - bool HasDefaultAlignment, bool IsMetadataType); + bool HasDefaultAlignment, bool IsMetadataType, + bool IsFragmentTypeInfo); /// Create type for a local variable. - static DebugTypeInfo getLocalVariable(VarDecl *Decl, - swift::Type Ty, const TypeInfo &Info); + static DebugTypeInfo getLocalVariable(VarDecl *Decl, swift::Type Ty, + const TypeInfo &Info, + bool IsFragmentTypeInfo); /// Create type for global type metadata. static DebugTypeInfo getMetadata(swift::Type Ty, llvm::Type *StorageTy, Size size, Alignment align); @@ -68,10 +71,12 @@ class DebugTypeInfo { static DebugTypeInfo getForwardDecl(swift::Type Ty); /// Create a standalone type from a TypeInfo object. - static DebugTypeInfo getFromTypeInfo(swift::Type Ty, const TypeInfo &Info); + static DebugTypeInfo getFromTypeInfo(swift::Type Ty, const TypeInfo &Info, + bool IsFragmentTypeInfo); /// Global variables. - static DebugTypeInfo getGlobal(SILGlobalVariable *GV, llvm::Type *StorageType, - Size size, Alignment align); + static DebugTypeInfo getGlobal(SILGlobalVariable *GV, + llvm::Type *StorageType, Size size, + Alignment align); /// ObjC classes. static DebugTypeInfo getObjCClass(ClassDecl *theClass, llvm::Type *StorageType, Size size, @@ -86,24 +91,29 @@ class DebugTypeInfo { // Determine whether this type is an Archetype dependent on a generic context. bool isContextArchetype() const { - if (auto archetype = Type->getWithoutSpecifierType()->getAs()) { + if (auto archetype = + Type->getWithoutSpecifierType()->getAs()) { return !isa(archetype->getRoot()); } return false; } - llvm::Type *getStorageType() const { + llvm::Type *getFragmentStorageType() const { if (size && size->isZero()) - assert(StorageType && "only defined types may have a size"); - return StorageType; + assert(FragmentStorageType && "only defined types may have a size"); + return FragmentStorageType; } - Optional getSize() const { return size; } + Optional getTypeSize() const { + return SizeIsFragmentSize ? llvm::None : size; + } + Optional getRawSize() const { return size; } void setSize(Size NewSize) { size = NewSize; } Alignment getAlignment() const { return align; } bool isNull() const { return Type == nullptr; } - bool isForwardDecl() const { return StorageType == nullptr; } + bool isForwardDecl() const { return FragmentStorageType == nullptr; } bool isMetadataType() const { return IsMetadataType; } bool hasDefaultAlignment() const { return DefaultAlignment; } + bool isSizeFragmentSize() const { return SizeIsFragmentSize; } bool operator==(DebugTypeInfo T) const; bool operator!=(DebugTypeInfo T) const; @@ -115,9 +125,10 @@ class DebugTypeInfo { /// A DebugTypeInfo with a defined size (that may be 0). class CompletedDebugTypeInfo : public DebugTypeInfo { CompletedDebugTypeInfo(DebugTypeInfo DbgTy) : DebugTypeInfo(DbgTy) {} + public: static Optional get(DebugTypeInfo DbgTy) { - if (!DbgTy.getSize()) + if (!DbgTy.getRawSize() || DbgTy.isSizeFragmentSize()) return {}; return CompletedDebugTypeInfo(DbgTy); } @@ -125,7 +136,7 @@ class CompletedDebugTypeInfo : public DebugTypeInfo { static Optional getFromTypeInfo(swift::Type Ty, const TypeInfo &Info) { return CompletedDebugTypeInfo::get( - DebugTypeInfo::getFromTypeInfo(Ty, Info)); + DebugTypeInfo::getFromTypeInfo(Ty, Info, /*IsFragment*/ false)); } Size::int_type getSizeValue() const { return size->getValue(); } @@ -144,7 +155,7 @@ template <> struct DenseMapInfo { static swift::irgen::DebugTypeInfo getTombstoneKey() { return swift::irgen::DebugTypeInfo( llvm::DenseMapInfo::getTombstoneKey(), nullptr, - swift::irgen::Size(0), swift::irgen::Alignment(), false, false); + swift::irgen::Size(0), swift::irgen::Alignment(), false, false, false); } static unsigned getHashValue(swift::irgen::DebugTypeInfo Val) { return DenseMapInfo::getHashValue(Val.getType()); diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index d4505636b978e..2815aa85435cb 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -616,8 +616,8 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { void createParameterType(llvm::SmallVectorImpl &Parameters, SILType type) { auto RealType = type.getASTType(); - auto DbgTy = - DebugTypeInfo::getFromTypeInfo(RealType, IGM.getTypeInfo(type)); + auto DbgTy = DebugTypeInfo::getFromTypeInfo(RealType, IGM.getTypeInfo(type), + /*isFragment*/ false); Parameters.push_back(getOrCreateType(DbgTy)); } @@ -981,7 +981,7 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { llvm::DINode::DIFlags Flags) { StringRef Name = Decl->getName().str(); unsigned SizeOfByte = CI.getTargetInfo().getCharWidth(); - unsigned SizeInBits = DbgTy.getSize()->getValue() * SizeOfByte; + unsigned SizeInBits = DbgTy.getSizeValue() * SizeOfByte; // Default, since Swift doesn't allow specifying a custom alignment. unsigned AlignInBits = 0; @@ -1012,8 +1012,9 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { // all enum values. Use the raw type for the debug type, but // the storage size from the enum. ElemDbgTy = CompletedDebugTypeInfo::get( - DebugTypeInfo(Decl->getRawType(), DbgTy.getStorageType(), - DbgTy.getSize(), DbgTy.getAlignment(), true, false)); + DebugTypeInfo(Decl->getRawType(), DbgTy.getFragmentStorageType(), + DbgTy.getRawSize(), DbgTy.getAlignment(), true, false, + DbgTy.isSizeFragmentSize())); else if (auto ArgTy = ElemDecl->getArgumentInterfaceType()) { // A discriminated union. This should really be described as a // DW_TAG_variant_type. For now only describing the data. @@ -1024,8 +1025,9 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { // Discriminated union case without argument. Fallback to Int // as the element type; there is no storage here. Type IntTy = IGM.Context.getIntType(); - ElemDbgTy = CompletedDebugTypeInfo::get(DebugTypeInfo( - IntTy, DbgTy.getStorageType(), Size(0), Alignment(1), true, false)); + ElemDbgTy = CompletedDebugTypeInfo::get( + DebugTypeInfo(IntTy, DbgTy.getFragmentStorageType(), Size(0), + Alignment(1), true, false, false)); } if (!ElemDbgTy) { // Without complete type info we can only create a forward decl. @@ -1049,19 +1051,18 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { } llvm::DIType *getOrCreateDesugaredType(Type Ty, DebugTypeInfo DbgTy) { - DebugTypeInfo BlandDbgTy(Ty, DbgTy.getStorageType(), DbgTy.getSize(), - DbgTy.getAlignment(), DbgTy.hasDefaultAlignment(), - DbgTy.isMetadataType()); + DebugTypeInfo BlandDbgTy( + Ty, DbgTy.getFragmentStorageType(), DbgTy.getRawSize(), + DbgTy.getAlignment(), DbgTy.hasDefaultAlignment(), + DbgTy.isMetadataType(), DbgTy.isSizeFragmentSize()); return getOrCreateType(BlandDbgTy); } uint64_t getSizeOfBasicType(CompletedDebugTypeInfo DbgTy) { uint64_t SizeOfByte = CI.getTargetInfo().getCharWidth(); - uint64_t BitWidth = 0; - if (DbgTy.getSize()) - BitWidth = DbgTy.getSizeValue() * SizeOfByte; - llvm::Type *StorageType = DbgTy.getStorageType() - ? DbgTy.getStorageType() + uint64_t BitWidth = DbgTy.getSizeValue() * SizeOfByte; + llvm::Type *StorageType = DbgTy.getFragmentStorageType() + ? DbgTy.getFragmentStorageType() : IGM.DataLayout.getSmallestLegalIntType( IGM.getLLVMContext(), BitWidth); @@ -1294,8 +1295,8 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { uint64_t SizeOfByte = CI.getTargetInfo().getCharWidth(); // FIXME: SizeInBits is redundant with DbgTy, remove it. uint64_t SizeInBits = 0; - if (DbgTy.getSize()) - SizeInBits = DbgTy.getSize()->getValue() * SizeOfByte; + if (DbgTy.getTypeSize()) + SizeInBits = DbgTy.getTypeSize()->getValue() * SizeOfByte; unsigned AlignInBits = DbgTy.hasDefaultAlignment() ? 0 : DbgTy.getAlignment().getValue() * SizeOfByte; @@ -1410,7 +1411,7 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { SizeInBits, AlignInBits, Flags, nullptr, llvm::dwarf::DW_LANG_Swift, MangledName); StringRef Name = Decl->getName().str(); - if (DbgTy.getSize()) + if (DbgTy.getTypeSize()) return createOpaqueStruct(Scope, Name, File, FwdDeclLine, SizeInBits, AlignInBits, Flags, MangledName); return DBuilder.createForwardDecl( @@ -1532,7 +1533,8 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { auto PTy = IGM.getLoweredType(ProtocolDecl->getInterfaceType()).getASTType(); auto PDbgTy = DebugTypeInfo::getFromTypeInfo( - ProtocolDecl->getInterfaceType(), IGM.getTypeInfoForLowered(PTy)); + ProtocolDecl->getInterfaceType(), IGM.getTypeInfoForLowered(PTy), + false); auto PDITy = getOrCreateType(PDbgTy); Protocols.push_back( DBuilder.createInheritance(FwdDecl.get(), PDITy, 0, 0, Flags)); @@ -1603,7 +1605,7 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { auto *BuiltinVectorTy = BaseTy->castTo(); auto ElemTy = BuiltinVectorTy->getElementType(); auto ElemDbgTy = DebugTypeInfo::getFromTypeInfo( - ElemTy, IGM.getTypeInfoForUnlowered(ElemTy)); + ElemTy, IGM.getTypeInfoForUnlowered(ElemTy), false); unsigned Count = BuiltinVectorTy->getNumElements(); auto Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1); return DBuilder.createVectorType(SizeInBits, AlignInBits, @@ -1637,9 +1639,10 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { // For TypeAlias types, the DeclContext for the aliased type is // in the decl of the alias type. - DebugTypeInfo AliasedDbgTy(AliasedTy, DbgTy.getStorageType(), - DbgTy.getSize(), DbgTy.getAlignment(), - DbgTy.hasDefaultAlignment(), false); + DebugTypeInfo AliasedDbgTy(AliasedTy, DbgTy.getFragmentStorageType(), + DbgTy.getRawSize(), DbgTy.getAlignment(), + DbgTy.hasDefaultAlignment(), false, + DbgTy.isSizeFragmentSize()); return DBuilder.createTypedef(getOrCreateType(AliasedDbgTy), MangledName, File, 0, Scope); } @@ -2315,7 +2318,8 @@ IRGenDebugInfoImpl::emitFunction(const SILDebugScope *DS, llvm::Function *Fn, ErrorInfo->getReturnValueType(IGM.getSILModule(), FnTy, IGM.getMaximalTypeExpansionContext()), IGM.getTypeInfo(IGM.silConv.getSILType( - *ErrorInfo, FnTy, IGM.getMaximalTypeExpansionContext()))); + *ErrorInfo, FnTy, IGM.getMaximalTypeExpansionContext())), + false); Error = DBuilder.getOrCreateArray({getOrCreateType(DTI)}).get(); } @@ -2437,7 +2441,7 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( if (DbgTy.getType()->hasOpenedExistential()) return; - if (!DbgTy.getSize()) + if (!DbgTy.getTypeSize()) DbgTy.setSize(getStorageSize(IGM.DataLayout, Storage)); SILVarScope KeyScope = DS; @@ -2539,8 +2543,11 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( // Sanity checks. assert(SizeInBits && "zero-sized piece"); - assert(SizeInBits < getSizeInBits(Var) && "piece covers entire var"); - assert(OffsetInBits + SizeInBits <= getSizeInBits(Var) && "pars > totum"); + if (getSizeInBits(Var)) { + assert(SizeInBits < getSizeInBits(Var) && "piece covers entire var"); + assert(OffsetInBits + SizeInBits <= getSizeInBits(Var) && + "pars > totum"); + } // Add the piece DWARF expression. Operands.push_back(llvm::dwarf::DW_OP_LLVM_fragment); diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp index 21a1afcf6b399..25ea35af804da 100644 --- a/lib/IRGen/IRGenSIL.cpp +++ b/lib/IRGen/IRGenSIL.cpp @@ -4731,11 +4731,15 @@ void IRGenSILFunction::visitDebugValueInst(DebugValueInst *i) { VarInfo->Name = getVarName(i, IsAnonymous); DebugTypeInfo DbgTy; SILType SILTy; - if (auto MaybeSILTy = VarInfo->Type) + bool IsFragmentType = false; + if (auto MaybeSILTy = VarInfo->Type) { // If there is auxiliary type info, use it SILTy = *MaybeSILTy; - else + } else { SILTy = SILVal->getType(); + if (VarInfo->DIExpr) + IsFragmentType = VarInfo->DIExpr.hasFragment(); + } auto RealTy = SILTy.getASTType(); if (IsAddrVal && IsInCoro) @@ -4751,11 +4755,12 @@ void IRGenSILFunction::visitDebugValueInst(DebugValueInst *i) { // Figure out the debug variable type if (VarDecl *Decl = i->getDecl()) { - DbgTy = DebugTypeInfo::getLocalVariable( - Decl, RealTy, getTypeInfo(SILVal->getType())); + DbgTy = DebugTypeInfo::getLocalVariable(Decl, RealTy, getTypeInfo(SILTy), + IsFragmentType); } else if (!SILTy.hasArchetype() && !VarInfo->Name.empty()) { // Handle the cases that read from a SIL file - DbgTy = DebugTypeInfo::getFromTypeInfo(RealTy, getTypeInfo(SILTy)); + DbgTy = DebugTypeInfo::getFromTypeInfo(RealTy, getTypeInfo(SILTy), + IsFragmentType); } else return; @@ -5110,18 +5115,24 @@ void IRGenSILFunction::emitDebugInfoForAllocStack(AllocStackInst *i, } SILType SILTy; - if (auto MaybeSILTy = VarInfo->Type) + bool IsFragmentType = false; + if (auto MaybeSILTy = VarInfo->Type) { // If there is auxiliary type info, use it SILTy = *MaybeSILTy; - else + } else { SILTy = i->getType(); + if (VarInfo->DIExpr) + IsFragmentType = VarInfo->DIExpr.hasFragment(); + } auto RealType = SILTy.getASTType(); DebugTypeInfo DbgTy; if (Decl) { - DbgTy = DebugTypeInfo::getLocalVariable(Decl, RealType, type); + DbgTy = + DebugTypeInfo::getLocalVariable(Decl, RealType, type, IsFragmentType); } else if (i->getFunction()->isBare() && !SILTy.hasArchetype() && !VarInfo->Name.empty()) { - DbgTy = DebugTypeInfo::getFromTypeInfo(RealType, getTypeInfo(SILTy)); + DbgTy = DebugTypeInfo::getFromTypeInfo(RealType, getTypeInfo(SILTy), + IsFragmentType); } else return; @@ -5341,7 +5352,7 @@ void IRGenSILFunction::visitAllocBoxInst(swift::AllocBoxInst *i) { IGM.getMaximalTypeExpansionContext(), i->getBoxType(), IGM.getSILModule().Types, 0); auto RealType = SILTy.getASTType(); - auto DbgTy = DebugTypeInfo::getLocalVariable(Decl, RealType, type); + auto DbgTy = DebugTypeInfo::getLocalVariable(Decl, RealType, type, false); auto VarInfo = i->getVarInfo(); assert(VarInfo && "debug_value without debug info"); From eb2b7ba4b824b90bc0836ca1cb16c1302e570874 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Thu, 16 Sep 2021 18:17:04 -0700 Subject: [PATCH 106/116] Fix local variable uniquing to take into account tail-allocated variable names --- lib/IRGen/IRGenDebugInfo.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index 2815aa85435cb..4aeb821599a8b 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -47,6 +47,7 @@ #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Serialization/ASTReader.h" +#include "llvm/ADT/StringSet.h" #include "llvm/Config/config.h" #include "llvm/IR/DIBuilder.h" #include "llvm/IR/DebugInfo.h" @@ -107,9 +108,9 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { const PathRemapper &DebugPrefixMap; /// Various caches. - /// @{ - using SILVarScope = llvm::PointerUnion; - using VarID = std::tuple; + /// \{ + llvm::StringSet<> VarNames; + using VarID = std::tuple; llvm::DenseMap LocalVarCache; llvm::DenseMap ScopeCache; llvm::DenseMap InlinedAtCache; @@ -120,7 +121,7 @@ class IRGenDebugInfoImpl : public IRGenDebugInfo { llvm::StringMap DIFileCache; TrackingDIRefMap DIRefMap; TrackingDIRefMap InnerTypeCache; - /// @} + /// \} /// A list of replaceable fwddecls that need to be RAUWed at the end. std::vector> ReplaceMap; @@ -2444,7 +2445,6 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( if (!DbgTy.getTypeSize()) DbgTy.setSize(getStorageSize(IGM.DataLayout, Storage)); - SILVarScope KeyScope = DS; auto *Scope = dyn_cast_or_null(getOrCreateScope(DS)); assert(Scope && "variable has no local scope"); auto DInstLoc = getStartLocation(DbgInstLoc); @@ -2455,7 +2455,6 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( if (ArgNo > 0) { while (isa(Scope)) Scope = cast(Scope)->getScope(); - KeyScope = DS->getInlinedFunction(); } assert(isa_and_nonnull(Scope) && "variable has no scope"); llvm::DIFile *Unit = getFile(Scope); @@ -2476,22 +2475,25 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( // Create the descriptor for the variable. unsigned DVarLine = DInstLine; + uint16_t DVarCol = 0; if (VarInfo.Loc) { auto DVarLoc = getStartLocation(VarInfo.Loc); DVarLine = DVarLoc.line; + DVarCol = DVarLoc.column; } llvm::DIScope *VarScope = Scope; if (ArgNo == 0 && VarInfo.Scope) { if (auto *VS = dyn_cast_or_null( getOrCreateScope(VarInfo.Scope))) { VarScope = VS; - KeyScope = VarInfo.Scope; } } // Get or create the DILocalVariable. llvm::DILocalVariable *Var; - VarID Key(KeyScope, VarInfo.Name.data(), ArgNo); + // VarInfo.Name points into tail-allocated storage in debug_value insns. + llvm::StringRef UniqueName = VarNames.insert(VarInfo.Name).first->getKey(); + VarID Key(VarScope, UniqueName, DVarLine, DVarCol); auto CachedVar = LocalVarCache.find(Key); if (CachedVar != LocalVarCache.end()) { Var = cast(CachedVar->second); From 35863895dcecdc06ead71f39afa6e8efcdadeb54 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 17 Sep 2021 15:56:00 -0700 Subject: [PATCH 107/116] Use a custom diagnostic when parsing SIL DIExpressions --- include/swift/AST/DiagnosticsParse.def | 2 ++ lib/SIL/Parser/ParseSIL.cpp | 3 +-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/include/swift/AST/DiagnosticsParse.def b/include/swift/AST/DiagnosticsParse.def index ff2766a2b4503..829f06d6ac21a 100644 --- a/include/swift/AST/DiagnosticsParse.def +++ b/include/swift/AST/DiagnosticsParse.def @@ -522,6 +522,8 @@ ERROR(sil_invalid_column_in_sil_location,none, "column number must be a positive integer", ()) ERROR(sil_invalid_scope_slot,none, "scope number must be a positive integer ", ()) +ERROR(sil_invalid_constant,none, + "constant operand must be an integer literal ", ()) ERROR(sil_scope_undeclared,none, "scope number %0 needs to be declared before first use", (unsigned)) ERROR(sil_scope_redefined,none, diff --git a/lib/SIL/Parser/ParseSIL.cpp b/lib/SIL/Parser/ParseSIL.cpp index 7a24cfb0ed324..9db8364191dee 100644 --- a/lib/SIL/Parser/ParseSIL.cpp +++ b/lib/SIL/Parser/ParseSIL.cpp @@ -1701,8 +1701,7 @@ bool SILParser::parseSILDebugInfoExpression(SILDebugInfoExpression &DIExpr) { IsNegative = true; } int64_t Val; - // FIXME: Use the correct diagnostic - if (parseInteger(Val, diag::sil_invalid_scope_slot)) + if (parseInteger(Val, diag::sil_invalid_constant)) return true; if (IsNegative) Val = -Val; From dc50c93301f58199696e4c0437cb091bfd336c64 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 17 Sep 2021 15:56:33 -0700 Subject: [PATCH 108/116] Handle missing DIExprOperator kinds in IRGenDebugInfo --- lib/IRGen/IRGenDebugInfo.cpp | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index 4aeb821599a8b..f2e223c17f4bd 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -2421,8 +2421,22 @@ bool IRGenDebugInfoImpl::buildDebugInfoExpression( case SILDIExprOperator::Dereference: Operands.push_back(llvm::dwarf::DW_OP_deref); break; - default: - llvm_unreachable("Unrecognized operator"); + case SILDIExprOperator::Plus: + Operands.push_back(llvm::dwarf::DW_OP_plus); + break; + case SILDIExprOperator::Minus: + Operands.push_back(llvm::dwarf::DW_OP_minus); + break; + case SILDIExprOperator::ConstUInt: + Operands.push_back(llvm::dwarf::DW_OP_constu); + Operands.push_back(*ExprOperand[1].getAsConstInt()); + break; + case SILDIExprOperator::ConstSInt: + Operands.push_back(llvm::dwarf::DW_OP_consts); + Operands.push_back(*ExprOperand[1].getAsConstInt()); + break; + case SILDIExprOperator::INVALID: + return false; } } return true; From 2edf09831e39ab014317e21c24ff9ce502cf0760 Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Mon, 20 Sep 2021 15:38:05 -0700 Subject: [PATCH 109/116] Disable test on 32-bit CPUs --- test/DebugInfo/constant_propagation.sil | 1 + 1 file changed, 1 insertion(+) diff --git a/test/DebugInfo/constant_propagation.sil b/test/DebugInfo/constant_propagation.sil index b968500f05a81..055315d765bae 100644 --- a/test/DebugInfo/constant_propagation.sil +++ b/test/DebugInfo/constant_propagation.sil @@ -1,4 +1,5 @@ // RUN: %target-sil-opt -enable-sil-verify-all -sil-print-debuginfo -diagnostic-constant-propagation %s | %FileCheck %s +// REQUIRES: CPU=arm64 || CPU=x86_64 sil_stage canonical From 0e83389e3575bf0f87dc8d2c74317da18fd57a5a Mon Sep 17 00:00:00 2001 From: Adrian Prantl Date: Fri, 24 Sep 2021 14:48:22 -0700 Subject: [PATCH 110/116] Wrap assertion code in infndef NDEBUG to fix non-asserts build. --- lib/IRGen/IRGenDebugInfo.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index f2e223c17f4bd..24aa94a7fbe42 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -2558,12 +2558,14 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( AlignInBits = SizeOfByte; // Sanity checks. +#ifndef NDEBUG assert(SizeInBits && "zero-sized piece"); if (getSizeInBits(Var)) { assert(SizeInBits < getSizeInBits(Var) && "piece covers entire var"); assert(OffsetInBits + SizeInBits <= getSizeInBits(Var) && "pars > totum"); } +#endif // Add the piece DWARF expression. Operands.push_back(llvm::dwarf::DW_OP_LLVM_fragment); From 1c8149b564195e7506523ab28243439be04f1702 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Mon, 27 Sep 2021 11:01:19 -0700 Subject: [PATCH 111/116] tests: disable Concurrency.throwing The rebranch is exposing a UaF/stack corruption, disable this for the time being. --- test/Concurrency/throwing.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/Concurrency/throwing.swift b/test/Concurrency/throwing.swift index 0f5a8fe83044a..4e4c73fb86327 100644 --- a/test/Concurrency/throwing.swift +++ b/test/Concurrency/throwing.swift @@ -6,6 +6,9 @@ // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime +// SR-15252 +// XFAIL: OS=windows-msvc + import _Concurrency import StdlibUnittest From 72089ec6ce7da4dcd41494524fe3872a7f4c8cf0 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Mon, 27 Sep 2021 14:46:58 -0700 Subject: [PATCH 112/116] Disabling ClangImporter/overlay.swift MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (Swift hashes) The last good merge commit was: bc61e6adeea The first bad merge commit was: 0d6ac8f2cbf The commit where it broke was 7e77bc4d877. This commit only changes a test and shouldn’t have affected the failing test. I'm disabling this test for now since we need to rebranch. --- test/ClangImporter/overlay.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/ClangImporter/overlay.swift b/test/ClangImporter/overlay.swift index 6f949d87ae74a..a36cf722a6931 100644 --- a/test/ClangImporter/overlay.swift +++ b/test/ClangImporter/overlay.swift @@ -3,6 +3,8 @@ // REQUIRES: objc_interop +// REQUIRES: rdar83592270 + // Do not import Foundation! This tests indirect visibility. #if REVERSED import Redeclaration From 9d3b7590ef1d3a77de8b40208e43dccffc64f43d Mon Sep 17 00:00:00 2001 From: Mishal Shah Date: Mon, 27 Sep 2021 15:57:14 -0700 Subject: [PATCH 113/116] Update llvm-project branch to stable/20210726 --- utils/update_checkout/update-checkout-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/update_checkout/update-checkout-config.json b/utils/update_checkout/update-checkout-config.json index b45976f3ce5f8..dbada66fbdb71 100644 --- a/utils/update_checkout/update-checkout-config.json +++ b/utils/update_checkout/update-checkout-config.json @@ -69,7 +69,7 @@ "main": { "aliases": ["master", "swift/main", "main"], "repos": { - "llvm-project": "swift/main", + "llvm-project": "stable/20210726", "swift": "main", "cmark": "main", "llbuild": "main", From 2b9a9e4bd67f5cdb643a952835f4055dd6387054 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Mon, 27 Sep 2021 17:15:11 -0700 Subject: [PATCH 114/116] LLVMPasses: adapt to ba664d9 Adapt to API changes in ba664d9, where `AAQueryInfo` now requires the capturing information. Switch to the new `SimpleAAQueryInfo` which maintains the status quo for alias analysis. --- include/swift/LLVMPasses/Passes.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/swift/LLVMPasses/Passes.h b/include/swift/LLVMPasses/Passes.h index d716d3087ec78..09abe2847b811 100644 --- a/include/swift/LLVMPasses/Passes.h +++ b/include/swift/LLVMPasses/Passes.h @@ -34,7 +34,7 @@ namespace swift { using AAResultBase::getModRefInfo; llvm::ModRefInfo getModRefInfo(const llvm::CallBase *Call, const llvm::MemoryLocation &Loc) { - llvm::AAQueryInfo AAQI; + llvm::SimpleAAQueryInfo AAQI; return getModRefInfo(Call, Loc, AAQI); } llvm::ModRefInfo getModRefInfo(const llvm::CallBase *Call, From 6956b7c5c901e7b9b50d23ab5a9e083ddc888fb5 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Tue, 28 Sep 2021 10:05:05 -0700 Subject: [PATCH 115/116] Replace /usr/bin/python with /usr/env/python /usr/bin/python doesn't exist on ubuntu 20.04 causing tests to fail. I've updated the shebangs everywhere to use `/usr/bin/env python` instead. --- benchmark/scripts/compare_perf_tests.py | 2 +- benchmark/scripts/test_Benchmark_Driver.py | 2 +- benchmark/scripts/test_compare_perf_tests.py | 2 +- benchmark/scripts/test_utils.py | 2 +- test/ScanDependencies/Inputs/CommandRunner.py | 2 +- utils/jobstats/__init__.py | 2 +- utils/jobstats/jobstats.py | 2 +- utils/process-stats-dir.py | 2 +- utils/rusage.py | 2 +- validation-test/ParseableInterface/verify_all_overlays.py | 2 +- validation-test/SIL/verify_all_overlays.py | 4 ++-- 11 files changed, 12 insertions(+), 12 deletions(-) diff --git a/benchmark/scripts/compare_perf_tests.py b/benchmark/scripts/compare_perf_tests.py index 57ad939720820..5c4af709da146 100755 --- a/benchmark/scripts/compare_perf_tests.py +++ b/benchmark/scripts/compare_perf_tests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # -*- coding: utf-8 -*- # ===--- compare_perf_tests.py -------------------------------------------===// diff --git a/benchmark/scripts/test_Benchmark_Driver.py b/benchmark/scripts/test_Benchmark_Driver.py index 0f83eb74ca701..abc4ed18b3fea 100644 --- a/benchmark/scripts/test_Benchmark_Driver.py +++ b/benchmark/scripts/test_Benchmark_Driver.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # -*- coding: utf-8 -*- # ===--- test_Benchmark_Driver.py ----------------------------------------===// diff --git a/benchmark/scripts/test_compare_perf_tests.py b/benchmark/scripts/test_compare_perf_tests.py index 469c591afb3e2..20d821208f752 100644 --- a/benchmark/scripts/test_compare_perf_tests.py +++ b/benchmark/scripts/test_compare_perf_tests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # -*- coding: utf-8 -*- # ===--- test_compare_perf_tests.py --------------------------------------===// diff --git a/benchmark/scripts/test_utils.py b/benchmark/scripts/test_utils.py index 70465f0b83d52..05ab9d2a5c6c8 100644 --- a/benchmark/scripts/test_utils.py +++ b/benchmark/scripts/test_utils.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # -*- coding: utf-8 -*- # ===--- test_utils.py ---------------------------------------------------===// diff --git a/test/ScanDependencies/Inputs/CommandRunner.py b/test/ScanDependencies/Inputs/CommandRunner.py index c54adba3fce2c..c2812bb7cd964 100755 --- a/test/ScanDependencies/Inputs/CommandRunner.py +++ b/test/ScanDependencies/Inputs/CommandRunner.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python import subprocess import sys diff --git a/utils/jobstats/__init__.py b/utils/jobstats/__init__.py index 14e81ea2ea688..20b909c9baec3 100644 --- a/utils/jobstats/__init__.py +++ b/utils/jobstats/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # ==-- jobstats - support for reading the contents of stats dirs --==# # diff --git a/utils/jobstats/jobstats.py b/utils/jobstats/jobstats.py index 2fd29de5e24b8..c6fd1ed10ff31 100644 --- a/utils/jobstats/jobstats.py +++ b/utils/jobstats/jobstats.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # ==-- jobstats - support for reading the contents of stats dirs --==# # diff --git a/utils/process-stats-dir.py b/utils/process-stats-dir.py index 61ec73410e580..d6c933455b400 100755 --- a/utils/process-stats-dir.py +++ b/utils/process-stats-dir.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # ==-- process-stats-dir - summarize one or more Swift -stats-output-dirs --==# # diff --git a/utils/rusage.py b/utils/rusage.py index e0195ac1b513c..7dda698fca542 100755 --- a/utils/rusage.py +++ b/utils/rusage.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # utils/rusage.py - Utility to measure resource usage -*- python -*- # # This source file is part of the Swift.org open source project diff --git a/validation-test/ParseableInterface/verify_all_overlays.py b/validation-test/ParseableInterface/verify_all_overlays.py index 3b5a1aba2f69c..51f5471374d93 100755 --- a/validation-test/ParseableInterface/verify_all_overlays.py +++ b/validation-test/ParseableInterface/verify_all_overlays.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # Note that this test should still "pass" when no swiftinterfaces have been # generated. diff --git a/validation-test/SIL/verify_all_overlays.py b/validation-test/SIL/verify_all_overlays.py index 7f268287cefc1..f3719ad6fec52 100755 --- a/validation-test/SIL/verify_all_overlays.py +++ b/validation-test/SIL/verify_all_overlays.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python3 # RUN: ${python} %s %target-swiftmodule-name %platform-sdk-overlay-dir \ # RUN: %target-sil-opt -sdk %sdk -enable-sil-verify-all \ # RUN: -F %sdk/System/Library/PrivateFrameworks \ @@ -39,7 +39,7 @@ # llvm-bcanalyzer | not grep Unknown bcanalyzer_output = subprocess.check_output(["llvm-bcanalyzer", - module_path]) + module_path]).decode("utf-8") if "Unknown" in bcanalyzer_output: print(bcanalyzer_output) sys.exit(1) From 198858126d70c533463c7e6450d32cbefc489a15 Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Fri, 8 Oct 2021 12:25:49 -0700 Subject: [PATCH 116/116] Fix DebugInfo/prologue.swift for llvm-project commit 1813652b0398345c4b4407d5fd5ffb749830fdd4 removed the prologue_end, so this test started failing. That directive is now annotated with `is_stmt 0`. --- test/DebugInfo/prologue.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/DebugInfo/prologue.swift b/test/DebugInfo/prologue.swift index 4ff2fbeeedc56..7c6e125f9a91b 100644 --- a/test/DebugInfo/prologue.swift +++ b/test/DebugInfo/prologue.swift @@ -7,7 +7,7 @@ func markUsed(_ t: T) {} // CHECK: .file [[F:[0-9]+]] "{{.*}}prologue.swift" func bar(_ x: T, y: U) { markUsed("bar") } // CHECK: $s8prologue3bar_1yyx_q_tr0_lF: -// CHECK: .loc [[F]] 0 0 prologue_end +// CHECK: .loc [[F]] 0 0 is_stmt 0 // Make sure there is no allocation happening between the end of // prologue and the beginning of the function body. // CHECK-NOT: callq *