diff options
Diffstat (limited to 'contrib/llvm/tools')
298 files changed, 5172 insertions, 1809 deletions
diff --git a/contrib/llvm/tools/bugpoint/ToolRunner.cpp b/contrib/llvm/tools/bugpoint/ToolRunner.cpp index 10532ef8395b..70b18e3dbbf9 100644 --- a/contrib/llvm/tools/bugpoint/ToolRunner.cpp +++ b/contrib/llvm/tools/bugpoint/ToolRunner.cpp @@ -861,7 +861,7 @@ Error CC::MakeSharedObject(const std::string &InputFile, FileType fileType, errs() << "\n";); if (RunProgramWithTimeout(CCPath, &CCArgs[0], "", "", "")) return ProcessFailure(CCPath, &CCArgs[0]); - return Error::success();; + return Error::success(); } /// create - Try to find the CC executable diff --git a/contrib/llvm/tools/clang/include/clang-c/Index.h b/contrib/llvm/tools/clang/include/clang-c/Index.h index 4241e43a9697..f404e6d72ec9 100644 --- a/contrib/llvm/tools/clang/include/clang-c/Index.h +++ b/contrib/llvm/tools/clang/include/clang-c/Index.h @@ -171,7 +171,60 @@ typedef struct CXVersion { */ int Subminor; } CXVersion; - + +/** + * \brief Describes the exception specification of a cursor. + * + * A negative value indicates that the cursor is not a function declaration. + */ +enum CXCursor_ExceptionSpecificationKind { + + /** + * \brief The cursor has no exception specification. + */ + CXCursor_ExceptionSpecificationKind_None, + + /** + * \brief The cursor has exception specification throw() + */ + CXCursor_ExceptionSpecificationKind_DynamicNone, + + /** + * \brief The cursor has exception specification throw(T1, T2) + */ + CXCursor_ExceptionSpecificationKind_Dynamic, + + /** + * \brief The cursor has exception specification throw(...). + */ + CXCursor_ExceptionSpecificationKind_MSAny, + + /** + * \brief The cursor has exception specification basic noexcept. + */ + CXCursor_ExceptionSpecificationKind_BasicNoexcept, + + /** + * \brief The cursor has exception specification computed noexcept. + */ + CXCursor_ExceptionSpecificationKind_ComputedNoexcept, + + /** + * \brief The exception specification has not yet been evaluated. + */ + CXCursor_ExceptionSpecificationKind_Unevaluated, + + /** + * \brief The exception specification has not yet been instantiated. + */ + CXCursor_ExceptionSpecificationKind_Uninstantiated, + + /** + * \brief The exception specification has not been parsed yet. + */ + CXCursor_ExceptionSpecificationKind_Unparsed +}; + /** * \brief Provides a shared context for creating translation units. * @@ -3471,6 +3524,13 @@ CINDEX_LINKAGE enum CXCallingConv clang_getFunctionTypeCallingConv(CXType T); CINDEX_LINKAGE CXType clang_getResultType(CXType T); /** + * \brief Retrieve the exception specification type associated with a function type. + * + * If a non-function type is passed in, an error code of -1 is returned. + */ +CINDEX_LINKAGE int clang_getExceptionSpecificationType(CXType T); + +/** * \brief Retrieve the number of non-variadic parameters associated with a * function type. * @@ -3499,6 +3559,13 @@ CINDEX_LINKAGE unsigned clang_isFunctionTypeVariadic(CXType T); CINDEX_LINKAGE CXType clang_getCursorResultType(CXCursor C); /** + * \brief Retrieve the exception specification type associated with a given cursor. + * + * This only returns a valid result if the cursor refers to a function or method. + */ +CINDEX_LINKAGE int clang_getCursorExceptionSpecificationType(CXCursor C); + +/** * \brief Return 1 if the CXType is a POD (plain old data) type, and 0 * otherwise. */ diff --git a/contrib/llvm/tools/clang/include/clang/AST/ASTContext.h b/contrib/llvm/tools/clang/include/clang/AST/ASTContext.h index 4c379620ab2d..3b46d31458ce 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/ASTContext.h +++ b/contrib/llvm/tools/clang/include/clang/AST/ASTContext.h @@ -2050,6 +2050,11 @@ public: /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits. uint64_t getFieldOffset(const ValueDecl *FD) const; + /// Get the offset of an ObjCIvarDecl in bits. + uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, + const ObjCImplementationDecl *ID, + const ObjCIvarDecl *Ivar) const; + bool isNearlyEmpty(const CXXRecordDecl *RD) const; VTableContextBase *getVTableContext(); diff --git a/contrib/llvm/tools/clang/include/clang/AST/ASTStructuralEquivalence.h b/contrib/llvm/tools/clang/include/clang/AST/ASTStructuralEquivalence.h index 770bb5763fbd..23674c65f332 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/ASTStructuralEquivalence.h +++ b/contrib/llvm/tools/clang/include/clang/AST/ASTStructuralEquivalence.h @@ -62,9 +62,11 @@ struct StructuralEquivalenceContext { StructuralEquivalenceContext( ASTContext &FromCtx, ASTContext &ToCtx, llvm::DenseSet<std::pair<Decl *, Decl *>> &NonEquivalentDecls, - bool StrictTypeSpelling = false, bool Complain = true) + bool StrictTypeSpelling = false, bool Complain = true, + bool ErrorOnTagTypeMismatch = false) : FromCtx(FromCtx), ToCtx(ToCtx), NonEquivalentDecls(NonEquivalentDecls), - StrictTypeSpelling(StrictTypeSpelling), Complain(Complain), + StrictTypeSpelling(StrictTypeSpelling), + ErrorOnTagTypeMismatch(ErrorOnTagTypeMismatch), Complain(Complain), LastDiagFromC2(false) {} DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID); diff --git a/contrib/llvm/tools/clang/include/clang/AST/Decl.h b/contrib/llvm/tools/clang/include/clang/AST/Decl.h index 30552be9b381..08b34a75aa60 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/Decl.h +++ b/contrib/llvm/tools/clang/include/clang/AST/Decl.h @@ -2019,7 +2019,10 @@ public: /// These functions have special behavior under C++1y [expr.new]: /// An implementation is allowed to omit a call to a replaceable global /// allocation function. [...] - bool isReplaceableGlobalAllocationFunction() const; + /// + /// If this function is an aligned allocation/deallocation function, return + /// true through IsAligned. + bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const; /// Compute the language linkage. LanguageLinkage getLanguageLinkage() const; diff --git a/contrib/llvm/tools/clang/include/clang/AST/NSAPI.h b/contrib/llvm/tools/clang/include/clang/AST/NSAPI.h index 583f9d9f1deb..3757116e7c70 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/NSAPI.h +++ b/contrib/llvm/tools/clang/include/clang/AST/NSAPI.h @@ -49,7 +49,7 @@ public: NSStr_initWithString, NSStr_initWithUTF8String }; - static const unsigned NumNSStringMethods = 5; + static const unsigned NumNSStringMethods = 6; IdentifierInfo *getNSClassId(NSClassIdKindKind K) const; @@ -112,7 +112,7 @@ public: NSMutableDict_setObjectForKeyedSubscript, NSMutableDict_setValueForKey }; - static const unsigned NumNSDictionaryMethods = 14; + static const unsigned NumNSDictionaryMethods = 13; /// \brief The Objective-C NSDictionary selectors. Selector getNSDictionarySelector(NSDictionaryMethodKind MK) const; diff --git a/contrib/llvm/tools/clang/include/clang/AST/OpenMPClause.h b/contrib/llvm/tools/clang/include/clang/AST/OpenMPClause.h index f977e63e04f6..14e73819f53d 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/OpenMPClause.h +++ b/contrib/llvm/tools/clang/include/clang/AST/OpenMPClause.h @@ -20,6 +20,7 @@ #include "clang/AST/Stmt.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" +#include "llvm/ADT/MapVector.h" namespace clang { @@ -3001,7 +3002,7 @@ protected: // Organize the components by declaration and retrieve the original // expression. Original expressions are always the first component of the // mappable component list. - llvm::DenseMap<ValueDecl *, SmallVector<MappableExprComponentListRef, 8>> + llvm::MapVector<ValueDecl *, SmallVector<MappableExprComponentListRef, 8>> ComponentListMap; { auto CI = ComponentLists.begin(); diff --git a/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h b/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h index ad3f40d0d3f6..152e05bca740 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h +++ b/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h @@ -593,6 +593,16 @@ bool RecursiveASTVisitor<Derived>::PostVisitStmt(Stmt *S) { #define STMT(CLASS, PARENT) \ case Stmt::CLASS##Class: \ TRY_TO(WalkUpFrom##CLASS(static_cast<CLASS *>(S))); break; +#define INITLISTEXPR(CLASS, PARENT) \ + case Stmt::CLASS##Class: \ + { \ + auto ILE = static_cast<CLASS *>(S); \ + if (auto Syn = ILE->isSemanticForm() ? ILE->getSyntacticForm() : ILE) \ + TRY_TO(WalkUpFrom##CLASS(Syn)); \ + if (auto Sem = ILE->isSemanticForm() ? ILE : ILE->getSemanticForm()) \ + TRY_TO(WalkUpFrom##CLASS(Sem)); \ + break; \ + } #include "clang/AST/StmtNodes.inc" } @@ -2220,13 +2230,15 @@ bool RecursiveASTVisitor<Derived>::TraverseSynOrSemInitListExpr( // the syntactic and the semantic form. // // There is no guarantee about which form \p S takes when this method is called. -DEF_TRAVERSE_STMT(InitListExpr, { +template <typename Derived> +bool RecursiveASTVisitor<Derived>::TraverseInitListExpr( + InitListExpr *S, DataRecursionQueue *Queue) { TRY_TO(TraverseSynOrSemInitListExpr( S->isSemanticForm() ? S->getSyntacticForm() : S, Queue)); TRY_TO(TraverseSynOrSemInitListExpr( S->isSemanticForm() ? S : S->getSemanticForm(), Queue)); - ShouldVisitChildren = false; -}) + return true; +} // GenericSelectionExpr is a special case because the types and expressions // are interleaved. We also need to watch out for null types (default diff --git a/contrib/llvm/tools/clang/include/clang/AST/Redeclarable.h b/contrib/llvm/tools/clang/include/clang/AST/Redeclarable.h index cd5f186a2086..89a9d3c4cc21 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/Redeclarable.h +++ b/contrib/llvm/tools/clang/include/clang/AST/Redeclarable.h @@ -21,6 +21,60 @@ namespace clang { class ASTContext; +// Some notes on redeclarables: +// +// - Every redeclarable is on a circular linked list. +// +// - Every decl has a pointer to the first element of the chain _and_ a +// DeclLink that may point to one of 3 possible states: +// - the "previous" (temporal) element in the chain +// - the "latest" (temporal) element in the chain +// - the an "uninitialized-latest" value (when newly-constructed) +// +// - The first element is also often called the canonical element. Every +// element has a pointer to it so that "getCanonical" can be fast. +// +// - Most links in the chain point to previous, except the link out of +// the first; it points to latest. +// +// - Elements are called "first", "previous", "latest" or +// "most-recent" when referring to temporal order: order of addition +// to the chain. +// +// - To make matters confusing, the DeclLink type uses the term "next" +// for its pointer-storage internally (thus functions like +// NextIsPrevious). It's easiest to just ignore the implementation of +// DeclLink when making sense of the redeclaration chain. +// +// - There's also a "definition" link for several types of +// redeclarable, where only one definition should exist at any given +// time (and the defn pointer is stored in the decl's "data" which +// is copied to every element on the chain when it's changed). +// +// Here is some ASCII art: +// +// "first" "latest" +// "canonical" "most recent" +// +------------+ first +--------------+ +// | | <--------------------------- | | +// | | | | +// | | | | +// | | +--------------+ | | +// | | first | | | | +// | | <---- | | | | +// | | | | | | +// | @class A | link | @interface A | link | @class A | +// | seen first | <---- | seen second | <---- | seen third | +// | | | | | | +// +------------+ +--------------+ +--------------+ +// | data | defn | data | defn | data | +// | | ----> | | <---- | | +// +------------+ +--------------+ +--------------+ +// | | ^ ^ +// | |defn | | +// | link +-----+ | +// +-->-------------------------------------------+ + /// \brief Provides common interface for the Decls that can be redeclared. template<typename decl_type> class Redeclarable { diff --git a/contrib/llvm/tools/clang/include/clang/Basic/AttrDocs.td b/contrib/llvm/tools/clang/include/clang/Basic/AttrDocs.td index 65dd7445ba26..2987f07d8bb4 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/AttrDocs.td +++ b/contrib/llvm/tools/clang/include/clang/Basic/AttrDocs.td @@ -605,20 +605,27 @@ semantics: for ``T`` and ``U`` to be incompatible. The declaration of ``overloadable`` functions is restricted to function -declarations and definitions. Most importantly, if any function with a given -name is given the ``overloadable`` attribute, then all function declarations -and definitions with that name (and in that scope) must have the -``overloadable`` attribute. This rule even applies to redeclarations of -functions whose original declaration had the ``overloadable`` attribute, e.g., +declarations and definitions. If a function is marked with the ``overloadable`` +attribute, then all declarations and definitions of functions with that name, +except for at most one (see the note below about unmarked overloads), must have +the ``overloadable`` attribute. In addition, redeclarations of a function with +the ``overloadable`` attribute must have the ``overloadable`` attribute, and +redeclarations of a function without the ``overloadable`` attribute must *not* +have the ``overloadable`` attribute. e.g., .. code-block:: c int f(int) __attribute__((overloadable)); float f(float); // error: declaration of "f" must have the "overloadable" attribute + int f(int); // error: redeclaration of "f" must have the "overloadable" attribute int g(int) __attribute__((overloadable)); int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute + int h(int); + int h(int) __attribute__((overloadable)); // error: declaration of "h" must not + // have the "overloadable" attribute + Functions marked ``overloadable`` must have prototypes. Therefore, the following code is ill-formed: @@ -651,7 +658,28 @@ caveats to this use of name mangling: linkage specification, it's name *will* be mangled in the same way as it would in C. -Query for this feature with ``__has_extension(attribute_overloadable)``. +For the purpose of backwards compatibility, at most one function with the same +name as other ``overloadable`` functions may omit the ``overloadable`` +attribute. In this case, the function without the ``overloadable`` attribute +will not have its name mangled. + +For example: + +.. code-block:: c + + // Notes with mangled names assume Itanium mangling. + int f(int); + int f(double) __attribute__((overloadable)); + void foo() { + f(5); // Emits a call to f (not _Z1fi, as it would with an overload that + // was marked with overloadable). + f(1.0); // Emits a call to _Z1fd. + } + +Support for unmarked overloads is not present in some versions of clang. You may +query for it using ``__has_extension(overloadable_unmarked)``. + +Query for this attribute with ``__has_attribute(overloadable)``. }]; } diff --git a/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsNios2.def b/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsNios2.def new file mode 100644 index 000000000000..d9697e795c44 --- /dev/null +++ b/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsNios2.def @@ -0,0 +1,70 @@ +//===-- BuiltinsNios2.def - Nios2 Builtin function database --------*- C++ -*-==// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the Nios2-specific builtin function database. Users of +// this file must define the BUILTIN macro to make use of this information. +// +//===----------------------------------------------------------------------===// + +// The format of this database matches clang/Basic/Builtins.def. + +#if defined(BUILTIN) && !defined(TARGET_BUILTIN) +# define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE) BUILTIN(ID, TYPE, ATTRS) +#endif + +// Nios2 R1 builtins: + +//int __builtin_ldbio(volatile const void *); +BUILTIN(__builtin_ldbio, "ivDC*", "") +//int __builtin_ldbuio(volatile const void *); +BUILTIN(__builtin_ldbuio, "ivDC*", "") +//int __builtin_ldhio(volatile const void *); +BUILTIN(__builtin_ldhio, "ivDC*", "") +//int __builtin_ldhuio(volatile const void *); +BUILTIN(__builtin_ldhuio, "ivDC*", "") +//int __builtin_ldwio(volatile const void *); +BUILTIN(__builtin_ldwio, "ivDC*", "") +//int __builtin_ldwuio(int); +BUILTIN(__builtin_ldwuio, "ii", "") +// int __builtin_rdctl(int); +BUILTIN(__builtin_rdctl, "iIi", "") +// void __builtin_wrctl(int, int); +BUILTIN(__builtin_wrctl, "vIii", "") +// int __builtin_rdprs(int, int); +BUILTIN(__builtin_rdprs, "iii", "") +//void __builtin_stbio(volatile void *, int); +BUILTIN(__builtin_stbio, "vvD*i", "") +//void __builtin_sthio(volatile void *, int); +BUILTIN(__builtin_sthio, "vvD*i", "") +//void __builtin_stwio(volatile void *, int); +BUILTIN(__builtin_stwio, "vvD*i", "") +//void __builtin_sync(void); +BUILTIN(__builtin_sync, "v", "") +// void __builtin_flushd(volatile void *); +BUILTIN(__builtin_flushd, "vvD*", "") +// void __builtin_flushda(volatile void *); +BUILTIN(__builtin_flushda, "vvD*", "") + +// Nios2 R2 builtins: + +// int __builtin_wrpie(int); +TARGET_BUILTIN(__builtin_wrpie, "ii", "", "nios2r2mandatory") +// void __builtin_eni(int); +TARGET_BUILTIN(__builtin_eni, "vi", "", "nios2r2mandatory") +// int __builtin_ldex(volatile const void *); +TARGET_BUILTIN(__builtin_ldex, "ivDC*", "", "nios2r2mandatory") +// int __builtin_stex(volatile void *, int); +TARGET_BUILTIN(__builtin_stex, "ivD*i", "", "nios2r2mandatory") +// int __builtin_ldsex(volatile const void *); +TARGET_BUILTIN(__builtin_ldsex, "ivDC*", "", "nios2r2mpx") +// int __builtin_stsex(volatile void *, int); +TARGET_BUILTIN(__builtin_stsex, "ivDC*i", "", "nios2r2mpx") + +#undef BUILTIN +#undef TARGET_BUILTIN diff --git a/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsWebAssembly.def b/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsWebAssembly.def index de56908be83c..19318dcebb9e 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsWebAssembly.def +++ b/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsWebAssembly.def @@ -21,4 +21,8 @@ BUILTIN(__builtin_wasm_current_memory, "z", "n") BUILTIN(__builtin_wasm_grow_memory, "zz", "n") +// Exception handling builtins. +BUILTIN(__builtin_wasm_throw, "vUiv*", "r") +BUILTIN(__builtin_wasm_rethrow, "v", "r") + #undef BUILTIN diff --git a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticASTKinds.td b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticASTKinds.td index 652d06278557..b3cba2066edd 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticASTKinds.td +++ b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticASTKinds.td @@ -200,12 +200,17 @@ def note_odr_defined_here : Note<"also defined here">; def err_odr_function_type_inconsistent : Error< "external function %0 declared with incompatible types in different " "translation units (%1 vs. %2)">; -def warn_odr_tag_type_inconsistent : Warning< - "type %0 has incompatible definitions in different translation units">, - InGroup<DiagGroup<"odr">>; +def warn_odr_tag_type_inconsistent + : Warning<"type %0 has incompatible definitions in different translation " + "units">, + InGroup<DiagGroup<"odr">>; +def err_odr_tag_type_inconsistent + : Error<"type %0 has incompatible definitions in different translation " + "units">; def note_odr_tag_kind_here: Note< "%0 is a %select{struct|interface|union|class|enum}1 here">; def note_odr_field : Note<"field %0 has type %1 here">; +def note_odr_field_name : Note<"field has name %0 here">; def note_odr_missing_field : Note<"no corresponding field here">; def note_odr_bit_field : Note<"bit-field %0 with type %1 and length %2 here">; def note_odr_not_bit_field : Note<"field %0 is not a bit-field">; diff --git a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticDriverKinds.td b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticDriverKinds.td index eb6dd37c148d..42e1e5edaf9e 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticDriverKinds.td +++ b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticDriverKinds.td @@ -138,6 +138,9 @@ def err_drv_cc_print_options_failure : Error< def err_drv_lto_without_lld : Error<"LTO requires -fuse-ld=lld">; def err_drv_preamble_format : Error< "incorrect format for -preamble-bytes=N,END">; +def err_invalid_ios_deployment_target : Error< + "invalid iOS deployment version '%0', iOS 10 is the maximum deployment " + "target for 32-bit targets">; def err_drv_conflicting_deployment_targets : Error< "conflicting deployment targets, both '%0' and '%1' are present in environment">; def err_arc_unsupported_on_runtime : Error< @@ -195,8 +198,8 @@ def warn_drv_unused_argument : Warning< def warn_drv_empty_joined_argument : Warning< "joined argument expects additional value: '%0'">, InGroup<UnusedCommandLineArgument>; -def warn_drv_fdiagnostics_show_hotness_requires_pgo : Warning< - "argument '-fdiagnostics-show-hotness' requires profile-guided optimization information">, +def warn_drv_diagnostics_hotness_requires_pgo : Warning< + "argument '%0' requires profile-guided optimization information">, InGroup<UnusedCommandLineArgument>; def warn_drv_clang_unsupported : Warning< "the clang compiler does not support '%0'">; diff --git a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td index 464c2425a1f1..3a0564806b32 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td +++ b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td @@ -311,6 +311,7 @@ def : DiagGroup<"nonportable-cfstrings">; def NonVirtualDtor : DiagGroup<"non-virtual-dtor">; def : DiagGroup<"effc++", [NonVirtualDtor]>; def OveralignedType : DiagGroup<"over-aligned">; +def AlignedAllocationUnavailable : DiagGroup<"aligned-allocation-unavailable">; def OldStyleCast : DiagGroup<"old-style-cast">; def : DiagGroup<"old-style-definition">; def OutOfLineDeclaration : DiagGroup<"out-of-line-declaration">; diff --git a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td index cba9b251215a..136e48ab5e54 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -3294,13 +3294,15 @@ def warn_iboutletcollection_property_assign : Warning< "IBOutletCollection properties should be copy/strong and not assign">, InGroup<ObjCInvalidIBOutletProperty>; -def err_attribute_overloadable_missing : Error< - "%select{overloaded function|redeclaration of}0 %1 must have the " - "'overloadable' attribute">; +def err_attribute_overloadable_mismatch : Error< + "redeclaration of %0 must %select{not |}1have the 'overloadable' attribute">; def note_attribute_overloadable_prev_overload : Note< - "previous overload of function is here">; + "previous %select{unmarked |}0overload of function is here">; def err_attribute_overloadable_no_prototype : Error< "'overloadable' function %0 must have a prototype">; +def err_attribute_overloadable_multiple_unmarked_overloads : Error< + "at most one overload for a given name may lack the 'overloadable' " + "attribute">; def warn_ns_attribute_wrong_return_type : Warning< "%0 attribute only applies to %select{functions|methods|properties}1 that " "return %select{an Objective-C object|a pointer|a non-retainable pointer}2">, @@ -6405,6 +6407,12 @@ def warn_overaligned_type : Warning< "type %0 requires %1 bytes of alignment and the default allocator only " "guarantees %2 bytes">, InGroup<OveralignedType>, DefaultIgnore; +def warn_aligned_allocation_unavailable :Warning< + "aligned %select{allocation|deallocation}0 function of type '%1' possibly " + "unavailable on %2">, InGroup<AlignedAllocationUnavailable>, DefaultError; +def note_silence_unligned_allocation_unavailable : Note< + "if you supply your own aligned allocation functions, use " + "-Wno-aligned-allocation-unavailable to silence this diagnostic">; def err_conditional_void_nonvoid : Error< "%select{left|right}1 operand to ? is void, but %select{right|left}1 operand " @@ -8402,7 +8410,7 @@ def warn_opencl_attr_deprecated_ignored : Warning < def err_opencl_variadic_function : Error< "invalid prototype, variadic arguments are not allowed in OpenCL">; def err_opencl_requires_extension : Error< - "use of %select{type |declaration}0%1 requires %2 extension to be enabled">; + "use of %select{type|declaration}0 %1 requires %2 extension to be enabled">; // OpenCL v2.0 s6.13.6 -- Builtin Pipe Functions def err_opencl_builtin_pipe_first_arg : Error< diff --git a/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.def b/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.def index 60c8a68cd2e9..dfdad108922a 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.def +++ b/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.def @@ -199,6 +199,7 @@ LANGOPT(CUDADeviceApproxTranscendentals, 1, 0, "using approximate transcendental LANGOPT(SizedDeallocation , 1, 0, "sized deallocation") LANGOPT(AlignedAllocation , 1, 0, "aligned allocation") +LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are unavailable") LANGOPT(NewAlignOverride , 32, 0, "maximum alignment guaranteed by '::operator new(size_t)'") LANGOPT(ConceptsTS , 1, 0, "enable C++ Extensions for Concepts") BENIGN_LANGOPT(ModulesCodegen , 1, 0, "Modules code generation") diff --git a/contrib/llvm/tools/clang/include/clang/Basic/OpenMPKinds.def b/contrib/llvm/tools/clang/include/clang/Basic/OpenMPKinds.def index 74ec26f19ac2..aae1c3a9b8c5 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/OpenMPKinds.def +++ b/contrib/llvm/tools/clang/include/clang/Basic/OpenMPKinds.def @@ -552,6 +552,7 @@ OPENMP_TASKLOOP_CLAUSE(priority) OPENMP_TASKLOOP_CLAUSE(grainsize) OPENMP_TASKLOOP_CLAUSE(nogroup) OPENMP_TASKLOOP_CLAUSE(num_tasks) +OPENMP_TASKLOOP_CLAUSE(reduction) // Clauses allowed for OpenMP directive 'taskloop simd'. OPENMP_TASKLOOP_SIMD_CLAUSE(if) @@ -572,6 +573,7 @@ OPENMP_TASKLOOP_SIMD_CLAUSE(simdlen) OPENMP_TASKLOOP_SIMD_CLAUSE(grainsize) OPENMP_TASKLOOP_SIMD_CLAUSE(nogroup) OPENMP_TASKLOOP_SIMD_CLAUSE(num_tasks) +OPENMP_TASKLOOP_SIMD_CLAUSE(reduction) // Clauses allowed for OpenMP directive 'critical'. OPENMP_CRITICAL_CLAUSE(hint) diff --git a/contrib/llvm/tools/clang/include/clang/Basic/SourceLocation.h b/contrib/llvm/tools/clang/include/clang/Basic/SourceLocation.h index f0fe4c27062e..12aa0e4f5717 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/SourceLocation.h +++ b/contrib/llvm/tools/clang/include/clang/Basic/SourceLocation.h @@ -262,6 +262,65 @@ public: bool isInvalid() const { return !isValid(); } }; +/// \brief Represents an unpacked "presumed" location which can be presented +/// to the user. +/// +/// A 'presumed' location can be modified by \#line and GNU line marker +/// directives and is always the expansion point of a normal location. +/// +/// You can get a PresumedLoc from a SourceLocation with SourceManager. +class PresumedLoc { + const char *Filename; + unsigned Line, Col; + SourceLocation IncludeLoc; + +public: + PresumedLoc() : Filename(nullptr) {} + PresumedLoc(const char *FN, unsigned Ln, unsigned Co, SourceLocation IL) + : Filename(FN), Line(Ln), Col(Co), IncludeLoc(IL) {} + + /// \brief Return true if this object is invalid or uninitialized. + /// + /// This occurs when created with invalid source locations or when walking + /// off the top of a \#include stack. + bool isInvalid() const { return Filename == nullptr; } + bool isValid() const { return Filename != nullptr; } + + /// \brief Return the presumed filename of this location. + /// + /// This can be affected by \#line etc. + const char *getFilename() const { + assert(isValid()); + return Filename; + } + + /// \brief Return the presumed line number of this location. + /// + /// This can be affected by \#line etc. + unsigned getLine() const { + assert(isValid()); + return Line; + } + + /// \brief Return the presumed column number of this location. + /// + /// This cannot be affected by \#line, but is packaged here for convenience. + unsigned getColumn() const { + assert(isValid()); + return Col; + } + + /// \brief Return the presumed include location of this location. + /// + /// This can be affected by GNU linemarker directives. + SourceLocation getIncludeLoc() const { + assert(isValid()); + return IncludeLoc; + } +}; + +class FileEntry; + /// \brief A SourceLocation and its associated SourceManager. /// /// This is useful for argument passing to functions that expect both objects. @@ -274,6 +333,12 @@ public: explicit FullSourceLoc(SourceLocation Loc, const SourceManager &SM) : SourceLocation(Loc), SrcMgr(&SM) {} + bool hasManager() const { + bool hasSrcMgr = SrcMgr != nullptr; + assert(hasSrcMgr == isValid() && "FullSourceLoc has location but no manager"); + return hasSrcMgr; + } + /// \pre This FullSourceLoc has an associated SourceManager. const SourceManager &getManager() const { assert(SrcMgr && "SourceManager is NULL."); @@ -284,6 +349,13 @@ public: FullSourceLoc getExpansionLoc() const; FullSourceLoc getSpellingLoc() const; + FullSourceLoc getFileLoc() const; + std::pair<FullSourceLoc, FullSourceLoc> getImmediateExpansionRange() const; + PresumedLoc getPresumedLoc(bool UseLineDirectives = true) const; + bool isMacroArgExpansion(FullSourceLoc *StartLoc = nullptr) const; + FullSourceLoc getImmediateMacroCallerLoc() const; + std::pair<FullSourceLoc, StringRef> getModuleImportLoc() const; + unsigned getFileOffset() const; unsigned getExpansionLineNumber(bool *Invalid = nullptr) const; unsigned getExpansionColumnNumber(bool *Invalid = nullptr) const; @@ -293,6 +365,12 @@ public: const char *getCharacterData(bool *Invalid = nullptr) const; + unsigned getLineNumber(bool *Invalid = nullptr) const; + unsigned getColumnNumber(bool *Invalid = nullptr) const; + + std::pair<FullSourceLoc, FullSourceLoc> getExpansionRange() const; + + const FileEntry *getFileEntry() const; /// \brief Return a StringRef to the source buffer data for the /// specified FileID. @@ -345,50 +423,6 @@ public: }; -/// \brief Represents an unpacked "presumed" location which can be presented -/// to the user. -/// -/// A 'presumed' location can be modified by \#line and GNU line marker -/// directives and is always the expansion point of a normal location. -/// -/// You can get a PresumedLoc from a SourceLocation with SourceManager. -class PresumedLoc { - const char *Filename; - unsigned Line, Col; - SourceLocation IncludeLoc; -public: - PresumedLoc() : Filename(nullptr) {} - PresumedLoc(const char *FN, unsigned Ln, unsigned Co, SourceLocation IL) - : Filename(FN), Line(Ln), Col(Co), IncludeLoc(IL) { - } - - /// \brief Return true if this object is invalid or uninitialized. - /// - /// This occurs when created with invalid source locations or when walking - /// off the top of a \#include stack. - bool isInvalid() const { return Filename == nullptr; } - bool isValid() const { return Filename != nullptr; } - - /// \brief Return the presumed filename of this location. - /// - /// This can be affected by \#line etc. - const char *getFilename() const { assert(isValid()); return Filename; } - - /// \brief Return the presumed line number of this location. - /// - /// This can be affected by \#line etc. - unsigned getLine() const { assert(isValid()); return Line; } - - /// \brief Return the presumed column number of this location. - /// - /// This cannot be affected by \#line, but is packaged here for convenience. - unsigned getColumn() const { assert(isValid()); return Col; } - - /// \brief Return the presumed include location of this location. - /// - /// This can be affected by GNU linemarker directives. - SourceLocation getIncludeLoc() const { assert(isValid()); return IncludeLoc; } -}; } // end namespace clang diff --git a/contrib/llvm/tools/clang/include/clang/Basic/SourceManager.h b/contrib/llvm/tools/clang/include/clang/Basic/SourceManager.h index 5e01f6416748..ed3f8dfa86e7 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/SourceManager.h +++ b/contrib/llvm/tools/clang/include/clang/Basic/SourceManager.h @@ -80,9 +80,19 @@ namespace SrcMgr { /// system_header is seen or in various other cases. /// enum CharacteristicKind { - C_User, C_System, C_ExternCSystem + C_User, C_System, C_ExternCSystem, C_User_ModuleMap, C_System_ModuleMap }; + /// Determine whether a file / directory characteristic is for system code. + inline bool isSystem(CharacteristicKind CK) { + return CK != C_User && CK != C_User_ModuleMap; + } + + /// Determine whether a file characteristic is for a module map. + inline bool isModuleMap(CharacteristicKind CK) { + return CK == C_User_ModuleMap || CK == C_System_ModuleMap; + } + /// \brief One instance of this struct is kept for every file loaded or used. /// /// This object owns the MemoryBuffer object. @@ -251,12 +261,14 @@ namespace SrcMgr { /// preprocessing of this \#include, including this SLocEntry. /// /// Zero means the preprocessor didn't provide such info for this SLocEntry. - unsigned NumCreatedFIDs; + unsigned NumCreatedFIDs : 31; - /// \brief Contains the ContentCache* and the bits indicating the - /// characteristic of the file and whether it has \#line info, all - /// bitmangled together. - uintptr_t Data; + /// \brief Whether this FileInfo has any \#line directives. + unsigned HasLineDirectives : 1; + + /// \brief The content cache and the characteristic of the file. + llvm::PointerIntPair<const ContentCache*, 3, CharacteristicKind> + ContentAndKind; friend class clang::SourceManager; friend class clang::ASTWriter; @@ -269,10 +281,9 @@ namespace SrcMgr { FileInfo X; X.IncludeLoc = IL.getRawEncoding(); X.NumCreatedFIDs = 0; - X.Data = (uintptr_t)Con; - assert((X.Data & 7) == 0 &&"ContentCache pointer insufficiently aligned"); - assert((unsigned)FileCharacter < 4 && "invalid file character"); - X.Data |= (unsigned)FileCharacter; + X.HasLineDirectives = false; + X.ContentAndKind.setPointer(Con); + X.ContentAndKind.setInt(FileCharacter); return X; } @@ -280,22 +291,22 @@ namespace SrcMgr { return SourceLocation::getFromRawEncoding(IncludeLoc); } - const ContentCache* getContentCache() const { - return reinterpret_cast<const ContentCache*>(Data & ~uintptr_t(7)); + const ContentCache *getContentCache() const { + return ContentAndKind.getPointer(); } /// \brief Return whether this is a system header or not. CharacteristicKind getFileCharacteristic() const { - return (CharacteristicKind)(Data & 3); + return ContentAndKind.getInt(); } /// \brief Return true if this FileID has \#line directives in it. - bool hasLineDirectives() const { return (Data & 4) != 0; } + bool hasLineDirectives() const { return HasLineDirectives; } /// \brief Set the flag that indicates that this FileID has /// line table entries associated with it. void setHasLineDirectives() { - Data |= 4; + HasLineDirectives = true; } }; @@ -407,6 +418,8 @@ namespace SrcMgr { }; public: + SLocEntry() : Offset(), IsExpansion(), File() {} + unsigned getOffset() const { return Offset; } bool isExpansion() const { return IsExpansion; } @@ -789,9 +802,8 @@ public: FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID = 0, unsigned LoadedOffset = 0) { - const SrcMgr::ContentCache * - IR = getOrCreateContentCache(SourceFile, - /*isSystemFile=*/FileCharacter != SrcMgr::C_User); + const SrcMgr::ContentCache *IR = + getOrCreateContentCache(SourceFile, isSystem(FileCharacter)); assert(IR && "getOrCreateContentCache() cannot return NULL"); return createFileID(IR, IncludePos, FileCharacter, LoadedID, LoadedOffset); } @@ -1360,7 +1372,7 @@ public: /// \brief Returns if a SourceLocation is in a system header. bool isInSystemHeader(SourceLocation Loc) const { - return getFileCharacteristic(Loc) != SrcMgr::C_User; + return isSystem(getFileCharacteristic(Loc)); } /// \brief Returns if a SourceLocation is in an "extern C" system header. @@ -1477,6 +1489,17 @@ public: /// \returns true if LHS source location comes before RHS, false otherwise. bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const; + /// \brief Determines whether the two decomposed source location is in the + /// same translation unit. As a byproduct, it also calculates the order + /// of the source locations in case they are in the same TU. + /// + /// \returns Pair of bools the first component is true if the two locations + /// are in the same TU. The second bool is true if the first is true + /// and \p LOffs is before \p ROffs. + std::pair<bool, bool> + isInTheSameTranslationUnit(std::pair<FileID, unsigned> &LOffs, + std::pair<FileID, unsigned> &ROffs) const; + /// \brief Determines the order of 2 source locations in the "source location /// address space". bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const { diff --git a/contrib/llvm/tools/clang/include/clang/Basic/TargetBuiltins.h b/contrib/llvm/tools/clang/include/clang/Basic/TargetBuiltins.h index 5d45e162d9f6..8f4f5e9a74dd 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/TargetBuiltins.h +++ b/contrib/llvm/tools/clang/include/clang/Basic/TargetBuiltins.h @@ -150,6 +150,16 @@ namespace clang { }; } + /// \brief Nios2 builtins + namespace Nios2 { + enum { + LastTIBuiltin = clang::Builtin::FirstTSBuiltin - 1, +#define BUILTIN(ID, TYPE, ATTRS) BI##ID, +#include "clang/Basic/BuiltinsNios2.def" + LastTSBuiltin + }; + } + /// \brief MIPS builtins namespace Mips { enum { diff --git a/contrib/llvm/tools/clang/include/clang/Basic/TargetOptions.h b/contrib/llvm/tools/clang/include/clang/Basic/TargetOptions.h index 6ca1ba39c8fb..9bb19c7b79df 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/TargetOptions.h +++ b/contrib/llvm/tools/clang/include/clang/Basic/TargetOptions.h @@ -18,6 +18,7 @@ #include <string> #include <vector> #include "clang/Basic/OpenCLOptions.h" +#include "llvm/Target/TargetOptions.h" namespace clang { @@ -41,7 +42,7 @@ public: std::string ABI; /// The EABI version to use - std::string EABIVersion; + llvm::EABI EABIVersion; /// If given, the version string of the linker in use. std::string LinkerVersion; diff --git a/contrib/llvm/tools/clang/include/clang/Basic/Visibility.h b/contrib/llvm/tools/clang/include/clang/Basic/Visibility.h index 6ac52ed6b5e1..cc839d789e7f 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/Visibility.h +++ b/contrib/llvm/tools/clang/include/clang/Basic/Visibility.h @@ -75,6 +75,9 @@ public: static LinkageInfo none() { return LinkageInfo(NoLinkage, DefaultVisibility, false); } + static LinkageInfo visible_none() { + return LinkageInfo(VisibleNoLinkage, DefaultVisibility, false); + } Linkage getLinkage() const { return (Linkage)linkage_; } Visibility getVisibility() const { return (Visibility)visibility_; } diff --git a/contrib/llvm/tools/clang/include/clang/Driver/CC1Options.td b/contrib/llvm/tools/clang/include/clang/Driver/CC1Options.td index c478cfc7833e..205f36b723c8 100644 --- a/contrib/llvm/tools/clang/include/clang/Driver/CC1Options.td +++ b/contrib/llvm/tools/clang/include/clang/Driver/CC1Options.td @@ -145,7 +145,7 @@ def dwarf_debug_flags : Separate<["-"], "dwarf-debug-flags">, HelpText<"The string to embed in the Dwarf debug flags record.">; def compress_debug_sections : Flag<["-", "--"], "compress-debug-sections">, HelpText<"DWARF debug sections compression">; -def compress_debug_sections_EQ : Flag<["-"], "compress-debug-sections=">, +def compress_debug_sections_EQ : Joined<["-"], "compress-debug-sections=">, HelpText<"DWARF debug sections compression type">; def mno_exec_stack : Flag<["-"], "mnoexecstack">, HelpText<"Mark the file as not needing an executable stack">; @@ -268,8 +268,6 @@ def vectorize_loops : Flag<["-"], "vectorize-loops">, HelpText<"Run the Loop vectorization passes">; def vectorize_slp : Flag<["-"], "vectorize-slp">, HelpText<"Run the SLP vectorization passes">; -def vectorize_slp_aggressive : Flag<["-"], "vectorize-slp-aggressive">, - HelpText<"Run the BB vectorization passes">; def dependent_lib : Joined<["--"], "dependent-lib=">, HelpText<"Add dependent library">; def linker_option : Joined<["--"], "linker-option=">, @@ -323,6 +321,10 @@ def flto_unit: Flag<["-"], "flto-unit">, def fno_lto_unit: Flag<["-"], "fno-lto-unit">; def fthin_link_bitcode_EQ : Joined<["-"], "fthin-link-bitcode=">, HelpText<"Write minimized bitcode to <file> for the ThinLTO thin link only">; +def fdebug_pass_manager : Flag<["-"], "fdebug-pass-manager">, + HelpText<"Prints debug information for the new pass manager">; +def fno_debug_pass_manager : Flag<["-"], "fno-debug-pass-manager">, + HelpText<"Disables debug printing for the new pass manager">; //===----------------------------------------------------------------------===// // Dependency Output Options @@ -568,6 +570,9 @@ def find_pch_source_EQ : Joined<["-"], "find-pch-source=">, def fno_pch_timestamp : Flag<["-"], "fno-pch-timestamp">, HelpText<"Disable inclusion of timestamp in precompiled headers">; +def aligned_alloc_unavailable : Flag<["-"], "faligned-alloc-unavailable">, + HelpText<"Aligned allocation/deallocation functions are unavailable">; + //===----------------------------------------------------------------------===// // Language Options //===----------------------------------------------------------------------===// diff --git a/contrib/llvm/tools/clang/include/clang/Driver/Compilation.h b/contrib/llvm/tools/clang/include/clang/Driver/Compilation.h index 114e0b33c75a..036b04605ac7 100644 --- a/contrib/llvm/tools/clang/include/clang/Driver/Compilation.h +++ b/contrib/llvm/tools/clang/include/clang/Driver/Compilation.h @@ -105,10 +105,13 @@ class Compilation { /// Whether we're compiling for diagnostic purposes. bool ForDiagnostics; + /// Whether an error during the parsing of the input args. + bool ContainsError; + public: Compilation(const Driver &D, const ToolChain &DefaultToolChain, llvm::opt::InputArgList *Args, - llvm::opt::DerivedArgList *TranslatedArgs); + llvm::opt::DerivedArgList *TranslatedArgs, bool ContainsError); ~Compilation(); const Driver &getDriver() const { return TheDriver; } @@ -275,6 +278,9 @@ public: /// Return true if we're compiling for diagnostics. bool isForDiagnostics() const { return ForDiagnostics; } + /// Return whether an error during the parsing of the input args. + bool containsError() const { return ContainsError; } + /// Redirect - Redirect output of this compilation. Can only be done once. /// /// \param Redirects - array of pointers to paths. The array diff --git a/contrib/llvm/tools/clang/include/clang/Driver/Driver.h b/contrib/llvm/tools/clang/include/clang/Driver/Driver.h index 1009754a15d5..5a087eea1b4e 100644 --- a/contrib/llvm/tools/clang/include/clang/Driver/Driver.h +++ b/contrib/llvm/tools/clang/include/clang/Driver/Driver.h @@ -341,7 +341,8 @@ public: /// ParseArgStrings - Parse the given list of strings into an /// ArgList. - llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args); + llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args, + bool &ContainsError); /// BuildInputs - Construct the list of inputs and their types from /// the given arguments. diff --git a/contrib/llvm/tools/clang/include/clang/Driver/Options.td b/contrib/llvm/tools/clang/include/clang/Driver/Options.td index 68b331fed2bd..b65b984731f6 100644 --- a/contrib/llvm/tools/clang/include/clang/Driver/Options.td +++ b/contrib/llvm/tools/clang/include/clang/Driver/Options.td @@ -723,6 +723,9 @@ def fdiagnostics_print_source_range_info : Flag<["-"], "fdiagnostics-print-sourc HelpText<"Print source range spans in numeric form">; def fdiagnostics_show_hotness : Flag<["-"], "fdiagnostics-show-hotness">, Group<f_Group>, Flags<[CC1Option]>, HelpText<"Enable profile hotness information in diagnostic line">; +def fdiagnostics_hotness_threshold_EQ : Joined<["-"], "fdiagnostics-hotness-threshold=">, + Group<f_Group>, Flags<[CC1Option]>, MetaVarName<"<number>">, + HelpText<"Prevent optimization remarks from being output if they do not have at least this profile count">; def fdiagnostics_show_option : Flag<["-"], "fdiagnostics-show-option">, Group<f_Group>, Flags<[CC1Option]>, HelpText<"Print option name with mappable diagnostics">; def fdiagnostics_show_note_include_stack : Flag<["-"], "fdiagnostics-show-note-include-stack">, @@ -1405,9 +1408,6 @@ def : Flag<["-"], "fno-tree-vectorize">, Alias<fno_vectorize>; def fslp_vectorize : Flag<["-"], "fslp-vectorize">, Group<f_Group>, HelpText<"Enable the superword-level parallelism vectorization passes">; def fno_slp_vectorize : Flag<["-"], "fno-slp-vectorize">, Group<f_Group>; -def fslp_vectorize_aggressive : Flag<["-"], "fslp-vectorize-aggressive">, Group<f_Group>, - HelpText<"Enable the BB vectorization passes">; -def fno_slp_vectorize_aggressive : Flag<["-"], "fno-slp-vectorize-aggressive">, Group<f_Group>; def : Flag<["-"], "ftree-slp-vectorize">, Alias<fslp_vectorize>; def : Flag<["-"], "fno-tree-slp-vectorize">, Alias<fno_slp_vectorize>; def Wlarge_by_value_copy_def : Flag<["-"], "Wlarge-by-value-copy">, diff --git a/contrib/llvm/tools/clang/include/clang/Format/Format.h b/contrib/llvm/tools/clang/include/clang/Format/Format.h index c1b62477ed1c..ee24c55fef61 100644 --- a/contrib/llvm/tools/clang/include/clang/Format/Format.h +++ b/contrib/llvm/tools/clang/include/clang/Format/Format.h @@ -717,7 +717,29 @@ struct FormatStyle { /// } /// \endcode /// - bool SplitEmptyFunctionBody; + bool SplitEmptyFunction; + /// \brief If ``false``, empty record (e.g. class, struct or union) body + /// can be put on a single line. This option is used only if the opening + /// brace of the record has already been wrapped, i.e. the `AfterClass` + /// (for classes) brace wrapping mode is set. + /// \code + /// class Foo vs. class Foo + /// {} { + /// } + /// \endcode + /// + bool SplitEmptyRecord; + /// \brief If ``false``, empty namespace body can be put on a single line. + /// This option is used only if the opening brace of the namespace has + /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is + /// set. + /// \code + /// namespace Foo vs. namespace Foo + /// {} { + /// } + /// \endcode + /// + bool SplitEmptyNamespace; }; /// \brief Control of individual brace wrapping cases. @@ -966,7 +988,7 @@ struct FormatStyle { /// IncludeCategories: /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/' /// Priority: 2 - /// - Regex: '^(<|"(gtest|isl|json)/)' + /// - Regex: '^(<|"(gtest|gmock|isl|json)/)' /// Priority: 3 /// - Regex: '.*' /// Priority: 1 diff --git a/contrib/llvm/tools/clang/include/clang/Frontend/ASTUnit.h b/contrib/llvm/tools/clang/include/clang/Frontend/ASTUnit.h index 2950c31c2d3d..1ac4f07a3549 100644 --- a/contrib/llvm/tools/clang/include/clang/Frontend/ASTUnit.h +++ b/contrib/llvm/tools/clang/include/clang/Frontend/ASTUnit.h @@ -628,6 +628,15 @@ public: IntrusiveRefCntPtr<DiagnosticsEngine> Diags, bool CaptureDiagnostics, bool UserFilesAreVolatile); + enum WhatToLoad { + /// Load options and the preprocessor state. + LoadPreprocessorOnly, + /// Load the AST, but do not restore Sema state. + LoadASTOnly, + /// Load everything, including Sema. + LoadEverything + }; + /// \brief Create a ASTUnit from an AST file. /// /// \param Filename - The AST file to load. @@ -640,7 +649,7 @@ public: /// \returns - The initialized ASTUnit or null if the AST failed to load. static std::unique_ptr<ASTUnit> LoadFromASTFile( const std::string &Filename, const PCHContainerReader &PCHContainerRdr, - IntrusiveRefCntPtr<DiagnosticsEngine> Diags, + WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, const FileSystemOptions &FileSystemOpts, bool UseDebugInfo = false, bool OnlyLocalDecls = false, ArrayRef<RemappedFile> RemappedFiles = None, bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false, diff --git a/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.def b/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.def index f3deb05ec6df..238bb231bdf5 100644 --- a/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.def +++ b/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.def @@ -57,6 +57,8 @@ CODEGENOPT(DisableLifetimeMarkers, 1, 0) ///< Don't emit any lifetime markers CODEGENOPT(DisableO0ImplyOptNone , 1, 0) ///< Don't annonate function with optnone at O0 CODEGENOPT(ExperimentalNewPassManager, 1, 0) ///< Enables the new, experimental ///< pass manager. +CODEGENOPT(DebugPassManager, 1, 0) ///< Prints debug information for the new + ///< pass manager. CODEGENOPT(DisableRedZone , 1, 0) ///< Set when -mno-red-zone is enabled. CODEGENOPT(DisableTailCalls , 1, 0) ///< Do not emit tail calls. CODEGENOPT(EmitDeclMetadata , 1, 0) ///< Emit special metadata indicating what @@ -177,7 +179,6 @@ CODEGENOPT(RerollLoops , 1, 0) ///< Control whether loops are rerolled. CODEGENOPT(NoUseJumpTables , 1, 0) ///< Set when -fno-jump-tables is enabled. CODEGENOPT(UnsafeFPMath , 1, 0) ///< Allow unsafe floating point optzns. CODEGENOPT(UnwindTables , 1, 0) ///< Emit unwind tables. -CODEGENOPT(VectorizeBB , 1, 0) ///< Run basic block vectorizer. CODEGENOPT(VectorizeLoop , 1, 0) ///< Run loop vectorizer. CODEGENOPT(VectorizeSLP , 1, 0) ///< Run SLP vectorizer. @@ -260,6 +261,10 @@ VALUE_CODEGENOPT(EmitCheckPathComponentsToStrip, 32, 0) /// Whether to report the hotness of the code region for optimization remarks. CODEGENOPT(DiagnosticsWithHotness, 1, 0) +/// The minimum hotness value a diagnostic needs in order to be included in +/// optimization diagnostics. +VALUE_CODEGENOPT(DiagnosticsHotnessThreshold, 32, 0) + /// Whether copy relocations support is available when building as PIE. CODEGENOPT(PIECopyRelocations, 1, 0) diff --git a/contrib/llvm/tools/clang/include/clang/Frontend/DiagnosticRenderer.h b/contrib/llvm/tools/clang/include/clang/Frontend/DiagnosticRenderer.h index 2588feb2b87d..e453d7db624c 100644 --- a/contrib/llvm/tools/clang/include/clang/Frontend/DiagnosticRenderer.h +++ b/contrib/llvm/tools/clang/include/clang/Frontend/DiagnosticRenderer.h @@ -70,33 +70,27 @@ protected: DiagnosticOptions *DiagOpts); virtual ~DiagnosticRenderer(); - - virtual void emitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc, + + virtual void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, StringRef Message, ArrayRef<CharSourceRange> Ranges, - const SourceManager *SM, DiagOrStoredDiag Info) = 0; - - virtual void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, + + virtual void emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, - ArrayRef<CharSourceRange> Ranges, - const SourceManager &SM) = 0; + ArrayRef<CharSourceRange> Ranges) = 0; - virtual void emitCodeContext(SourceLocation Loc, + virtual void emitCodeContext(FullSourceLoc Loc, DiagnosticsEngine::Level Level, - SmallVectorImpl<CharSourceRange>& Ranges, - ArrayRef<FixItHint> Hints, - const SourceManager &SM) = 0; - - virtual void emitIncludeLocation(SourceLocation Loc, PresumedLoc PLoc, - const SourceManager &SM) = 0; - virtual void emitImportLocation(SourceLocation Loc, PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) = 0; - virtual void emitBuildingModuleLocation(SourceLocation Loc, PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) = 0; + SmallVectorImpl<CharSourceRange> &Ranges, + ArrayRef<FixItHint> Hints) = 0; + + virtual void emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) = 0; + virtual void emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc, + StringRef ModuleName) = 0; + virtual void emitBuildingModuleLocation(FullSourceLoc Loc, PresumedLoc PLoc, + StringRef ModuleName) = 0; virtual void beginDiagnostic(DiagOrStoredDiag D, DiagnosticsEngine::Level Level) {} @@ -106,25 +100,21 @@ protected: private: void emitBasicNote(StringRef Message); - void emitIncludeStack(SourceLocation Loc, PresumedLoc PLoc, - DiagnosticsEngine::Level Level, const SourceManager &SM); - void emitIncludeStackRecursively(SourceLocation Loc, const SourceManager &SM); - void emitImportStack(SourceLocation Loc, const SourceManager &SM); - void emitImportStackRecursively(SourceLocation Loc, StringRef ModuleName, - const SourceManager &SM); + void emitIncludeStack(FullSourceLoc Loc, PresumedLoc PLoc, + DiagnosticsEngine::Level Level); + void emitIncludeStackRecursively(FullSourceLoc Loc); + void emitImportStack(FullSourceLoc Loc); + void emitImportStackRecursively(FullSourceLoc Loc, StringRef ModuleName); void emitModuleBuildStack(const SourceManager &SM); - void emitCaret(SourceLocation Loc, DiagnosticsEngine::Level Level, - ArrayRef<CharSourceRange> Ranges, ArrayRef<FixItHint> Hints, - const SourceManager &SM); - void emitSingleMacroExpansion(SourceLocation Loc, + void emitCaret(FullSourceLoc Loc, DiagnosticsEngine::Level Level, + ArrayRef<CharSourceRange> Ranges, ArrayRef<FixItHint> Hints); + void emitSingleMacroExpansion(FullSourceLoc Loc, DiagnosticsEngine::Level Level, - ArrayRef<CharSourceRange> Ranges, - const SourceManager &SM); - void emitMacroExpansions(SourceLocation Loc, - DiagnosticsEngine::Level Level, + ArrayRef<CharSourceRange> Ranges); + void emitMacroExpansions(FullSourceLoc Loc, DiagnosticsEngine::Level Level, ArrayRef<CharSourceRange> Ranges, - ArrayRef<FixItHint> Hints, - const SourceManager &SM); + ArrayRef<FixItHint> Hints); + public: /// \brief Emit a diagnostic. /// @@ -138,12 +128,9 @@ public: /// \param Message The diagnostic message to emit. /// \param Ranges The underlined ranges for this code snippet. /// \param FixItHints The FixIt hints active for this diagnostic. - /// \param SM The SourceManager; will be null if the diagnostic came from the - /// frontend, thus \p Loc will be invalid. - void emitDiagnostic(SourceLocation Loc, DiagnosticsEngine::Level Level, + void emitDiagnostic(FullSourceLoc Loc, DiagnosticsEngine::Level Level, StringRef Message, ArrayRef<CharSourceRange> Ranges, ArrayRef<FixItHint> FixItHints, - const SourceManager *SM, DiagOrStoredDiag D = (Diagnostic *)nullptr); void emitStoredDiagnostic(StoredDiagnostic &Diag); @@ -159,19 +146,15 @@ public: ~DiagnosticNoteRenderer() override; - void emitIncludeLocation(SourceLocation Loc, PresumedLoc PLoc, - const SourceManager &SM) override; + void emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) override; - void emitImportLocation(SourceLocation Loc, PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) override; + void emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc, + StringRef ModuleName) override; - void emitBuildingModuleLocation(SourceLocation Loc, PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) override; + void emitBuildingModuleLocation(FullSourceLoc Loc, PresumedLoc PLoc, + StringRef ModuleName) override; - virtual void emitNote(SourceLocation Loc, StringRef Message, - const SourceManager *SM) = 0; + virtual void emitNote(FullSourceLoc Loc, StringRef Message) = 0; }; } // end clang namespace #endif diff --git a/contrib/llvm/tools/clang/include/clang/Frontend/TextDiagnostic.h b/contrib/llvm/tools/clang/include/clang/Frontend/TextDiagnostic.h index 9b108c28bd1c..1bbfe9fa02e3 100644 --- a/contrib/llvm/tools/clang/include/clang/Frontend/TextDiagnostic.h +++ b/contrib/llvm/tools/clang/include/clang/Frontend/TextDiagnostic.h @@ -75,44 +75,35 @@ public: unsigned Columns, bool ShowColors); protected: - void emitDiagnosticMessage(SourceLocation Loc,PresumedLoc PLoc, - DiagnosticsEngine::Level Level, - StringRef Message, + void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc, + DiagnosticsEngine::Level Level, StringRef Message, ArrayRef<CharSourceRange> Ranges, - const SourceManager *SM, DiagOrStoredDiag D) override; - void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, + void emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, - ArrayRef<CharSourceRange> Ranges, - const SourceManager &SM) override; - - void emitCodeContext(SourceLocation Loc, - DiagnosticsEngine::Level Level, - SmallVectorImpl<CharSourceRange>& Ranges, - ArrayRef<FixItHint> Hints, - const SourceManager &SM) override { - emitSnippetAndCaret(Loc, Level, Ranges, Hints, SM); + ArrayRef<CharSourceRange> Ranges) override; + + void emitCodeContext(FullSourceLoc Loc, DiagnosticsEngine::Level Level, + SmallVectorImpl<CharSourceRange> &Ranges, + ArrayRef<FixItHint> Hints) override { + emitSnippetAndCaret(Loc, Level, Ranges, Hints); } - void emitIncludeLocation(SourceLocation Loc, PresumedLoc PLoc, - const SourceManager &SM) override; + void emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) override; - void emitImportLocation(SourceLocation Loc, PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) override; + void emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc, + StringRef ModuleName) override; - void emitBuildingModuleLocation(SourceLocation Loc, PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) override; + void emitBuildingModuleLocation(FullSourceLoc Loc, PresumedLoc PLoc, + StringRef ModuleName) override; private: void emitFilename(StringRef Filename, const SourceManager &SM); - void emitSnippetAndCaret(SourceLocation Loc, DiagnosticsEngine::Level Level, - SmallVectorImpl<CharSourceRange>& Ranges, - ArrayRef<FixItHint> Hints, - const SourceManager &SM); + void emitSnippetAndCaret(FullSourceLoc Loc, DiagnosticsEngine::Level Level, + SmallVectorImpl<CharSourceRange> &Ranges, + ArrayRef<FixItHint> Hints); void emitSnippet(StringRef SourceLine); diff --git a/contrib/llvm/tools/clang/include/clang/Frontend/Utils.h b/contrib/llvm/tools/clang/include/clang/Frontend/Utils.h index 0ee46846c804..8ccc31982dab 100644 --- a/contrib/llvm/tools/clang/include/clang/Frontend/Utils.h +++ b/contrib/llvm/tools/clang/include/clang/Frontend/Utils.h @@ -184,10 +184,11 @@ createChainedIncludesSource(CompilerInstance &CI, /// /// \return A CompilerInvocation, or 0 if none was built for the given /// argument vector. -std::unique_ptr<CompilerInvocation> -createInvocationFromCommandLine(ArrayRef<const char *> Args, - IntrusiveRefCntPtr<DiagnosticsEngine> Diags = - IntrusiveRefCntPtr<DiagnosticsEngine>()); +std::unique_ptr<CompilerInvocation> createInvocationFromCommandLine( + ArrayRef<const char *> Args, + IntrusiveRefCntPtr<DiagnosticsEngine> Diags = + IntrusiveRefCntPtr<DiagnosticsEngine>(), + IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr); /// Return the value of the last argument as an integer, or a default. If Diags /// is non-null, emits an error if the argument is given, but non-integral. diff --git a/contrib/llvm/tools/clang/include/clang/Lex/HeaderSearch.h b/contrib/llvm/tools/clang/include/clang/Lex/HeaderSearch.h index ee17dcbb8b5a..1b7f80c87ff1 100644 --- a/contrib/llvm/tools/clang/include/clang/Lex/HeaderSearch.h +++ b/contrib/llvm/tools/clang/include/clang/Lex/HeaderSearch.h @@ -47,7 +47,7 @@ struct HeaderFileInfo { /// whether it is C++ clean or not. This can be set by the include paths or /// by \#pragma gcc system_header. This is an instance of /// SrcMgr::CharacteristicKind. - unsigned DirInfo : 2; + unsigned DirInfo : 3; /// \brief Whether this header file info was supplied by an external source, /// and has not changed since. diff --git a/contrib/llvm/tools/clang/include/clang/Lex/PTHLexer.h b/contrib/llvm/tools/clang/include/clang/Lex/PTHLexer.h index 904be792b2a9..f96af665b157 100644 --- a/contrib/llvm/tools/clang/include/clang/Lex/PTHLexer.h +++ b/contrib/llvm/tools/clang/include/clang/Lex/PTHLexer.h @@ -36,7 +36,7 @@ class PTHLexer : public PreprocessorLexer { const unsigned char* LastHashTokPtr; /// PPCond - Pointer to a side table in the PTH file that provides a - /// a consise summary of the preproccessor conditional block structure. + /// a concise summary of the preprocessor conditional block structure. /// This is used to perform quick skipping of conditional blocks. const unsigned char* PPCond; diff --git a/contrib/llvm/tools/clang/include/clang/Sema/Lookup.h b/contrib/llvm/tools/clang/include/clang/Sema/Lookup.h index 9134ddf9198c..ea32997d4066 100644 --- a/contrib/llvm/tools/clang/include/clang/Sema/Lookup.h +++ b/contrib/llvm/tools/clang/include/clang/Sema/Lookup.h @@ -18,6 +18,8 @@ #include "clang/AST/DeclCXX.h" #include "clang/Sema/Sema.h" +#include "llvm/ADT/Optional.h" + namespace clang { /// @brief Represents the results of name lookup. @@ -273,7 +275,7 @@ public: /// declarations, such as those in modules that have not yet been imported. bool isHiddenDeclarationVisible(NamedDecl *ND) const { return AllowHidden || - (isForRedeclaration() && ND->isExternallyVisible()); + (isForRedeclaration() && ND->hasExternalFormalLinkage()); } /// Sets whether tag declarations should be hidden by non-tag @@ -465,7 +467,7 @@ public: Paths = nullptr; } } else { - AmbiguityKind SavedAK; + llvm::Optional<AmbiguityKind> SavedAK; bool WasAmbiguous = false; if (ResultKind == Ambiguous) { SavedAK = Ambiguity; @@ -479,7 +481,7 @@ public: if (ResultKind == Ambiguous) { (void)WasAmbiguous; assert(WasAmbiguous); - Ambiguity = SavedAK; + Ambiguity = SavedAK.getValue(); } else if (Paths) { deletePaths(Paths); Paths = nullptr; diff --git a/contrib/llvm/tools/clang/include/clang/Sema/Sema.h b/contrib/llvm/tools/clang/include/clang/Sema/Sema.h index 02c133d1c4fc..95134d52f873 100644 --- a/contrib/llvm/tools/clang/include/clang/Sema/Sema.h +++ b/contrib/llvm/tools/clang/include/clang/Sema/Sema.h @@ -1542,6 +1542,10 @@ public: bool hasVisibleMergedDefinition(NamedDecl *Def); + /// Determine if \p D and \p Suggested have a structurally compatible + /// layout as described in C11 6.2.7/1. + bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); + /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, @@ -1629,9 +1633,13 @@ public: // struct SkipBodyInfo { - SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {} + SkipBodyInfo() + : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), + New(nullptr) {} bool ShouldSkip; + bool CheckSameAsPrevious; NamedDecl *Previous; + NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); @@ -2145,13 +2153,11 @@ public: }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, - SourceLocation KWLoc, CXXScopeSpec &SS, - IdentifierInfo *Name, SourceLocation NameLoc, - AttributeList *Attr, AccessSpecifier AS, - SourceLocation ModulePrivateLoc, - MultiTemplateParamsArg TemplateParameterLists, - bool &OwnedDecl, bool &IsDependent, - SourceLocation ScopedEnumKWLoc, + SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, + SourceLocation NameLoc, AttributeList *Attr, + AccessSpecifier AS, SourceLocation ModulePrivateLoc, + MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, + bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); @@ -2219,6 +2225,12 @@ public: /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); + /// Perform ODR-like check for C/ObjC when merging tag types from modules. + /// Differently from C++, actually parse the body and reject / error out + /// in case of a structural mismatch. + bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, + SkipBodyInfo &SkipBody); + typedef void *SkippedDefinitionContext; /// \brief Invoked when we enter a tag definition that we're skipping. @@ -2272,8 +2284,8 @@ public: Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, - AttributeList *Attrs, - SourceLocation EqualLoc, Expr *Val); + AttributeList *Attrs, SourceLocation EqualLoc, + Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, @@ -3233,7 +3245,7 @@ public: void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); - // Helper for delayed proccessing of attributes. + // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, bool IncludeCXX11Attributes = true); @@ -8432,7 +8444,7 @@ public: /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. - bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E); + bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. @@ -10276,6 +10288,7 @@ private: void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); + void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(Expr *E); /// \brief Perform semantic checks on a completed expression. This will either diff --git a/contrib/llvm/tools/clang/include/clang/Serialization/ASTReader.h b/contrib/llvm/tools/clang/include/clang/Serialization/ASTReader.h index 737f6fb3d413..eafa05175832 100644 --- a/contrib/llvm/tools/clang/include/clang/Serialization/ASTReader.h +++ b/contrib/llvm/tools/clang/include/clang/Serialization/ASTReader.h @@ -400,7 +400,7 @@ private: Preprocessor &PP; /// \brief The AST context into which we'll read the AST files. - ASTContext &Context; + ASTContext *ContextObj = nullptr; /// \brief The AST consumer. ASTConsumer *Consumer = nullptr; @@ -1146,6 +1146,7 @@ private: time_t StoredTime; bool Overridden; bool Transient; + bool TopLevelModuleMap; }; /// \brief Reads the stored information about an input file. @@ -1386,7 +1387,7 @@ public: /// precompiled header will be loaded. /// /// \param Context the AST context that this precompiled header will be - /// loaded into. + /// loaded into, if any. /// /// \param PCHContainerRdr the PCHContainerOperations to use for loading and /// creating modules. @@ -1418,7 +1419,7 @@ public: /// /// \param ReadTimer If non-null, a timer used to track the time spent /// deserializing. - ASTReader(Preprocessor &PP, ASTContext &Context, + ASTReader(Preprocessor &PP, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, StringRef isysroot = "", bool DisableValidation = false, @@ -2207,7 +2208,10 @@ public: void completeVisibleDeclsMap(const DeclContext *DC) override; /// \brief Retrieve the AST context that this AST reader supplements. - ASTContext &getContext() { return Context; } + ASTContext &getContext() { + assert(ContextObj && "requested AST context when not loading AST"); + return *ContextObj; + } // \brief Contains the IDs for declarations that were requested before we have // access to a Sema object. @@ -2249,6 +2253,12 @@ public: llvm::function_ref<void(const serialization::InputFile &IF, bool isSystem)> Visitor); + /// Visit all the top-level module maps loaded when building the given module + /// file. + void visitTopLevelModuleMaps(serialization::ModuleFile &MF, + llvm::function_ref< + void(const FileEntry *)> Visitor); + bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; } }; diff --git a/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td index 4171c685cb98..82ab720af8dc 100644 --- a/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ b/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -38,6 +38,11 @@ def CoreAlpha : Package<"core">, InPackage<Alpha>, Hidden; // default. Such checkers belong in the alpha package. def OptIn : Package<"optin">; +// In the Portability package reside checkers for finding code that relies on +// implementation-defined behavior. Such checks are wanted for cross-platform +// development, but unwanted for developers who target only a single platform. +def PortabilityOptIn : Package<"portability">, InPackage<OptIn>; + def Nullability : Package<"nullability">; def Cplusplus : Package<"cplusplus">; @@ -416,7 +421,7 @@ def GenericTaintChecker : Checker<"TaintPropagation">, let ParentPackage = Unix in { -def UnixAPIChecker : Checker<"API">, +def UnixAPIMisuseChecker : Checker<"API">, HelpText<"Check calls to various UNIX/Posix functions">, DescFile<"UnixAPIChecker.cpp">; @@ -754,3 +759,14 @@ def CloneChecker : Checker<"CloneChecker">, } // end "clone" +//===----------------------------------------------------------------------===// +// Portability checkers. +//===----------------------------------------------------------------------===// + +let ParentPackage = PortabilityOptIn in { + +def UnixAPIPortabilityChecker : Checker<"UnixAPI">, + HelpText<"Finds implementation-defined behavior in UNIX/Posix functions">, + DescFile<"UnixAPIChecker.cpp">; + +} // end optin.portability diff --git a/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h b/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h new file mode 100644 index 000000000000..099eaca6c42a --- /dev/null +++ b/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h @@ -0,0 +1,70 @@ +//===--- RenamingAction.h - Clang refactoring library ---------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// \brief Provides an action to rename every symbol at a point. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLING_REFACTOR_RENAME_RENAMING_ACTION_H +#define LLVM_CLANG_TOOLING_REFACTOR_RENAME_RENAMING_ACTION_H + +#include "clang/Tooling/Refactoring.h" + +namespace clang { +class ASTConsumer; +class CompilerInstance; + +namespace tooling { + +class RenamingAction { +public: + RenamingAction(const std::vector<std::string> &NewNames, + const std::vector<std::string> &PrevNames, + const std::vector<std::vector<std::string>> &USRList, + std::map<std::string, tooling::Replacements> &FileToReplaces, + bool PrintLocations = false) + : NewNames(NewNames), PrevNames(PrevNames), USRList(USRList), + FileToReplaces(FileToReplaces), PrintLocations(PrintLocations) {} + + std::unique_ptr<ASTConsumer> newASTConsumer(); + +private: + const std::vector<std::string> &NewNames, &PrevNames; + const std::vector<std::vector<std::string>> &USRList; + std::map<std::string, tooling::Replacements> &FileToReplaces; + bool PrintLocations; +}; + +/// Rename all symbols identified by the given USRs. +class QualifiedRenamingAction { +public: + QualifiedRenamingAction( + const std::vector<std::string> &NewNames, + const std::vector<std::vector<std::string>> &USRList, + std::map<std::string, tooling::Replacements> &FileToReplaces) + : NewNames(NewNames), USRList(USRList), FileToReplaces(FileToReplaces) {} + + std::unique_ptr<ASTConsumer> newASTConsumer(); + +private: + /// New symbol names. + const std::vector<std::string> &NewNames; + + /// A list of USRs. Each element represents USRs of a symbol being renamed. + const std::vector<std::vector<std::string>> &USRList; + + /// A file path to replacements map. + std::map<std::string, tooling::Replacements> &FileToReplaces; +}; + +} // end namespace tooling +} // end namespace clang + +#endif // LLVM_CLANG_TOOLING_REFACTOR_RENAME_RENAMING_ACTION_H diff --git a/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFinder.h b/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFinder.h new file mode 100644 index 000000000000..28d541af43c0 --- /dev/null +++ b/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFinder.h @@ -0,0 +1,84 @@ +//===--- USRFinder.h - Clang refactoring library --------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// \brief Methods for determining the USR of a symbol at a location in source +/// code. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLING_REFACTOR_RENAME_USR_FINDER_H +#define LLVM_CLANG_TOOLING_REFACTOR_RENAME_USR_FINDER_H + +#include "clang/AST/AST.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include <string> +#include <vector> + +using namespace llvm; +using namespace clang::ast_matchers; + +namespace clang { + +class ASTContext; +class Decl; +class SourceLocation; +class NamedDecl; + +namespace tooling { + +// Given an AST context and a point, returns a NamedDecl identifying the symbol +// at the point. Returns null if nothing is found at the point. +const NamedDecl *getNamedDeclAt(const ASTContext &Context, + const SourceLocation Point); + +// Given an AST context and a fully qualified name, returns a NamedDecl +// identifying the symbol with a matching name. Returns null if nothing is +// found for the name. +const NamedDecl *getNamedDeclFor(const ASTContext &Context, + const std::string &Name); + +// Converts a Decl into a USR. +std::string getUSRForDecl(const Decl *Decl); + +// FIXME: Implement RecursiveASTVisitor<T>::VisitNestedNameSpecifier instead. +class NestedNameSpecifierLocFinder : public MatchFinder::MatchCallback { +public: + explicit NestedNameSpecifierLocFinder(ASTContext &Context) + : Context(Context) {} + + std::vector<NestedNameSpecifierLoc> getNestedNameSpecifierLocations() { + addMatchers(); + Finder.matchAST(Context); + return Locations; + } + +private: + void addMatchers() { + const auto NestedNameSpecifierLocMatcher = + nestedNameSpecifierLoc().bind("nestedNameSpecifierLoc"); + Finder.addMatcher(NestedNameSpecifierLocMatcher, this); + } + + void run(const MatchFinder::MatchResult &Result) override { + const auto *NNS = Result.Nodes.getNodeAs<NestedNameSpecifierLoc>( + "nestedNameSpecifierLoc"); + Locations.push_back(*NNS); + } + + ASTContext &Context; + std::vector<NestedNameSpecifierLoc> Locations; + MatchFinder Finder; +}; + +} // end namespace tooling +} // end namespace clang + +#endif // LLVM_CLANG_TOOLING_REFACTOR_RENAME_USR_FINDER_H diff --git a/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFindingAction.h b/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFindingAction.h new file mode 100644 index 000000000000..8aafee95bc09 --- /dev/null +++ b/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFindingAction.h @@ -0,0 +1,54 @@ +//===--- USRFindingAction.h - Clang refactoring library -------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// \brief Provides an action to find all relevant USRs at a point. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLING_REFACTOR_RENAME_USR_FINDING_ACTION_H +#define LLVM_CLANG_TOOLING_REFACTOR_RENAME_USR_FINDING_ACTION_H + +#include "clang/Basic/LLVM.h" +#include "llvm/ADT/ArrayRef.h" + +#include <string> +#include <vector> + +namespace clang { +class ASTConsumer; +class CompilerInstance; +class NamedDecl; + +namespace tooling { + +struct USRFindingAction { + USRFindingAction(ArrayRef<unsigned> SymbolOffsets, + ArrayRef<std::string> QualifiedNames, bool Force) + : SymbolOffsets(SymbolOffsets), QualifiedNames(QualifiedNames), + ErrorOccurred(false), Force(Force) {} + std::unique_ptr<ASTConsumer> newASTConsumer(); + + ArrayRef<std::string> getUSRSpellings() { return SpellingNames; } + ArrayRef<std::vector<std::string>> getUSRList() { return USRList; } + bool errorOccurred() { return ErrorOccurred; } + +private: + std::vector<unsigned> SymbolOffsets; + std::vector<std::string> QualifiedNames; + std::vector<std::string> SpellingNames; + std::vector<std::vector<std::string>> USRList; + bool ErrorOccurred; + bool Force; +}; + +} // end namespace tooling +} // end namespace clang + +#endif // LLVM_CLANG_TOOLING_REFACTOR_RENAME_USR_FINDING_ACTION_H diff --git a/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/USRLocFinder.h b/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/USRLocFinder.h new file mode 100644 index 000000000000..733ea1a6ac9e --- /dev/null +++ b/contrib/llvm/tools/clang/include/clang/Tooling/Refactoring/Rename/USRLocFinder.h @@ -0,0 +1,49 @@ +//===--- USRLocFinder.h - Clang refactoring library -----------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// \brief Provides functionality for finding all instances of a USR in a given +/// AST. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLING_REFACTOR_RENAME_USR_LOC_FINDER_H +#define LLVM_CLANG_TOOLING_REFACTOR_RENAME_USR_LOC_FINDER_H + +#include "clang/AST/AST.h" +#include "clang/Tooling/Core/Replacement.h" +#include "clang/Tooling/Refactoring/AtomicChange.h" +#include "llvm/ADT/StringRef.h" +#include <string> +#include <vector> + +namespace clang { +namespace tooling { + +/// Create atomic changes for renaming all symbol references which are +/// identified by the USRs set to a given new name. +/// +/// \param USRs The set containing USRs of a particular old symbol. +/// \param NewName The new name to replace old symbol name. +/// \param TranslationUnitDecl The translation unit declaration. +/// +/// \return Atomic changes for renaming. +std::vector<tooling::AtomicChange> +createRenameAtomicChanges(llvm::ArrayRef<std::string> USRs, + llvm::StringRef NewName, Decl *TranslationUnitDecl); + +// FIXME: make this an AST matcher. Wouldn't that be awesome??? I agree! +std::vector<SourceLocation> +getLocationsOfUSRs(const std::vector<std::string> &USRs, + llvm::StringRef PrevName, Decl *Decl); + +} // end namespace tooling +} // end namespace clang + +#endif // LLVM_CLANG_TOOLING_REFACTOR_RENAME_USR_LOC_FINDER_H diff --git a/contrib/llvm/tools/clang/include/clang/module.modulemap b/contrib/llvm/tools/clang/include/clang/module.modulemap index 3b4238110026..f7e338d93399 100644 --- a/contrib/llvm/tools/clang/include/clang/module.modulemap +++ b/contrib/llvm/tools/clang/include/clang/module.modulemap @@ -33,6 +33,7 @@ module Clang_Basic { textual header "Basic/BuiltinsLe64.def" textual header "Basic/BuiltinsMips.def" textual header "Basic/BuiltinsNEON.def" + textual header "Basic/BuiltinsNios2.def" textual header "Basic/BuiltinsNVPTX.def" textual header "Basic/BuiltinsPPC.def" textual header "Basic/BuiltinsSystemZ.def" @@ -132,9 +133,10 @@ module Clang_StaticAnalyzer_Frontend { module Clang_Tooling { requires cplusplus umbrella "Tooling" module * { export * } - // FIXME: Exclude this header to avoid pulling all of the AST matchers + // FIXME: Exclude these headers to avoid pulling all of the AST matchers // library into clang-format. Due to inline key functions in the headers, // importing the AST matchers library gives a link dependency on the AST // matchers (and thus the AST), which clang-format should not have. exclude header "Tooling/RefactoringCallbacks.h" + exclude header "Tooling/Refactoring/Rename/USRFinder.h" } diff --git a/contrib/llvm/tools/clang/lib/AST/ASTContext.cpp b/contrib/llvm/tools/clang/lib/AST/ASTContext.cpp index fabfdc9ef7e5..a2ff176df11f 100644 --- a/contrib/llvm/tools/clang/lib/AST/ASTContext.cpp +++ b/contrib/llvm/tools/clang/lib/AST/ASTContext.cpp @@ -5990,9 +5990,19 @@ static void EncodeBitField(const ASTContext *Ctx, std::string& S, // compatibility with GCC, although providing it breaks anything that // actually uses runtime introspection and wants to work on both runtimes... if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { - const RecordDecl *RD = FD->getParent(); - const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); - S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); + uint64_t Offset; + + if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { + Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, + IVD); + } else { + const RecordDecl *RD = FD->getParent(); + const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); + Offset = RL.getFieldOffset(FD->getFieldIndex()); + } + + S += llvm::utostr(Offset); + if (const EnumType *ET = T->getAs<EnumType>()) S += ObjCEncodingForEnumType(Ctx, ET); else { diff --git a/contrib/llvm/tools/clang/lib/AST/ASTStructuralEquivalence.cpp b/contrib/llvm/tools/clang/lib/AST/ASTStructuralEquivalence.cpp index eff1aa5e323d..ea7faab767ed 100644 --- a/contrib/llvm/tools/clang/lib/AST/ASTStructuralEquivalence.cpp +++ b/contrib/llvm/tools/clang/lib/AST/ASTStructuralEquivalence.cpp @@ -735,13 +735,28 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, // Check for equivalent field names. IdentifierInfo *Name1 = Field1->getIdentifier(); IdentifierInfo *Name2 = Field2->getIdentifier(); - if (!::IsStructurallyEquivalent(Name1, Name2)) + if (!::IsStructurallyEquivalent(Name1, Name2)) { + if (Context.Complain) { + Context.Diag2(Owner2->getLocation(), + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) + << Context.ToCtx.getTypeDeclType(Owner2); + Context.Diag2(Field2->getLocation(), diag::note_odr_field_name) + << Field2->getDeclName(); + Context.Diag1(Field1->getLocation(), diag::note_odr_field_name) + << Field1->getDeclName(); + } return false; + } if (!IsStructurallyEquivalent(Context, Field1->getType(), Field2->getType())) { if (Context.Complain) { - Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent) + Context.Diag2(Owner2->getLocation(), + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) << Context.ToCtx.getTypeDeclType(Owner2); Context.Diag2(Field2->getLocation(), diag::note_odr_field) << Field2->getDeclName() << Field2->getType(); @@ -753,7 +768,10 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, if (Field1->isBitField() != Field2->isBitField()) { if (Context.Complain) { - Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent) + Context.Diag2(Owner2->getLocation(), + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) << Context.ToCtx.getTypeDeclType(Owner2); if (Field1->isBitField()) { Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field) @@ -780,7 +798,9 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, if (Bits1 != Bits2) { if (Context.Complain) { Context.Diag2(Owner2->getLocation(), - diag::warn_odr_tag_type_inconsistent) + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) << Context.ToCtx.getTypeDeclType(Owner2); Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field) << Field2->getDeclName() << Field2->getType() << Bits2; @@ -799,7 +819,10 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, RecordDecl *D1, RecordDecl *D2) { if (D1->isUnion() != D2->isUnion()) { if (Context.Complain) { - Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) + Context.Diag2(D2->getLocation(), + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) << Context.ToCtx.getTypeDeclType(D2); Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here) << D1->getDeclName() << (unsigned)D1->getTagKind(); @@ -927,7 +950,10 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Field1 != Field1End; ++Field1, ++Field2) { if (Field2 == Field2End) { if (Context.Complain) { - Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) + Context.Diag2(D2->getLocation(), + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) << Context.ToCtx.getTypeDeclType(D2); Context.Diag1(Field1->getLocation(), diag::note_odr_field) << Field1->getDeclName() << Field1->getType(); @@ -942,7 +968,10 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, if (Field2 != Field2End) { if (Context.Complain) { - Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) + Context.Diag2(D2->getLocation(), + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2(Field2->getLocation(), diag::note_odr_field) << Field2->getDeclName() << Field2->getType(); @@ -964,7 +993,10 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, EC1 != EC1End; ++EC1, ++EC2) { if (EC2 == EC2End) { if (Context.Complain) { - Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) + Context.Diag2(D2->getLocation(), + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) << Context.ToCtx.getTypeDeclType(D2); Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator) << EC1->getDeclName() << EC1->getInitVal().toString(10); @@ -978,7 +1010,10 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, if (!llvm::APSInt::isSameValue(Val1, Val2) || !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) { if (Context.Complain) { - Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) + Context.Diag2(D2->getLocation(), + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator) << EC2->getDeclName() << EC2->getInitVal().toString(10); @@ -991,7 +1026,10 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, if (EC2 != EC2End) { if (Context.Complain) { - Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) + Context.Diag2(D2->getLocation(), + Context.ErrorOnTagTypeMismatch + ? diag::err_odr_tag_type_inconsistent + : diag::warn_odr_tag_type_inconsistent) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator) << EC2->getDeclName() << EC2->getInitVal().toString(10); diff --git a/contrib/llvm/tools/clang/lib/AST/Decl.cpp b/contrib/llvm/tools/clang/lib/AST/Decl.cpp index 9862f4f26473..267c6992af89 100644 --- a/contrib/llvm/tools/clang/lib/AST/Decl.cpp +++ b/contrib/llvm/tools/clang/lib/AST/Decl.cpp @@ -1251,7 +1251,9 @@ static LinkageInfo computeLVForDecl(const NamedDecl *D, case Decl::EnumConstant: // C++ [basic.link]p4: an enumerator has the linkage of its enumeration. - return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation); + if (D->getASTContext().getLangOpts().CPlusPlus) + return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation); + return LinkageInfo::visible_none(); case Decl::Typedef: case Decl::TypeAlias: @@ -2630,7 +2632,7 @@ bool FunctionDecl::isReservedGlobalPlacementOperator() const { return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy); } -bool FunctionDecl::isReplaceableGlobalAllocationFunction() const { +bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const { if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) return false; if (getDeclName().getCXXOverloadedOperator() != OO_New && @@ -2676,8 +2678,11 @@ bool FunctionDecl::isReplaceableGlobalAllocationFunction() const { // In C++17, the next parameter can be a 'std::align_val_t' for aligned // new/delete. - if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) + if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) { + if (IsAligned) + *IsAligned = true; Consume(); + } // Finally, if this is not a sized delete, the final parameter can // be a 'const std::nothrow_t&'. diff --git a/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp b/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp index 9f87fe12a9cd..07d128ba555b 100644 --- a/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp +++ b/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp @@ -1417,11 +1417,8 @@ CXXDestructorDecl *CXXRecordDecl::getDestructor() const { Context.getCanonicalType(ClassType)); DeclContext::lookup_result R = lookup(Name); - if (R.empty()) - return nullptr; - CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(R.front()); - return Dtor; + return R.empty() ? nullptr : dyn_cast<CXXDestructorDecl>(R.front()); } bool CXXRecordDecl::isAnyDestructorNoReturn() const { diff --git a/contrib/llvm/tools/clang/lib/AST/Expr.cpp b/contrib/llvm/tools/clang/lib/AST/Expr.cpp index c21cd3f65bd4..afc7fa8ea094 100644 --- a/contrib/llvm/tools/clang/lib/AST/Expr.cpp +++ b/contrib/llvm/tools/clang/lib/AST/Expr.cpp @@ -1641,25 +1641,32 @@ const char *CastExpr::getCastKindName() const { llvm_unreachable("Unhandled cast kind!"); } +namespace { + Expr *skipImplicitTemporary(Expr *expr) { + // Skip through reference binding to temporary. + if (MaterializeTemporaryExpr *Materialize + = dyn_cast<MaterializeTemporaryExpr>(expr)) + expr = Materialize->GetTemporaryExpr(); + + // Skip any temporary bindings; they're implicit. + if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(expr)) + expr = Binder->getSubExpr(); + + return expr; + } +} + Expr *CastExpr::getSubExprAsWritten() { Expr *SubExpr = nullptr; CastExpr *E = this; do { - SubExpr = E->getSubExpr(); + SubExpr = skipImplicitTemporary(E->getSubExpr()); - // Skip through reference binding to temporary. - if (MaterializeTemporaryExpr *Materialize - = dyn_cast<MaterializeTemporaryExpr>(SubExpr)) - SubExpr = Materialize->GetTemporaryExpr(); - - // Skip any temporary bindings; they're implicit. - if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) - SubExpr = Binder->getSubExpr(); - // Conversions by constructor and conversion functions have a // subexpression describing the call; strip it off. if (E->getCastKind() == CK_ConstructorConversion) - SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0); + SubExpr = + skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0)); else if (E->getCastKind() == CK_UserDefinedConversion) { assert((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) && diff --git a/contrib/llvm/tools/clang/lib/AST/ExprConstant.cpp b/contrib/llvm/tools/clang/lib/AST/ExprConstant.cpp index 768947d00ac4..e836135cf2f9 100644 --- a/contrib/llvm/tools/clang/lib/AST/ExprConstant.cpp +++ b/contrib/llvm/tools/clang/lib/AST/ExprConstant.cpp @@ -6226,10 +6226,6 @@ bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { // the initializer list. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; - if (Init->isValueDependent()) { - Success = false; - continue; - } // Temporarily override This, in case there's a CXXDefaultInitExpr in here. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, @@ -9940,8 +9936,7 @@ static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { } static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, - const ASTContext &Ctx, bool &IsConst, - bool IsCheckingForOverflow) { + const ASTContext &Ctx, bool &IsConst) { // Fast-path evaluations of integer literals, since we sometimes see files // containing vast quantities of these. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { @@ -9962,7 +9957,7 @@ static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, // performance problems. Only do so in C++11 for now. if (Exp->isRValue() && (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && - !Ctx.getLangOpts().CPlusPlus11 && !IsCheckingForOverflow) { + !Ctx.getLangOpts().CPlusPlus11) { IsConst = false; return true; } @@ -9977,7 +9972,7 @@ static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, /// will be applied to the result. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { bool IsConst; - if (FastEvaluateAsRValue(this, Result, Ctx, IsConst, false)) + if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) return IsConst; EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); @@ -10102,7 +10097,7 @@ APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { bool IsConst; EvalResult EvalResult; - if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst, true)) { + if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) { EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); (void)::EvaluateAsRValue(Info, this, EvalResult.Val); } diff --git a/contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp b/contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp index cc7a6941f63a..3a899bdbb6d2 100644 --- a/contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp +++ b/contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp @@ -966,16 +966,71 @@ void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) { } if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) { - DiagnosticsEngine &Diags = Context.getDiags(); - unsigned DiagID = - Diags.getCustomDiagID(DiagnosticsEngine::Error, - "cannot mangle a local inside this block yet"); - Diags.Report(BD->getLocation(), DiagID); - - // FIXME: This is completely, utterly, wrong; see ItaniumMangle - // for how this should be done. - Out << "__block_invoke" << Context.getBlockId(BD, false); - Out << '@'; + auto Discriminate = + [](StringRef Name, const unsigned Discriminator, + const unsigned ParameterDiscriminator) -> std::string { + std::string Buffer; + llvm::raw_string_ostream Stream(Buffer); + Stream << Name; + if (Discriminator) + Stream << '_' << Discriminator; + if (ParameterDiscriminator) + Stream << '_' << ParameterDiscriminator; + return Stream.str(); + }; + + unsigned Discriminator = BD->getBlockManglingNumber(); + if (!Discriminator) + Discriminator = Context.getBlockId(BD, /*Local=*/false); + + // Mangle the parameter position as a discriminator to deal with unnamed + // parameters. Rather than mangling the unqualified parameter name, + // always use the position to give a uniform mangling. + unsigned ParameterDiscriminator = 0; + if (const auto *MC = BD->getBlockManglingContextDecl()) + if (const auto *P = dyn_cast<ParmVarDecl>(MC)) + if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext())) + ParameterDiscriminator = + F->getNumParams() - P->getFunctionScopeIndex(); + + DC = getEffectiveDeclContext(BD); + + Out << '?'; + mangleSourceName(Discriminate("_block_invoke", Discriminator, + ParameterDiscriminator)); + // If we have a block mangling context, encode that now. This allows us + // to discriminate between named static data initializers in the same + // scope. This is handled differently from parameters, which use + // positions to discriminate between multiple instances. + if (const auto *MC = BD->getBlockManglingContextDecl()) + if (!isa<ParmVarDecl>(MC)) + if (const auto *ND = dyn_cast<NamedDecl>(MC)) + mangleUnqualifiedName(ND); + // MS ABI and Itanium manglings are in inverted scopes. In the case of a + // RecordDecl, mangle the entire scope hierachy at this point rather than + // just the unqualified name to get the ordering correct. + if (const auto *RD = dyn_cast<RecordDecl>(DC)) + mangleName(RD); + else + Out << '@'; + // void __cdecl + Out << "YAX"; + // struct __block_literal * + Out << 'P'; + // __ptr64 + if (PointersAre64Bit) + Out << 'E'; + Out << 'A'; + mangleArtificalTagType(TTK_Struct, + Discriminate("__block_literal", Discriminator, + ParameterDiscriminator)); + Out << "@Z"; + + // If the effective context was a Record, we have fully mangled the + // qualified name and do not need to continue. + if (isa<RecordDecl>(DC)) + break; + continue; } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) { mangleObjCMethodName(Method); } else if (isa<NamedDecl>(DC)) { diff --git a/contrib/llvm/tools/clang/lib/AST/ODRHash.cpp b/contrib/llvm/tools/clang/lib/AST/ODRHash.cpp index 05bed658f3fc..3f66e58eb868 100644 --- a/contrib/llvm/tools/clang/lib/AST/ODRHash.cpp +++ b/contrib/llvm/tools/clang/lib/AST/ODRHash.cpp @@ -82,25 +82,13 @@ void ODRHash::AddDeclarationName(DeclarationName Name) { } void ODRHash::AddNestedNameSpecifier(const NestedNameSpecifier *NNS) { - // Unlike the other pointer handling functions, allow null pointers here. - if (!NNS) { - AddBoolean(false); - return; + assert(NNS && "Expecting non-null pointer."); + const auto *Prefix = NNS->getPrefix(); + AddBoolean(Prefix); + if (Prefix) { + AddNestedNameSpecifier(Prefix); } - - // Skip inlined namespaces. auto Kind = NNS->getKind(); - if (Kind == NestedNameSpecifier::Namespace) { - if (NNS->getAsNamespace()->isInline()) { - return AddNestedNameSpecifier(NNS->getPrefix()); - } - } - - AddBoolean(true); - - // Process prefix - AddNestedNameSpecifier(NNS->getPrefix()); - ID.AddInteger(Kind); switch (Kind) { case NestedNameSpecifier::Identifier: @@ -146,7 +134,10 @@ void ODRHash::AddTemplateArgument(TemplateArgument TA) { switch (Kind) { case TemplateArgument::Null: + llvm_unreachable("Expected valid TemplateArgument"); case TemplateArgument::Type: + AddQualType(TA.getAsType()); + break; case TemplateArgument::Declaration: case TemplateArgument::NullPtr: case TemplateArgument::Integral: @@ -430,8 +421,18 @@ public: Hash.AddQualType(T); } + void AddType(const Type *T) { + Hash.AddBoolean(T); + if (T) { + Hash.AddType(T); + } + } + void AddNestedNameSpecifier(const NestedNameSpecifier *NNS) { - Hash.AddNestedNameSpecifier(NNS); + Hash.AddBoolean(NNS); + if (NNS) { + Hash.AddNestedNameSpecifier(NNS); + } } void AddIdentifierInfo(const IdentifierInfo *II) { @@ -517,7 +518,13 @@ public: void VisitTypedefType(const TypedefType *T) { AddDecl(T->getDecl()); - AddQualType(T->getDecl()->getUnderlyingType().getCanonicalType()); + QualType UnderlyingType = T->getDecl()->getUnderlyingType(); + VisitQualifiers(UnderlyingType.getQualifiers()); + while (const TypedefType *Underlying = + dyn_cast<TypedefType>(UnderlyingType.getTypePtr())) { + UnderlyingType = Underlying->getDecl()->getUnderlyingType(); + } + AddType(UnderlyingType.getTypePtr()); VisitType(T); } diff --git a/contrib/llvm/tools/clang/lib/AST/RecordLayoutBuilder.cpp b/contrib/llvm/tools/clang/lib/AST/RecordLayoutBuilder.cpp index cf981be0a4dd..c0b9cadca422 100644 --- a/contrib/llvm/tools/clang/lib/AST/RecordLayoutBuilder.cpp +++ b/contrib/llvm/tools/clang/lib/AST/RecordLayoutBuilder.cpp @@ -3073,6 +3073,41 @@ uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const { return OffsetInBits; } +uint64_t ASTContext::lookupFieldBitOffset(const ObjCInterfaceDecl *OID, + const ObjCImplementationDecl *ID, + const ObjCIvarDecl *Ivar) const { + const ObjCInterfaceDecl *Container = Ivar->getContainingInterface(); + + // FIXME: We should eliminate the need to have ObjCImplementationDecl passed + // in here; it should never be necessary because that should be the lexical + // decl context for the ivar. + + // If we know have an implementation (and the ivar is in it) then + // look up in the implementation layout. + const ASTRecordLayout *RL; + if (ID && declaresSameEntity(ID->getClassInterface(), Container)) + RL = &getASTObjCImplementationLayout(ID); + else + RL = &getASTObjCInterfaceLayout(Container); + + // Compute field index. + // + // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is + // implemented. This should be fixed to get the information from the layout + // directly. + unsigned Index = 0; + + for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin(); + IVD; IVD = IVD->getNextIvar()) { + if (Ivar == IVD) + break; + ++Index; + } + assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!"); + + return RL->getFieldOffset(Index); +} + /// getObjCLayout - Get or compute information about the layout of the /// given interface. /// diff --git a/contrib/llvm/tools/clang/lib/AST/StmtProfile.cpp b/contrib/llvm/tools/clang/lib/AST/StmtProfile.cpp index 99a25f342526..f1fbe2806b5d 100644 --- a/contrib/llvm/tools/clang/lib/AST/StmtProfile.cpp +++ b/contrib/llvm/tools/clang/lib/AST/StmtProfile.cpp @@ -186,7 +186,10 @@ namespace { Hash.AddTemplateName(Name); } void VisitNestedNameSpecifier(NestedNameSpecifier *NNS) override { - Hash.AddNestedNameSpecifier(NNS); + ID.AddBoolean(NNS); + if (NNS) { + Hash.AddNestedNameSpecifier(NNS); + } } }; } diff --git a/contrib/llvm/tools/clang/lib/Basic/SourceLocation.cpp b/contrib/llvm/tools/clang/lib/Basic/SourceLocation.cpp index a58d0465a6f4..89ddbc946a49 100644 --- a/contrib/llvm/tools/clang/lib/Basic/SourceLocation.cpp +++ b/contrib/llvm/tools/clang/lib/Basic/SourceLocation.cpp @@ -92,6 +92,76 @@ FullSourceLoc FullSourceLoc::getSpellingLoc() const { return FullSourceLoc(SrcMgr->getSpellingLoc(*this), *SrcMgr); } +FullSourceLoc FullSourceLoc::getFileLoc() const { + assert(isValid()); + return FullSourceLoc(SrcMgr->getFileLoc(*this), *SrcMgr); +} + +std::pair<FullSourceLoc, FullSourceLoc> +FullSourceLoc::getImmediateExpansionRange() const { + assert(isValid()); + std::pair<SourceLocation, SourceLocation> Range = + SrcMgr->getImmediateExpansionRange(*this); + return std::make_pair(FullSourceLoc(Range.first, *SrcMgr), + FullSourceLoc(Range.second, *SrcMgr)); +} + +PresumedLoc FullSourceLoc::getPresumedLoc(bool UseLineDirectives) const { + if (!isValid()) + return PresumedLoc(); + + return SrcMgr->getPresumedLoc(*this, UseLineDirectives); +} + +bool FullSourceLoc::isMacroArgExpansion(FullSourceLoc *StartLoc) const { + assert(isValid()); + return SrcMgr->isMacroArgExpansion(*this, StartLoc); +} + +FullSourceLoc FullSourceLoc::getImmediateMacroCallerLoc() const { + assert(isValid()); + return FullSourceLoc(SrcMgr->getImmediateMacroCallerLoc(*this), *SrcMgr); +} + +std::pair<FullSourceLoc, StringRef> FullSourceLoc::getModuleImportLoc() const { + if (!isValid()) + return std::make_pair(FullSourceLoc(), StringRef()); + + std::pair<SourceLocation, StringRef> ImportLoc = + SrcMgr->getModuleImportLoc(*this); + return std::make_pair(FullSourceLoc(ImportLoc.first, *SrcMgr), + ImportLoc.second); +} + +unsigned FullSourceLoc::getFileOffset() const { + assert(isValid()); + return SrcMgr->getFileOffset(*this); +} + +unsigned FullSourceLoc::getLineNumber(bool *Invalid) const { + assert(isValid()); + return SrcMgr->getLineNumber(getFileID(), getFileOffset(), Invalid); +} + +unsigned FullSourceLoc::getColumnNumber(bool *Invalid) const { + assert(isValid()); + return SrcMgr->getColumnNumber(getFileID(), getFileOffset(), Invalid); +} + +std::pair<FullSourceLoc, FullSourceLoc> +FullSourceLoc::getExpansionRange() const { + assert(isValid()); + std::pair<SourceLocation, SourceLocation> Range = + SrcMgr->getExpansionRange(*this); + return std::make_pair(FullSourceLoc(Range.first, *SrcMgr), + FullSourceLoc(Range.second, *SrcMgr)); +} + +const FileEntry *FullSourceLoc::getFileEntry() const { + assert(isValid()); + return SrcMgr->getFileEntryForID(getFileID()); +} + unsigned FullSourceLoc::getExpansionLineNumber(bool *Invalid) const { assert(isValid()); return SrcMgr->getExpansionLineNumber(*this, Invalid); diff --git a/contrib/llvm/tools/clang/lib/Basic/SourceManager.cpp b/contrib/llvm/tools/clang/lib/Basic/SourceManager.cpp index 3936afab21a4..f0b53b4e48a5 100644 --- a/contrib/llvm/tools/clang/lib/Basic/SourceManager.cpp +++ b/contrib/llvm/tools/clang/lib/Basic/SourceManager.cpp @@ -2018,9 +2018,51 @@ bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, if (LOffs.first.isInvalid() || ROffs.first.isInvalid()) return LOffs.first.isInvalid() && !ROffs.first.isInvalid(); + std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs); + if (InSameTU.first) + return InSameTU.second; + + // If we arrived here, the location is either in a built-ins buffer or + // associated with global inline asm. PR5662 and PR22576 are examples. + + StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier(); + StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier(); + bool LIsBuiltins = LB == "<built-in>"; + bool RIsBuiltins = RB == "<built-in>"; + // Sort built-in before non-built-in. + if (LIsBuiltins || RIsBuiltins) { + if (LIsBuiltins != RIsBuiltins) + return LIsBuiltins; + // Both are in built-in buffers, but from different files. We just claim that + // lower IDs come first. + return LOffs.first < ROffs.first; + } + bool LIsAsm = LB == "<inline asm>"; + bool RIsAsm = RB == "<inline asm>"; + // Sort assembler after built-ins, but before the rest. + if (LIsAsm || RIsAsm) { + if (LIsAsm != RIsAsm) + return RIsAsm; + assert(LOffs.first == ROffs.first); + return false; + } + bool LIsScratch = LB == "<scratch space>"; + bool RIsScratch = RB == "<scratch space>"; + // Sort scratch after inline asm, but before the rest. + if (LIsScratch || RIsScratch) { + if (LIsScratch != RIsScratch) + return LIsScratch; + return LOffs.second < ROffs.second; + } + llvm_unreachable("Unsortable locations found"); +} + +std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit( + std::pair<FileID, unsigned> &LOffs, + std::pair<FileID, unsigned> &ROffs) const { // If the source locations are in the same file, just compare offsets. if (LOffs.first == ROffs.first) - return LOffs.second < ROffs.second; + return std::make_pair(true, LOffs.second < ROffs.second); // If we are comparing a source location with multiple locations in the same // file, we get a big win by caching the result. @@ -2030,7 +2072,8 @@ bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, // If we are comparing a source location with multiple locations in the same // file, we get a big win by caching the result. if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first)) - return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second); + return std::make_pair( + true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second)); // Okay, we missed in the cache, start updating the cache for this query. IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first, @@ -2060,44 +2103,12 @@ bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, // locations within the common file and cache them. if (LOffs.first == ROffs.first) { IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second); - return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second); + return std::make_pair( + true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second)); } - - // If we arrived here, the location is either in a built-ins buffer or - // associated with global inline asm. PR5662 and PR22576 are examples. - // Clear the lookup cache, it depends on a common location. IsBeforeInTUCache.clear(); - StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier(); - StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier(); - bool LIsBuiltins = LB == "<built-in>"; - bool RIsBuiltins = RB == "<built-in>"; - // Sort built-in before non-built-in. - if (LIsBuiltins || RIsBuiltins) { - if (LIsBuiltins != RIsBuiltins) - return LIsBuiltins; - // Both are in built-in buffers, but from different files. We just claim that - // lower IDs come first. - return LOffs.first < ROffs.first; - } - bool LIsAsm = LB == "<inline asm>"; - bool RIsAsm = RB == "<inline asm>"; - // Sort assembler after built-ins, but before the rest. - if (LIsAsm || RIsAsm) { - if (LIsAsm != RIsAsm) - return RIsAsm; - assert(LOffs.first == ROffs.first); - return false; - } - bool LIsScratch = LB == "<scratch space>"; - bool RIsScratch = RB == "<scratch space>"; - // Sort scratch after inline asm, but before the rest. - if (LIsScratch || RIsScratch) { - if (LIsScratch != RIsScratch) - return LIsScratch; - return LOffs.second < ROffs.second; - } - llvm_unreachable("Unsortable locations found"); + return std::make_pair(false, false); } void SourceManager::PrintStats() const { diff --git a/contrib/llvm/tools/clang/lib/Basic/Targets.cpp b/contrib/llvm/tools/clang/lib/Basic/Targets.cpp index c5af99e4b6af..4f04489a4a10 100644 --- a/contrib/llvm/tools/clang/lib/Basic/Targets.cpp +++ b/contrib/llvm/tools/clang/lib/Basic/Targets.cpp @@ -2706,7 +2706,7 @@ class X86TargetInfo : public TargetInfo { CK_C3_2, /// This enumerator is a bit odd, as GCC no longer accepts -march=yonah. - /// Clang however has some logic to suport this. + /// Clang however has some logic to support this. // FIXME: Warn, deprecate, and potentially remove this. CK_Yonah, //@} @@ -2737,6 +2737,7 @@ class X86TargetInfo : public TargetInfo { //@{ CK_Bonnell, CK_Silvermont, + CK_Goldmont, //@} /// \name Nehalem @@ -2878,6 +2879,7 @@ class X86TargetInfo : public TargetInfo { .Case("atom", CK_Bonnell) // Legacy name. .Case("silvermont", CK_Silvermont) .Case("slm", CK_Silvermont) // Legacy name. + .Case("goldmont", CK_Goldmont) .Case("nehalem", CK_Nehalem) .Case("corei7", CK_Nehalem) // Legacy name. .Case("westmere", CK_Westmere) @@ -3093,6 +3095,7 @@ public: case CK_Penryn: case CK_Bonnell: case CK_Silvermont: + case CK_Goldmont: case CK_Nehalem: case CK_Westmere: case CK_SandyBridge: @@ -3221,7 +3224,6 @@ bool X86TargetInfo::initFeatureMap( setFeatureEnabledImpl(Features, "cx16", true); break; case CK_Core2: - case CK_Bonnell: setFeatureEnabledImpl(Features, "ssse3", true); setFeatureEnabledImpl(Features, "fxsr", true); setFeatureEnabledImpl(Features, "cx16", true); @@ -3276,7 +3278,6 @@ bool X86TargetInfo::initFeatureMap( setFeatureEnabledImpl(Features, "xsaveopt", true); LLVM_FALLTHROUGH; case CK_Westmere: - case CK_Silvermont: setFeatureEnabledImpl(Features, "aes", true); setFeatureEnabledImpl(Features, "pclmul", true); LLVM_FALLTHROUGH; @@ -3285,6 +3286,28 @@ bool X86TargetInfo::initFeatureMap( setFeatureEnabledImpl(Features, "fxsr", true); setFeatureEnabledImpl(Features, "cx16", true); break; + case CK_Goldmont: + setFeatureEnabledImpl(Features, "sha", true); + setFeatureEnabledImpl(Features, "rdrnd", true); + setFeatureEnabledImpl(Features, "rdseed", true); + setFeatureEnabledImpl(Features, "xsave", true); + setFeatureEnabledImpl(Features, "xsaveopt", true); + setFeatureEnabledImpl(Features, "xsavec", true); + setFeatureEnabledImpl(Features, "xsaves", true); + setFeatureEnabledImpl(Features, "clflushopt", true); + setFeatureEnabledImpl(Features, "mpx", true); + LLVM_FALLTHROUGH; + case CK_Silvermont: + setFeatureEnabledImpl(Features, "aes", true); + setFeatureEnabledImpl(Features, "pclmul", true); + setFeatureEnabledImpl(Features, "sse4.2", true); + LLVM_FALLTHROUGH; + case CK_Bonnell: + setFeatureEnabledImpl(Features, "movbe", true); + setFeatureEnabledImpl(Features, "ssse3", true); + setFeatureEnabledImpl(Features, "fxsr", true); + setFeatureEnabledImpl(Features, "cx16", true); + break; case CK_KNL: setFeatureEnabledImpl(Features, "avx512f", true); setFeatureEnabledImpl(Features, "avx512cd", true); @@ -3524,6 +3547,7 @@ void X86TargetInfo::setSSELevel(llvm::StringMap<bool> &Features, Features["avx512pf"] = Features["avx512dq"] = Features["avx512bw"] = Features["avx512vl"] = Features["avx512vbmi"] = Features["avx512ifma"] = Features["avx512vpopcntdq"] = false; + break; } } @@ -3556,6 +3580,7 @@ void X86TargetInfo::setMMXLevel(llvm::StringMap<bool> &Features, LLVM_FALLTHROUGH; case AMD3DNowAthlon: Features["3dnowa"] = false; + break; } } @@ -3590,6 +3615,7 @@ void X86TargetInfo::setXOPLevel(llvm::StringMap<bool> &Features, XOPEnum Level, LLVM_FALLTHROUGH; case XOP: Features["xop"] = false; + break; } } @@ -3893,6 +3919,9 @@ void X86TargetInfo::getTargetDefines(const LangOptions &Opts, case CK_Silvermont: defineCPUMacros(Builder, "slm"); break; + case CK_Goldmont: + defineCPUMacros(Builder, "goldmont"); + break; case CK_Nehalem: case CK_Westmere: case CK_SandyBridge: @@ -4156,6 +4185,7 @@ void X86TargetInfo::getTargetDefines(const LangOptions &Opts, break; default: Builder.defineMacro("_M_IX86_FP", Twine(0)); + break; } } @@ -5413,7 +5443,7 @@ public: if (Triple.getOS() == llvm::Triple::Linux || Triple.getOS() == llvm::Triple::UnknownOS) this->MCountName = - Opts.EABIVersion == "gnu" ? "\01__gnu_mcount_nc" : "\01mcount"; + Opts.EABIVersion == llvm::EABI::GNU ? "\01__gnu_mcount_nc" : "\01mcount"; } StringRef getABI() const override { return ABI; } @@ -5594,6 +5624,17 @@ public: bool setFPMath(StringRef Name) override; + void getTargetDefinesARMV81A(const LangOptions &Opts, + MacroBuilder &Builder) const { + Builder.defineMacro("__ARM_FEATURE_QRDMX", "1"); + } + + void getTargetDefinesARMV82A(const LangOptions &Opts, + MacroBuilder &Builder) const { + // Also include the ARMv8.1-A defines + getTargetDefinesARMV81A(Opts, Builder); + } + void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { // Target identification. @@ -5792,8 +5833,15 @@ public: if (Opts.UnsafeFPMath) Builder.defineMacro("__ARM_FP_FAST", "1"); - if (ArchKind == llvm::ARM::AK_ARMV8_1A) - Builder.defineMacro("__ARM_FEATURE_QRDMX", "1"); + switch(ArchKind) { + default: break; + case llvm::ARM::AK_ARMV8_1A: + getTargetDefinesARMV81A(Opts, Builder); + break; + case llvm::ARM::AK_ARMV8_2A: + getTargetDefinesARMV82A(Opts, Builder); + break; + } } ArrayRef<Builtin::Info> getTargetBuiltins() const override { @@ -6186,9 +6234,8 @@ class AArch64TargetInfo : public TargetInfo { unsigned CRC; unsigned Crypto; unsigned Unaligned; - unsigned V8_1A; - unsigned V8_2A; unsigned HasFullFP16; + llvm::AArch64::ArchKind ArchKind; static const Builtin::Info BuiltinInfo[]; @@ -6236,7 +6283,7 @@ public: if (Triple.getOS() == llvm::Triple::Linux) this->MCountName = "\01_mcount"; else if (Triple.getOS() == llvm::Triple::UnknownOS) - this->MCountName = Opts.EABIVersion == "gnu" ? "\01_mcount" : "mcount"; + this->MCountName = Opts.EABIVersion == llvm::EABI::GNU ? "\01_mcount" : "mcount"; } StringRef getABI() const override { return ABI; } @@ -6254,6 +6301,20 @@ public: static_cast<unsigned>(llvm::AArch64::ArchKind::AK_INVALID); } + void getTargetDefinesARMV81A(const LangOptions &Opts, + MacroBuilder &Builder) const { + Builder.defineMacro("__ARM_FEATURE_QRDMX", "1"); + } + + void getTargetDefinesARMV82A(const LangOptions &Opts, + MacroBuilder &Builder) const { + // Also include the ARMv8.1 defines + getTargetDefinesARMV81A(Opts, Builder); + + if (FPU == NeonMode && HasFullFP16) + Builder.defineMacro("__ARM_FEATURE_FP16_VECTOR_ARITHMETIC", "1"); + } + void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { // Target identification. @@ -6318,10 +6379,15 @@ public: if (Unaligned) Builder.defineMacro("__ARM_FEATURE_UNALIGNED", "1"); - if (V8_1A) - Builder.defineMacro("__ARM_FEATURE_QRDMX", "1"); - if (V8_2A && FPU == NeonMode && HasFullFP16) - Builder.defineMacro("__ARM_FEATURE_FP16_VECTOR_ARITHMETIC", "1"); + switch(ArchKind) { + default: break; + case llvm::AArch64::ArchKind::AK_ARMV8_1A: + getTargetDefinesARMV81A(Opts, Builder); + break; + case llvm::AArch64::ArchKind::AK_ARMV8_2A: + getTargetDefinesARMV82A(Opts, Builder); + break; + } // All of the __sync_(bool|val)_compare_and_swap_(1|2|4|8) builtins work. Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1"); @@ -6348,9 +6414,8 @@ public: CRC = 0; Crypto = 0; Unaligned = 1; - V8_1A = 0; - V8_2A = 0; HasFullFP16 = 0; + ArchKind = llvm::AArch64::ArchKind::AK_ARMV8A; for (const auto &Feature : Features) { if (Feature == "+neon") @@ -6362,9 +6427,9 @@ public: if (Feature == "+strict-align") Unaligned = 0; if (Feature == "+v8.1a") - V8_1A = 1; + ArchKind = llvm::AArch64::ArchKind::AK_ARMV8_1A; if (Feature == "+v8.2a") - V8_2A = 1; + ArchKind = llvm::AArch64::ArchKind::AK_ARMV8_2A; if (Feature == "+fullfp16") HasFullFP16 = 1; } @@ -6550,6 +6615,43 @@ public: } }; +class MicrosoftARM64TargetInfo + : public WindowsTargetInfo<AArch64leTargetInfo> { + const llvm::Triple Triple; + +public: + MicrosoftARM64TargetInfo(const llvm::Triple &Triple, + const TargetOptions &Opts) + : WindowsTargetInfo<AArch64leTargetInfo>(Triple, Opts), Triple(Triple) { + WCharType = UnsignedShort; + SizeType = UnsignedLongLong; + TheCXXABI.set(TargetCXXABI::Microsoft); + } + + void setDataLayout() override { + resetDataLayout("e-m:w-i64:64-i128:128-n32:64-S128"); + } + + void getVisualStudioDefines(const LangOptions &Opts, + MacroBuilder &Builder) const { + WindowsTargetInfo<AArch64leTargetInfo>::getVisualStudioDefines(Opts, + Builder); + Builder.defineMacro("_WIN32", "1"); + Builder.defineMacro("_WIN64", "1"); + Builder.defineMacro("_M_ARM64", "1"); + } + + void getTargetDefines(const LangOptions &Opts, + MacroBuilder &Builder) const override { + WindowsTargetInfo::getTargetDefines(Opts, Builder); + getVisualStudioDefines(Opts, Builder); + } + + BuiltinVaListKind getBuiltinVaListKind() const override { + return TargetInfo::CharPtrBuiltinVaList; + } +}; + class AArch64beTargetInfo : public AArch64TargetInfo { void setDataLayout() override { assert(!getTriple().isOSBinFormatMachO()); @@ -7727,6 +7829,148 @@ public: } }; +class Nios2TargetInfo : public TargetInfo { + void setDataLayout() { + if (BigEndian) + resetDataLayout("E-p:32:32:32-i8:8:32-i16:16:32-n32"); + else + resetDataLayout("e-p:32:32:32-i8:8:32-i16:16:32-n32"); + } + + static const Builtin::Info BuiltinInfo[]; + std::string CPU; + std::string ABI; + +public: + Nios2TargetInfo(const llvm::Triple &triple, const TargetOptions &opts) + : TargetInfo(triple), CPU(opts.CPU), ABI(opts.ABI) { + SizeType = UnsignedInt; + PtrDiffType = SignedInt; + MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32; + setDataLayout(); + } + + StringRef getABI() const override { return ABI; } + bool setABI(const std::string &Name) override { + if (Name == "o32" || Name == "eabi") { + ABI = Name; + return true; + } + return false; + } + + bool setCPU(const std::string &Name) override { + if (Name == "nios2r1" || Name == "nios2r2") { + CPU = Name; + return true; + } + return false; + } + + void getTargetDefines(const LangOptions &Opts, + MacroBuilder &Builder) const override { + DefineStd(Builder, "nios2", Opts); + DefineStd(Builder, "NIOS2", Opts); + + Builder.defineMacro("__nios2"); + Builder.defineMacro("__NIOS2"); + Builder.defineMacro("__nios2__"); + Builder.defineMacro("__NIOS2__"); + } + + ArrayRef<Builtin::Info> getTargetBuiltins() const override { + return llvm::makeArrayRef(BuiltinInfo, clang::Nios2::LastTSBuiltin - + Builtin::FirstTSBuiltin); + } + + bool isFeatureSupportedByCPU(StringRef Feature, StringRef CPU) const { + const bool isR2 = CPU == "nios2r2"; + return llvm::StringSwitch<bool>(Feature) + .Case("nios2r2mandatory", isR2) + .Case("nios2r2bmx", isR2) + .Case("nios2r2mpx", isR2) + .Case("nios2r2cdx", isR2) + .Default(false); + } + + bool initFeatureMap(llvm::StringMap<bool> &Features, + DiagnosticsEngine &Diags, StringRef CPU, + const std::vector<std::string> &FeatureVec) const override { + static const char *allFeatures[] = { + "nios2r2mandatory", "nios2r2bmx", "nios2r2mpx", "nios2r2cdx" + }; + for (const char *feature : allFeatures) { + Features[feature] = isFeatureSupportedByCPU(feature, CPU); + } + return true; + } + + bool hasFeature(StringRef Feature) const override { + return isFeatureSupportedByCPU(Feature, CPU); + } + + BuiltinVaListKind getBuiltinVaListKind() const override { + return TargetInfo::VoidPtrBuiltinVaList; + } + + ArrayRef<const char *> getGCCRegNames() const override { + static const char *const GCCRegNames[] = { + // CPU register names + // Must match second column of GCCRegAliases + "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", + "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", + "r31", + // Floating point register names + "ctl0", "ctl1", "ctl2", "ctl3", "ctl4", "ctl5", "ctl6", "ctl7", "ctl8", + "ctl9", "ctl10", "ctl11", "ctl12", "ctl13", "ctl14", "ctl15" + }; + return llvm::makeArrayRef(GCCRegNames); + } + + bool validateAsmConstraint(const char *&Name, + TargetInfo::ConstraintInfo &Info) const override { + switch (*Name) { + default: + return false; + + case 'r': // CPU registers. + case 'd': // Equivalent to "r" unless generating MIPS16 code. + case 'y': // Equivalent to "r", backwards compatibility only. + case 'f': // floating-point registers. + case 'c': // $25 for indirect jumps + case 'l': // lo register + case 'x': // hilo register pair + Info.setAllowsRegister(); + return true; + } + } + + const char *getClobbers() const override { return ""; } + + ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override { + static const TargetInfo::GCCRegAlias aliases[] = { + {{"zero"}, "r0"}, {{"at"}, "r1"}, {{"et"}, "r24"}, + {{"bt"}, "r25"}, {{"gp"}, "r26"}, {{"sp"}, "r27"}, + {{"fp"}, "r28"}, {{"ea"}, "r29"}, {{"ba"}, "r30"}, + {{"ra"}, "r31"}, {{"status"}, "ctl0"}, {{"estatus"}, "ctl1"}, + {{"bstatus"}, "ctl2"}, {{"ienable"}, "ctl3"}, {{"ipending"}, "ctl4"}, + {{"cpuid"}, "ctl5"}, {{"exception"}, "ctl7"}, {{"pteaddr"}, "ctl8"}, + {{"tlbacc"}, "ctl9"}, {{"tlbmisc"}, "ctl10"}, {{"badaddr"}, "ctl12"}, + {{"config"}, "ctl13"}, {{"mpubase"}, "ctl14"}, {{"mpuacc"}, "ctl15"}, + }; + return llvm::makeArrayRef(aliases); + } +}; + +const Builtin::Info Nios2TargetInfo::BuiltinInfo[] = { +#define BUILTIN(ID, TYPE, ATTRS) \ + {#ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr}, +#define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE) \ + {#ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, FEATURE}, +#include "clang/Basic/BuiltinsNios2.def" +}; + class MipsTargetInfo : public TargetInfo { void setDataLayout() { StringRef Layout; @@ -9264,6 +9508,8 @@ static TargetInfo *AllocateTarget(const llvm::Triple &Triple, return new NetBSDTargetInfo<AArch64leTargetInfo>(Triple, Opts); case llvm::Triple::OpenBSD: return new OpenBSDTargetInfo<AArch64leTargetInfo>(Triple, Opts); + case llvm::Triple::Win32: + return new MicrosoftARM64TargetInfo(Triple, Opts); default: return new AArch64leTargetInfo(Triple, Opts); } @@ -9353,6 +9599,9 @@ static TargetInfo *AllocateTarget(const llvm::Triple &Triple, case llvm::Triple::msp430: return new MSP430TargetInfo(Triple, Opts); + case llvm::Triple::nios2: + return new LinuxTargetInfo<Nios2TargetInfo>(Triple, Opts); + case llvm::Triple::mips: switch (os) { case llvm::Triple::Linux: diff --git a/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp b/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp index bd01902a032b..9b3850abcce7 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp @@ -54,6 +54,7 @@ #include "llvm/Transforms/ObjCARC.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar/GVN.h" +#include "llvm/Transforms/Utils/NameAnonGlobals.h" #include "llvm/Transforms/Utils/SymbolRewriter.h" #include <memory> using namespace clang; @@ -414,11 +415,7 @@ static void initTargetOptions(llvm::TargetOptions &Options, Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; // Set EABI version. - Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion) - .Case("4", llvm::EABI::EABI4) - .Case("5", llvm::EABI::EABI5) - .Case("gnu", llvm::EABI::GNU) - .Default(llvm::EABI::Default); + Options.EABIVersion = TargetOpts.EABIVersion; if (LangOpts.SjLjExceptions) Options.ExceptionModel = llvm::ExceptionHandling::SjLj; @@ -491,7 +488,6 @@ void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM, PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel; PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; - PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB; PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; @@ -856,11 +852,15 @@ void EmitAssemblyHelper::EmitAssemblyWithNewPassManager( if (CodeGenOpts.hasProfileIRUse()) PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath; + if (!CodeGenOpts.SampleProfileFile.empty()) + PGOOpt.SampleProfileFile = CodeGenOpts.SampleProfileFile; + // Only pass a PGO options struct if -fprofile-generate or // -fprofile-use were passed on the cmdline. PassBuilder PB(TM.get(), (PGOOpt.RunProfileGen || - !PGOOpt.ProfileUseFile.empty()) ? + !PGOOpt.ProfileUseFile.empty() || + !PGOOpt.SampleProfileFile.empty()) ? Optional<PGOOptions>(PGOOpt) : None); LoopAnalysisManager LAM; @@ -878,20 +878,34 @@ void EmitAssemblyHelper::EmitAssemblyWithNewPassManager( PB.registerLoopAnalyses(LAM); PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); - ModulePassManager MPM; + ModulePassManager MPM(CodeGenOpts.DebugPassManager); if (!CodeGenOpts.DisableLLVMPasses) { + bool IsThinLTO = CodeGenOpts.EmitSummaryIndex; + bool IsLTO = CodeGenOpts.PrepareForLTO; + if (CodeGenOpts.OptimizationLevel == 0) { // Build a minimal pipeline based on the semantics required by Clang, // which is just that always inlining occurs. MPM.addPass(AlwaysInlinerPass()); + if (IsThinLTO) + MPM.addPass(NameAnonGlobalPass()); } else { - // Otherwise, use the default pass pipeline. We also have to map our - // optimization levels into one of the distinct levels used to configure - // the pipeline. + // Map our optimization levels into one of the distinct levels used to + // configure the pipeline. PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts); - MPM = PB.buildPerModuleDefaultPipeline(Level); + if (IsThinLTO) { + MPM = PB.buildThinLTOPreLinkDefaultPipeline( + Level, CodeGenOpts.DebugPassManager); + MPM.addPass(NameAnonGlobalPass()); + } else if (IsLTO) { + MPM = PB.buildLTOPreLinkDefaultPipeline(Level, + CodeGenOpts.DebugPassManager); + } else { + MPM = PB.buildPerModuleDefaultPipeline(Level, + CodeGenOpts.DebugPassManager); + } } } diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp index a6451b7fc3c1..2a6e92e7f3ce 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp @@ -9372,6 +9372,16 @@ Value *CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, Value *Callee = CGM.getIntrinsic(Intrinsic::wasm_grow_memory, X->getType()); return Builder.CreateCall(Callee, X); } + case WebAssembly::BI__builtin_wasm_throw: { + Value *Tag = EmitScalarExpr(E->getArg(0)); + Value *Obj = EmitScalarExpr(E->getArg(1)); + Value *Callee = CGM.getIntrinsic(Intrinsic::wasm_throw); + return Builder.CreateCall(Callee, {Tag, Obj}); + } + case WebAssembly::BI__builtin_wasm_rethrow: { + Value *Callee = CGM.getIntrinsic(Intrinsic::wasm_rethrow); + return Builder.CreateCall(Callee); + } default: return nullptr; diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGCall.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGCall.cpp index 38d520a2beb0..13a156c7bbd7 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGCall.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGCall.cpp @@ -1297,7 +1297,7 @@ static void CreateCoercedStore(llvm::Value *Src, // If store is legal, just bitcast the src pointer. if (SrcSize <= DstSize) { - Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy)); + Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy); BuildAggStore(CGF, Src, Dst, DstIsVolatile); } else { // Otherwise do coercion through memory. This is stupid, but @@ -2412,8 +2412,7 @@ void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, Address AddrToStoreInto = Address::invalid(); if (SrcSize <= DstSize) { - AddrToStoreInto = - Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy)); + AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy); } else { AddrToStoreInto = CreateTempAlloca(STy, Alloca.getAlignment(), "coerce"); @@ -3389,6 +3388,14 @@ void CodeGenFunction::EmitCallArgs( unsigned Idx = LeftToRight ? I : E - I - 1; CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx; unsigned InitialArgSize = Args.size(); + // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of + // the argument and parameter match or the objc method is parameterized. + assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || + getContext().hasSameUnqualifiedType((*Arg)->getType(), + ArgTypes[Idx]) || + (isa<ObjCMethodDecl>(AC.getDecl()) && + isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && + "Argument and parameter types don't match"); EmitCallArg(Args, *Arg, ArgTypes[Idx]); // In particular, we depend on it being the last arg in Args, and the // objectsize bits depend on there only being one arg if !LeftToRight. @@ -3449,7 +3456,6 @@ void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, if (const ObjCIndirectCopyRestoreExpr *CRE = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) { assert(getLangOpts().ObjCAutoRefCount); - assert(getContext().hasSameUnqualifiedType(E->getType(), type)); return emitWritebackArg(*this, args, CRE); } diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp index ccd3b8d513b1..4b656ea4a879 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp @@ -1860,6 +1860,10 @@ void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg, lt = Qualifiers::OCL_ExplicitNone; } + // Load objects passed indirectly. + if (Arg.isIndirect() && !ArgVal) + ArgVal = Builder.CreateLoad(DeclPtr); + if (lt == Qualifiers::OCL_Strong) { if (!isConsumed) { if (CGM.getCodeGenOpts().OptimizationLevel == 0) { diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp index 7976c53d9e98..98435fefbd2e 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp @@ -1678,7 +1678,10 @@ struct NullReturnState { /// Complete the null-return operation. It is valid to call this /// regardless of whether 'init' has been called. - RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType, + RValue complete(CodeGenFunction &CGF, + ReturnValueSlot returnSlot, + RValue result, + QualType resultType, const CallArgList &CallArgs, const ObjCMethodDecl *Method) { // If we never had to do a null-check, just use the raw result. @@ -1745,7 +1748,8 @@ struct NullReturnState { // memory or (2) agg values in registers. if (result.isAggregate()) { assert(result.isAggregate() && "null init of non-aggregate result?"); - CGF.EmitNullInitialization(result.getAggregateAddress(), resultType); + if (!returnSlot.isUnused()) + CGF.EmitNullInitialization(result.getAggregateAddress(), resultType); if (contBB) CGF.EmitBlock(contBB); return result; } @@ -2117,11 +2121,11 @@ CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, } } - NullReturnState nullReturn; + bool RequiresNullCheck = false; llvm::Constant *Fn = nullptr; if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) { - if (ReceiverCanBeNull) nullReturn.init(CGF, Arg0); + if (ReceiverCanBeNull) RequiresNullCheck = true; Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper) : ObjCTypes.getSendStretFn(IsSuper); } else if (CGM.ReturnTypeUsesFPRet(ResultType)) { @@ -2134,23 +2138,30 @@ CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, // arm64 uses objc_msgSend for stret methods and yet null receiver check // must be made for it. if (ReceiverCanBeNull && CGM.ReturnTypeUsesSRet(MSI.CallInfo)) - nullReturn.init(CGF, Arg0); + RequiresNullCheck = true; Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper) : ObjCTypes.getSendFn(IsSuper); } + // We don't need to emit a null check to zero out an indirect result if the + // result is ignored. + if (Return.isUnused()) + RequiresNullCheck = false; + // Emit a null-check if there's a consumed argument other than the receiver. - bool RequiresNullCheck = false; - if (ReceiverCanBeNull && CGM.getLangOpts().ObjCAutoRefCount && Method) { + if (!RequiresNullCheck && CGM.getLangOpts().ObjCAutoRefCount && Method) { for (const auto *ParamDecl : Method->parameters()) { if (ParamDecl->hasAttr<NSConsumedAttr>()) { - if (!nullReturn.NullBB) - nullReturn.init(CGF, Arg0); RequiresNullCheck = true; break; } } } + + NullReturnState nullReturn; + if (RequiresNullCheck) { + nullReturn.init(CGF, Arg0); + } llvm::Instruction *CallSite; Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType); @@ -2164,7 +2175,7 @@ CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, llvm::CallSite(CallSite).setDoesNotReturn(); } - return nullReturn.complete(CGF, rvalue, ResultType, CallArgs, + return nullReturn.complete(CGF, Return, rvalue, ResultType, CallArgs, RequiresNullCheck ? Method : nullptr); } @@ -6381,16 +6392,15 @@ llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF, llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName); if (PTGV) return CGF.Builder.CreateAlignedLoad(PTGV, Align); - PTGV = new llvm::GlobalVariable( - CGM.getModule(), - Init->getType(), false, - llvm::GlobalValue::WeakAnyLinkage, - Init, - ProtocolName); + PTGV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false, + llvm::GlobalValue::WeakAnyLinkage, Init, + ProtocolName); PTGV->setSection(GetSectionName("__objc_protorefs", "coalesced,no_dead_strip")); PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); PTGV->setAlignment(Align.getQuantity()); + if (!CGM.getTriple().isOSBinFormatMachO()) + PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolName)); CGM.addCompilerUsedGlobal(PTGV); return CGF.Builder.CreateAlignedLoad(PTGV, Align); } @@ -7074,7 +7084,7 @@ CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF, CGCallee callee(CGCalleeInfo(), calleePtr); RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args); - return nullReturn.complete(CGF, result, resultType, formalArgs, + return nullReturn.complete(CGF, returnSlot, result, resultType, formalArgs, requiresnullCheck ? method : nullptr); } diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.cpp index b5599dad3096..4cfddcb107cb 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.cpp @@ -26,61 +26,27 @@ using namespace clang; using namespace CodeGen; -static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM, - const ObjCInterfaceDecl *OID, - const ObjCImplementationDecl *ID, - const ObjCIvarDecl *Ivar) { - const ObjCInterfaceDecl *Container = Ivar->getContainingInterface(); - - // FIXME: We should eliminate the need to have ObjCImplementationDecl passed - // in here; it should never be necessary because that should be the lexical - // decl context for the ivar. - - // If we know have an implementation (and the ivar is in it) then - // look up in the implementation layout. - const ASTRecordLayout *RL; - if (ID && declaresSameEntity(ID->getClassInterface(), Container)) - RL = &CGM.getContext().getASTObjCImplementationLayout(ID); - else - RL = &CGM.getContext().getASTObjCInterfaceLayout(Container); - - // Compute field index. - // - // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is - // implemented. This should be fixed to get the information from the layout - // directly. - unsigned Index = 0; - - for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin(); - IVD; IVD = IVD->getNextIvar()) { - if (Ivar == IVD) - break; - ++Index; - } - assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!"); - - return RL->getFieldOffset(Index); -} - uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) { - return LookupFieldBitOffset(CGM, OID, nullptr, Ivar) / - CGM.getContext().getCharWidth(); + return CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar) / + CGM.getContext().getCharWidth(); } uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, const ObjCImplementationDecl *OID, const ObjCIvarDecl *Ivar) { - return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / - CGM.getContext().getCharWidth(); + return CGM.getContext().lookupFieldBitOffset(OID->getClassInterface(), OID, + Ivar) / + CGM.getContext().getCharWidth(); } unsigned CGObjCRuntime::ComputeBitfieldBitOffset( CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar) { - return LookupFieldBitOffset(CGM, ID, ID->getImplementation(), Ivar); + return CGM.getContext().lookupFieldBitOffset(ID, ID->getImplementation(), + Ivar); } LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF, @@ -119,7 +85,8 @@ LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF, // Note, there is a subtle invariant here: we can only call this routine on // non-synthesized ivars but we may be called for synthesized ivars. However, // a synthesized ivar can never be a bit-field, so this is safe. - uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, nullptr, Ivar); + uint64_t FieldBitOffset = + CGF.CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar); uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth(); uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign(); uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext()); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp index 8d83255ac139..3df95a4e9b2a 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -5603,7 +5603,7 @@ public: // We have to process the component lists that relate with the same // declaration in a single chunk so that we can generate the map flags // correctly. Therefore, we organize all lists in a map. - llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info; + llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info; // Helper function to fill the information map for the different supported // clauses. @@ -5927,16 +5927,11 @@ emitOffloadingArrays(CodeGenFunction &CGF, for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) { llvm::Value *BPVal = *BasePointers[i]; - if (BPVal->getType()->isPointerTy()) - BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy); - else { - assert(BPVal->getType()->isIntegerTy() && - "If not a pointer, the value type must be an integer."); - BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy); - } llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32( llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), Info.BasePointersArray, 0, i); + BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( + BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0)); Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy)); CGF.Builder.CreateStore(BPVal, BPAddr); @@ -5945,16 +5940,11 @@ emitOffloadingArrays(CodeGenFunction &CGF, Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr)); llvm::Value *PVal = Pointers[i]; - if (PVal->getType()->isPointerTy()) - PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy); - else { - assert(PVal->getType()->isIntegerTy() && - "If not a pointer, the value type must be an integer."); - PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy); - } llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32( llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), Info.PointersArray, 0, i); + P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( + P, PVal->getType()->getPointerTo(/*AddrSpace=*/0)); Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy)); CGF.Builder.CreateStore(PVal, PAddr); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGStmtOpenMP.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGStmtOpenMP.cpp index 77f3c332a12f..493cd627e418 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGStmtOpenMP.cpp @@ -239,21 +239,47 @@ static QualType getCanonicalParamType(ASTContext &C, QualType T) { return C.getCanonicalParamType(T); } -llvm::Function * -CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) { - assert( - CapturedStmtInfo && - "CapturedStmtInfo should be set when generating the captured function"); - const CapturedDecl *CD = S.getCapturedDecl(); - const RecordDecl *RD = S.getCapturedRecordDecl(); +namespace { + /// Contains required data for proper outlined function codegen. + struct FunctionOptions { + /// Captured statement for which the function is generated. + const CapturedStmt *S = nullptr; + /// true if cast to/from UIntPtr is required for variables captured by + /// value. + bool UIntPtrCastRequired = true; + /// true if only casted argumefnts must be registered as local args or VLA + /// sizes. + bool RegisterCastedArgsOnly = false; + /// Name of the generated function. + StringRef FunctionName; + explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired, + bool RegisterCastedArgsOnly, + StringRef FunctionName) + : S(S), UIntPtrCastRequired(UIntPtrCastRequired), + RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly), + FunctionName(FunctionName) {} + }; +} + +static std::pair<llvm::Function *, bool> emitOutlinedFunctionPrologue( + CodeGenFunction &CGF, FunctionArgList &Args, + llvm::DenseMap<const Decl *, std::pair<const VarDecl *, Address>> + &LocalAddrs, + llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> + &VLASizes, + llvm::Value *&CXXThisValue, const FunctionOptions &FO) { + const CapturedDecl *CD = FO.S->getCapturedDecl(); + const RecordDecl *RD = FO.S->getCapturedRecordDecl(); assert(CD->hasBody() && "missing CapturedDecl body"); + CXXThisValue = nullptr; // Build the argument list. + CodeGenModule &CGM = CGF.CGM; ASTContext &Ctx = CGM.getContext(); - FunctionArgList Args; + bool HasUIntPtrArgs = false; Args.append(CD->param_begin(), std::next(CD->param_begin(), CD->getContextParamPosition())); - auto I = S.captures().begin(); + auto I = FO.S->captures().begin(); for (auto *FD : RD->fields()) { QualType ArgType = FD->getType(); IdentifierInfo *II = nullptr; @@ -265,23 +291,24 @@ CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) { // deal with pointers. We can pass in the same way the VLA type sizes to the // outlined function. if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) || - I->capturesVariableArrayType()) - ArgType = Ctx.getUIntPtrType(); + I->capturesVariableArrayType()) { + HasUIntPtrArgs = true; + if (FO.UIntPtrCastRequired) + ArgType = Ctx.getUIntPtrType(); + } if (I->capturesVariable() || I->capturesVariableByCopy()) { CapVar = I->getCapturedVar(); II = CapVar->getIdentifier(); } else if (I->capturesThis()) - II = &getContext().Idents.get("this"); + II = &Ctx.Idents.get("this"); else { assert(I->capturesVariableArrayType()); - II = &getContext().Idents.get("vla"); + II = &Ctx.Idents.get("vla"); } - if (ArgType->isVariablyModifiedType()) { - ArgType = - getCanonicalParamType(getContext(), ArgType.getNonReferenceType()); - } - Args.push_back(ImplicitParamDecl::Create(getContext(), /*DC=*/nullptr, + if (ArgType->isVariablyModifiedType()) + ArgType = getCanonicalParamType(Ctx, ArgType.getNonReferenceType()); + Args.push_back(ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), II, ArgType, ImplicitParamDecl::Other)); ++I; @@ -296,90 +323,166 @@ CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) { CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args); llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); - llvm::Function *F = llvm::Function::Create( - FuncLLVMTy, llvm::GlobalValue::InternalLinkage, - CapturedStmtInfo->getHelperName(), &CGM.getModule()); + llvm::Function *F = + llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage, + FO.FunctionName, &CGM.getModule()); CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); if (CD->isNothrow()) F->addFnAttr(llvm::Attribute::NoUnwind); // Generate the function. - StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(), - CD->getBody()->getLocStart()); + CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(), + CD->getBody()->getLocStart()); unsigned Cnt = CD->getContextParamPosition(); - I = S.captures().begin(); + I = FO.S->captures().begin(); for (auto *FD : RD->fields()) { // If we are capturing a pointer by copy we don't need to do anything, just // use the value that we get from the arguments. if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) { const VarDecl *CurVD = I->getCapturedVar(); - Address LocalAddr = GetAddrOfLocalVar(Args[Cnt]); + Address LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]); // If the variable is a reference we need to materialize it here. if (CurVD->getType()->isReferenceType()) { - Address RefAddr = CreateMemTemp(CurVD->getType(), getPointerAlign(), - ".materialized_ref"); - EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr, /*Volatile=*/false, - CurVD->getType()); + Address RefAddr = CGF.CreateMemTemp( + CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref"); + CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr, + /*Volatile=*/false, CurVD->getType()); LocalAddr = RefAddr; } - setAddrOfLocalVar(CurVD, LocalAddr); + if (!FO.RegisterCastedArgsOnly) + LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}}); ++Cnt; ++I; continue; } LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); - LValue ArgLVal = - MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(), - BaseInfo); + LValue ArgLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(Args[Cnt]), + Args[Cnt]->getType(), BaseInfo); if (FD->hasCapturedVLAType()) { - LValue CastedArgLVal = - MakeAddrLValue(castValueFromUintptr(*this, FD->getType(), - Args[Cnt]->getName(), ArgLVal), - FD->getType(), BaseInfo); + if (FO.UIntPtrCastRequired) { + ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(), + Args[Cnt]->getName(), + ArgLVal), + FD->getType(), BaseInfo); + } auto *ExprArg = - EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal(); + CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal(); auto VAT = FD->getCapturedVLAType(); - VLASizeMap[VAT->getSizeExpr()] = ExprArg; + VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}}); } else if (I->capturesVariable()) { auto *Var = I->getCapturedVar(); QualType VarTy = Var->getType(); Address ArgAddr = ArgLVal.getAddress(); if (!VarTy->isReferenceType()) { if (ArgLVal.getType()->isLValueReferenceType()) { - ArgAddr = EmitLoadOfReference( + ArgAddr = CGF.EmitLoadOfReference( ArgAddr, ArgLVal.getType()->castAs<ReferenceType>()); } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) { assert(ArgLVal.getType()->isPointerType()); - ArgAddr = EmitLoadOfPointer( + ArgAddr = CGF.EmitLoadOfPointer( ArgAddr, ArgLVal.getType()->castAs<PointerType>()); } } - setAddrOfLocalVar( - Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var))); + if (!FO.RegisterCastedArgsOnly) { + LocalAddrs.insert( + {Args[Cnt], + {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}}); + } } else if (I->capturesVariableByCopy()) { assert(!FD->getType()->isAnyPointerType() && "Not expecting a captured pointer."); auto *Var = I->getCapturedVar(); QualType VarTy = Var->getType(); - setAddrOfLocalVar(Var, castValueFromUintptr(*this, FD->getType(), - Args[Cnt]->getName(), ArgLVal, - VarTy->isReferenceType())); + LocalAddrs.insert( + {Args[Cnt], + {Var, + FO.UIntPtrCastRequired + ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(), + ArgLVal, VarTy->isReferenceType()) + : ArgLVal.getAddress()}}); } else { // If 'this' is captured, load it into CXXThisValue. assert(I->capturesThis()); - CXXThisValue = - EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal(); + CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()) + .getScalarVal(); + LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}}); } ++Cnt; ++I; } + return {F, HasUIntPtrArgs}; +} + +llvm::Function * +CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) { + assert( + CapturedStmtInfo && + "CapturedStmtInfo should be set when generating the captured function"); + const CapturedDecl *CD = S.getCapturedDecl(); + // Build the argument list. + bool NeedWrapperFunction = + getDebugInfo() && + CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo; + FunctionArgList Args; + llvm::DenseMap<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs; + llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes; + FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false, + CapturedStmtInfo->getHelperName()); + llvm::Function *F; + bool HasUIntPtrArgs; + std::tie(F, HasUIntPtrArgs) = emitOutlinedFunctionPrologue( + *this, Args, LocalAddrs, VLASizes, CXXThisValue, FO); + for (const auto &LocalAddrPair : LocalAddrs) { + if (LocalAddrPair.second.first) { + setAddrOfLocalVar(LocalAddrPair.second.first, + LocalAddrPair.second.second); + } + } + for (const auto &VLASizePair : VLASizes) + VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second; PGO.assignRegionCounters(GlobalDecl(CD), F); CapturedStmtInfo->EmitBody(*this, CD->getBody()); FinishFunction(CD->getBodyRBrace()); - - return F; + if (!NeedWrapperFunction || !HasUIntPtrArgs) + return F; + + FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true, + /*RegisterCastedArgsOnly=*/true, + ".nondebug_wrapper."); + CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true); + WrapperCGF.disableDebugInfo(); + Args.clear(); + LocalAddrs.clear(); + VLASizes.clear(); + llvm::Function *WrapperF = + emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes, + WrapperCGF.CXXThisValue, WrapperFO).first; + LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); + llvm::SmallVector<llvm::Value *, 4> CallArgs; + for (const auto *Arg : Args) { + llvm::Value *CallArg; + auto I = LocalAddrs.find(Arg); + if (I != LocalAddrs.end()) { + LValue LV = + WrapperCGF.MakeAddrLValue(I->second.second, Arg->getType(), BaseInfo); + CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation()); + } else { + auto EI = VLASizes.find(Arg); + if (EI != VLASizes.end()) + CallArg = EI->second.second; + else { + LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg), + Arg->getType(), BaseInfo); + CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation()); + } + } + CallArgs.emplace_back(CallArg); + } + WrapperCGF.Builder.CreateCall(F, CallArgs); + WrapperCGF.FinishFunction(); + return WrapperF; } //===----------------------------------------------------------------------===// diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp index c7e30fad7575..4f03de55149b 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp @@ -228,7 +228,10 @@ namespace clang { Ctx.getDiagnosticHandler(); void *OldDiagnosticContext = Ctx.getDiagnosticContext(); Ctx.setDiagnosticHandler(DiagnosticHandler, this); - Ctx.setDiagnosticHotnessRequested(CodeGenOpts.DiagnosticsWithHotness); + Ctx.setDiagnosticsHotnessRequested(CodeGenOpts.DiagnosticsWithHotness); + if (CodeGenOpts.DiagnosticsHotnessThreshold != 0) + Ctx.setDiagnosticsHotnessThreshold( + CodeGenOpts.DiagnosticsHotnessThreshold); std::unique_ptr<llvm::tool_output_file> OptRecordFile; if (!CodeGenOpts.OptRecordFile.empty()) { @@ -246,7 +249,7 @@ namespace clang { llvm::make_unique<yaml::Output>(OptRecordFile->os())); if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone) - Ctx.setDiagnosticHotnessRequested(true); + Ctx.setDiagnosticsHotnessRequested(true); } // Link each LinkModule into our module. diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenPGO.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenPGO.cpp index 9e193531d0f6..c3d66c1dabc5 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenPGO.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenPGO.cpp @@ -617,6 +617,9 @@ uint64_t PGOHash::finalize() { void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) { const Decl *D = GD.getDecl(); + if (!D->hasBody()) + return; + bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr(); llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader(); if (!InstrumentRegions && !PGOReader) diff --git a/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp b/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp index 5c13e59a0d73..cf86644fb8cd 100644 --- a/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp @@ -23,10 +23,11 @@ using namespace clang; using namespace llvm::opt; Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain, - InputArgList *_Args, DerivedArgList *_TranslatedArgs) + InputArgList *_Args, DerivedArgList *_TranslatedArgs, + bool ContainsError) : TheDriver(D), DefaultToolChain(_DefaultToolChain), ActiveOffloadMask(0u), Args(_Args), TranslatedArgs(_TranslatedArgs), Redirects(nullptr), - ForDiagnostics(false) { + ForDiagnostics(false), ContainsError(ContainsError) { // The offloading host toolchain is the default tool chain. OrderedOffloadingToolchains.insert( std::make_pair(Action::OFK_Host, &DefaultToolChain)); diff --git a/contrib/llvm/tools/clang/lib/Driver/Driver.cpp b/contrib/llvm/tools/clang/lib/Driver/Driver.cpp index f23975829eaf..faced0697ed9 100644 --- a/contrib/llvm/tools/clang/lib/Driver/Driver.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/Driver.cpp @@ -153,8 +153,10 @@ void Driver::setDriverModeFromOption(StringRef Opt) { Diag(diag::err_drv_unsupported_option_argument) << OptName << Value; } -InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) { +InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings, + bool &ContainsError) { llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); + ContainsError = false; unsigned IncludedFlagsBitmask; unsigned ExcludedFlagsBitmask; @@ -167,27 +169,41 @@ InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) { IncludedFlagsBitmask, ExcludedFlagsBitmask); // Check for missing argument error. - if (MissingArgCount) - Diag(clang::diag::err_drv_missing_argument) + if (MissingArgCount) { + Diag(diag::err_drv_missing_argument) << Args.getArgString(MissingArgIndex) << MissingArgCount; + ContainsError |= + Diags.getDiagnosticLevel(diag::err_drv_missing_argument, + SourceLocation()) > DiagnosticsEngine::Warning; + } // Check for unsupported options. for (const Arg *A : Args) { if (A->getOption().hasFlag(options::Unsupported)) { - Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args); + Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args); + ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt, + SourceLocation()) > + DiagnosticsEngine::Warning; continue; } // Warn about -mcpu= without an argument. if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) { - Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args); + Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args); + ContainsError |= Diags.getDiagnosticLevel( + diag::warn_drv_empty_joined_argument, + SourceLocation()) > DiagnosticsEngine::Warning; } } - for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) - Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl : - diag::err_drv_unknown_argument) - << A->getAsString(Args); + for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) { + auto ID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl + : diag::err_drv_unknown_argument; + + Diags.Report(ID) << A->getAsString(Args); + ContainsError |= Diags.getDiagnosticLevel(ID, SourceLocation()) > + DiagnosticsEngine::Warning; + } return Args; } @@ -600,9 +616,8 @@ Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { // FIXME: This stuff needs to go into the Compilation, not the driver. bool CCCPrintPhases; - InputArgList Args = ParseArgStrings(ArgList.slice(1)); - if (Diags.hasErrorOccurred()) - return nullptr; + bool ContainsError; + InputArgList Args = ParseArgStrings(ArgList.slice(1), ContainsError); // Silence driver warnings if requested Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w)); @@ -692,7 +707,8 @@ Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs)); // The compilation takes ownership of Args. - Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs); + Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs, + ContainsError); if (!HandleImmediateArgs(*C)) return C; diff --git a/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.cpp b/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.cpp index 3a30f2a289b0..7a442c83e158 100644 --- a/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.cpp @@ -32,7 +32,7 @@ enum : SanitizerMask { RequiresPIE = DataFlow, NeedsUnwindTables = Address | Thread | Memory | DataFlow, SupportsCoverage = Address | KernelAddress | Memory | Leak | Undefined | - Integer | Nullability | DataFlow, + Integer | Nullability | DataFlow | Fuzzer, RecoverableByDefault = Undefined | Integer | Nullability, Unrecoverable = Unreachable | Return, LegacyFsanitizeRecoverMask = Undefined | Integer, diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Arch/ARM.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Arch/ARM.cpp index 4eac97620114..8cafd3c74bfb 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Arch/ARM.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Arch/ARM.cpp @@ -392,9 +392,7 @@ void arm::getARMTargetFeatures(const ToolChain &TC, if (B->getOption().matches(options::OPT_mlong_calls)) D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args); } - - CmdArgs.push_back("-backend-option"); - CmdArgs.push_back("-arm-execute-only"); + Features.push_back("+execute-only"); } } } diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Clang.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Clang.cpp index 292cf72b56ca..3731aa83ef06 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Clang.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Clang.cpp @@ -35,6 +35,7 @@ #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" +#include "llvm/Support/TargetParser.h" #include "llvm/Support/YAMLParser.h" #ifdef LLVM_ON_UNIX @@ -129,6 +130,13 @@ forAllAssociatedToolChains(Compilation &C, const JobAction &JA, else if (JA.isDeviceOffloading(Action::OFK_Cuda)) Work(*C.getSingleOffloadToolChain<Action::OFK_Host>()); + if (JA.isHostOffloading(Action::OFK_OpenMP)) { + auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>(); + for (auto II = TCs.first, IE = TCs.second; II != IE; ++II) + Work(*II->second); + } else if (JA.isDeviceOffloading(Action::OFK_OpenMP)) + Work(*C.getSingleOffloadToolChain<Action::OFK_Host>()); + // // TODO: Add support for other offloading programming models here. // @@ -781,15 +789,14 @@ static void addPGOAndCoverageFlags(Compilation &C, const Driver &D, CmdArgs.push_back("-femit-coverage-data"); if (Args.hasFlag(options::OPT_fcoverage_mapping, - options::OPT_fno_coverage_mapping, false) && - !ProfileGenerateArg) - D.Diag(clang::diag::err_drv_argument_only_allowed_with) - << "-fcoverage-mapping" - << "-fprofile-instr-generate"; + options::OPT_fno_coverage_mapping, false)) { + if (!ProfileGenerateArg) + D.Diag(clang::diag::err_drv_argument_only_allowed_with) + << "-fcoverage-mapping" + << "-fprofile-instr-generate"; - if (Args.hasFlag(options::OPT_fcoverage_mapping, - options::OPT_fno_coverage_mapping, false)) CmdArgs.push_back("-fcoverage-mapping"); + } if (C.getArgs().hasArg(options::OPT_c) || C.getArgs().hasArg(options::OPT_S)) { @@ -1309,43 +1316,13 @@ void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args, // FIXME: Support -meabi. // FIXME: Parts of this are duplicated in the backend, unify this somehow. const char *ABIName = nullptr; - if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) { + if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) ABIName = A->getValue(); - } else if (Triple.isOSBinFormatMachO()) { - if (arm::useAAPCSForMachO(Triple)) { - ABIName = "aapcs"; - } else if (Triple.isWatchABI()) { - ABIName = "aapcs16"; - } else { - ABIName = "apcs-gnu"; - } - } else if (Triple.isOSWindows()) { - // FIXME: this is invalid for WindowsCE - ABIName = "aapcs"; - } else { - // Select the default based on the platform. - switch (Triple.getEnvironment()) { - case llvm::Triple::Android: - case llvm::Triple::GNUEABI: - case llvm::Triple::GNUEABIHF: - case llvm::Triple::MuslEABI: - case llvm::Triple::MuslEABIHF: - ABIName = "aapcs-linux"; - break; - case llvm::Triple::EABIHF: - case llvm::Triple::EABI: - ABIName = "aapcs"; - break; - default: - if (Triple.getOS() == llvm::Triple::NetBSD) - ABIName = "apcs-gnu"; - else if (Triple.getOS() == llvm::Triple::OpenBSD) - ABIName = "aapcs-linux"; - else - ABIName = "aapcs"; - break; - } + else { + std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false); + ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data(); } + CmdArgs.push_back("-target-abi"); CmdArgs.push_back(ABIName); @@ -1993,6 +1970,16 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, CmdArgs.push_back(Args.MakeArgString(NormalizedTriple)); } + if (IsOpenMPDevice) { + // We have to pass the triple of the host if compiling for an OpenMP device. + std::string NormalizedTriple = + C.getSingleOffloadToolChain<Action::OFK_Host>() + ->getTriple() + .normalize(); + CmdArgs.push_back("-aux-triple"); + CmdArgs.push_back(Args.MakeArgString(NormalizedTriple)); + } + if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm || Triple.getArch() == llvm::Triple::thumb)) { unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6; @@ -4056,6 +4043,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, options::OPT_fno_diagnostics_show_hotness, false)) CmdArgs.push_back("-fdiagnostics-show-hotness"); + if (const Arg *A = + Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { + std::string Opt = std::string("-fdiagnostics-hotness-threshold=") + A->getValue(); + CmdArgs.push_back(Args.MakeArgString(Opt)); + } + if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) { CmdArgs.push_back("-fdiagnostics-format"); CmdArgs.push_back(A->getValue()); @@ -4140,11 +4133,6 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, options::OPT_fno_slp_vectorize, EnableSLPVec)) CmdArgs.push_back("-vectorize-slp"); - // -fno-slp-vectorize-aggressive is default. - if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive, - options::OPT_fno_slp_vectorize_aggressive, false)) - CmdArgs.push_back("-vectorize-slp-aggressive"); - if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ)) A->render(Args, CmdArgs); @@ -4413,10 +4401,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, // device declarations can be identified. Also, -fopenmp-is-device is passed // along to tell the frontend that it is generating code for a device, so that // only the relevant declarations are emitted. - if (IsOpenMPDevice && Inputs.size() == 2) { + if (IsOpenMPDevice) { CmdArgs.push_back("-fopenmp-is-device"); - CmdArgs.push_back("-fopenmp-host-ir-file-path"); - CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename())); + if (Inputs.size() == 2) { + CmdArgs.push_back("-fopenmp-host-ir-file-path"); + CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename())); + } } // For all the host OpenMP offloading compile jobs we need to pass the targets diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/CommonArgs.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains/CommonArgs.cpp index 5e360f62e21a..e8bb703054de 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/CommonArgs.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/CommonArgs.cpp @@ -215,6 +215,21 @@ static std::string getR600TargetGPU(const ArgList &Args) { return ""; } +static std::string getNios2TargetCPU(const ArgList &Args) { + Arg *A = Args.getLastArg(options::OPT_mcpu_EQ); + if (!A) + A = Args.getLastArg(options::OPT_march_EQ); + + if (!A) + return ""; + + const char *name = A->getValue(); + return llvm::StringSwitch<const char *>(name) + .Case("r1", "nios2r1") + .Case("r2", "nios2r2") + .Default(name); +} + static std::string getLanaiTargetCPU(const ArgList &Args) { if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { return A->getValue(); @@ -267,6 +282,10 @@ std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T, return A->getValue(); return ""; + case llvm::Triple::nios2: { + return getNios2TargetCPU(Args); + } + case llvm::Triple::mips: case llvm::Triple::mipsel: case llvm::Triple::mips64: @@ -598,7 +617,8 @@ bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols); // Inject libfuzzer dependencies. - if (TC.getSanitizerArgs().needsFuzzer()) { + if (TC.getSanitizerArgs().needsFuzzer() + && !Args.hasArg(options::OPT_shared)) { addLibFuzzerRuntime(TC, Args, CmdArgs); } diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/CrossWindows.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains/CrossWindows.cpp index d290c62a056a..7d0c438b1360 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/CrossWindows.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/CrossWindows.cpp @@ -238,8 +238,15 @@ AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, const Driver &D = getDriver(); const std::string &SysRoot = D.SysRoot; - if (DriverArgs.hasArg(options::OPT_nostdlibinc)) + auto AddSystemAfterIncludes = [&]() { + for (const auto &P : DriverArgs.getAllArgValues(options::OPT_isystem_after)) + addSystemInclude(DriverArgs, CC1Args, P); + }; + + if (DriverArgs.hasArg(options::OPT_nostdinc)) { + AddSystemAfterIncludes(); return; + } addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include"); if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { @@ -247,8 +254,7 @@ AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::sys::path::append(ResourceDir, "include"); addSystemInclude(DriverArgs, CC1Args, ResourceDir); } - for (const auto &P : DriverArgs.getAllArgValues(options::OPT_isystem_after)) - addSystemInclude(DriverArgs, CC1Args, P); + AddSystemAfterIncludes(); addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include"); } @@ -258,7 +264,7 @@ AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, const llvm::Triple &Triple = getTriple(); const std::string &SysRoot = getDriver().SysRoot; - if (DriverArgs.hasArg(options::OPT_nostdlibinc) || + if (DriverArgs.hasArg(options::OPT_nostdinc) || DriverArgs.hasArg(options::OPT_nostdincxx)) return; diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Darwin.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Darwin.cpp index e41b50c40b28..7b61095c3ba9 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Darwin.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Darwin.cpp @@ -1053,7 +1053,7 @@ void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args, AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan"); if (Sanitize.needsTsanRt()) AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan"); - if (Sanitize.needsFuzzer()) + if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) AddFuzzerLinkArgs(Args, CmdArgs); if (Sanitize.needsStatsRt()) { StringRef OS = isTargetMacOS() ? "osx" : "iossim"; @@ -1150,6 +1150,17 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { Args.getLastArg(options::OPT_mwatchos_version_min_EQ, options::OPT_mwatchos_simulator_version_min_EQ); + unsigned Major, Minor, Micro; + bool HadExtra; + + // iOS 10 is the maximum deployment target for 32-bit targets. + if (iOSVersion && getTriple().isArch32Bit() && + Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro, + HadExtra) && + Major > 10) + getDriver().Diag(diag::err_invalid_ios_deployment_target) + << iOSVersion->getAsString(Args); + // Add a macro to differentiate between m(iphone|tv|watch)os-version-min=X.Y and // -m(iphone|tv|watch)simulator-version-min=X.Y. if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ) || @@ -1191,6 +1202,14 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { if (char *env = ::getenv("WATCHOS_DEPLOYMENT_TARGET")) WatchOSTarget = env; + // iOS 10 is the maximum deployment target for 32-bit targets. + if (!iOSTarget.empty() && getTriple().isArch32Bit() && + Driver::GetReleaseVersion(iOSTarget.c_str(), Major, Minor, Micro, + HadExtra) && + Major > 10) + getDriver().Diag(diag::err_invalid_ios_deployment_target) + << std::string("IPHONEOS_DEPLOYMENT_TARGET=") + iOSTarget; + // If there is no command-line argument to specify the Target version and // no environment variable defined, see if we can set the default based // on -isysroot. @@ -1308,8 +1327,6 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { llvm_unreachable("Unable to infer Darwin variant"); // Set the tool chain target information. - unsigned Major, Minor, Micro; - bool HadExtra; if (Platform == MacOS) { assert((!iOSVersion && !TvOSVersion && !WatchOSVersion) && "Unknown target platform!"); @@ -1325,6 +1342,13 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100) getDriver().Diag(diag::err_drv_invalid_version_number) << iOSVersion->getAsString(Args); + // iOS 10 is the maximum deployment target for 32-bit targets. If the + // inferred deployment target is iOS 11 or later, set it to 10.99. + if (getTriple().isArch32Bit() && Major >= 11) { + Major = 10; + Minor = 99; + Micro = 99; + } } else if (Platform == TvOS) { if (!Driver::GetReleaseVersion(TvOSVersion->getValue(), Major, Minor, Micro, HadExtra) || HadExtra || @@ -1667,6 +1691,28 @@ void MachO::AddLinkRuntimeLibArgs(const ArgList &Args, AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true); } +bool Darwin::isAlignedAllocationUnavailable() const { + switch (TargetPlatform) { + case MacOS: // Earlier than 10.13. + return TargetVersion < VersionTuple(10U, 13U, 0U); + case IPhoneOS: + case IPhoneOSSimulator: + case TvOS: + case TvOSSimulator: // Earlier than 11.0. + return TargetVersion < VersionTuple(11U, 0U, 0U); + case WatchOS: + case WatchOSSimulator: // Earlier than 4.0. + return TargetVersion < VersionTuple(4U, 0U, 0U); + } + llvm_unreachable("Unsupported platform"); +} + +void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, + llvm::opt::ArgStringList &CC1Args) const { + if (isAlignedAllocationUnavailable()) + CC1Args.push_back("-faligned-alloc-unavailable"); +} + DerivedArgList * Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const { diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Darwin.h b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Darwin.h index 16ed04286ac0..ffcdf9a71a46 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Darwin.h +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Darwin.h @@ -384,6 +384,14 @@ protected: return TargetVersion < VersionTuple(V0, V1, V2); } + /// Return true if c++17 aligned allocation/deallocation functions are not + /// implemented in the c++ standard library of the deployment target we are + /// targeting. + bool isAlignedAllocationUnavailable() const; + + void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, + llvm::opt::ArgStringList &CC1Args) const override; + StringRef getPlatformFamily() const; static StringRef getSDKName(StringRef isysroot); StringRef getOSLibraryNameSuffix() const; diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/MipsLinux.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains/MipsLinux.cpp index 709c396a64b7..b394208336ed 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/MipsLinux.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/MipsLinux.cpp @@ -109,7 +109,7 @@ std::string MipsLLVMToolChain::findLibCxxIncludePath() const { void MipsLLVMToolChain::AddCXXStdlibLibArgs(const ArgList &Args, ArgStringList &CmdArgs) const { assert((GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) && - "Only -lc++ (aka libxx) is suported in this toolchain."); + "Only -lc++ (aka libxx) is supported in this toolchain."); CmdArgs.push_back("-lc++"); CmdArgs.push_back("-lc++abi"); diff --git a/contrib/llvm/tools/clang/lib/Format/ContinuationIndenter.cpp b/contrib/llvm/tools/clang/lib/Format/ContinuationIndenter.cpp index cca773cfe3cb..4197587a74c0 100644 --- a/contrib/llvm/tools/clang/lib/Format/ContinuationIndenter.cpp +++ b/contrib/llvm/tools/clang/lib/Format/ContinuationIndenter.cpp @@ -56,6 +56,8 @@ static bool startsNextParameter(const FormatToken &Current, if (Current.is(TT_CtorInitializerComma) && Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) return true; + if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName)) + return true; return Previous.is(tok::comma) && !Current.isTrailingComment() && ((Previous.isNot(TT_CtorInitializerComma) || Style.BreakConstructorInitializers != @@ -499,6 +501,13 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, } } +static bool lessOpensProtoMessageField(const FormatToken &LessTok, + const LineState &State) { + assert(LessTok.is(tok::less)); + return LessTok.NestingLevel > 0 || + (LessTok.Previous && LessTok.Previous->is(tok::equal)); +} + unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State, bool DryRun) { FormatToken &Current = *State.NextToken; @@ -641,6 +650,9 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State, // before the corresponding } or ]. if (PreviousNonComment && (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || + (Style.Language == FormatStyle::LK_Proto && + PreviousNonComment->is(tok::less) && + lessOpensProtoMessageField(*PreviousNonComment, State)) || (PreviousNonComment->is(TT_TemplateString) && PreviousNonComment->opensScope()))) State.Stack.back().BreakBeforeClosingBrace = true; @@ -682,7 +694,9 @@ unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) { if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block) return Current.NestingLevel == 0 ? State.FirstIndent : State.Stack.back().Indent; - if (Current.isOneOf(tok::r_brace, tok::r_square) && State.Stack.size() > 1) { + if ((Current.isOneOf(tok::r_brace, tok::r_square) || + (Current.is(tok::greater) && Style.Language == FormatStyle::LK_Proto)) && + State.Stack.size() > 1) { if (Current.closesBlockOrBlockTypeList(Style)) return State.Stack[State.Stack.size() - 2].NestedBlockIndent; if (Current.MatchingParen && @@ -1035,7 +1049,9 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, bool BreakBeforeParameter = false; unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall, State.Stack.back().NestedBlockIndent); - if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) { + if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || + (Style.Language == FormatStyle::LK_Proto && Current.is(tok::less) && + lessOpensProtoMessageField(Current, State))) { if (Current.opensBlockOrBlockTypeList(Style)) { NewIndent = Style.IndentWidth + std::min(State.Column, State.Stack.back().NestedBlockIndent); @@ -1047,12 +1063,12 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, Current.MatchingParen->Previous && Current.MatchingParen->Previous->is(tok::comma); AvoidBinPacking = - (Current.is(TT_ArrayInitializerLSquare) && EndsInComma) || - Current.is(TT_DictLiteral) || + EndsInComma || Current.is(TT_DictLiteral) || Style.Language == FormatStyle::LK_Proto || !Style.BinPackArguments || (NextNoComment && NextNoComment->isOneOf(TT_DesignatedInitializerPeriod, TT_DesignatedInitializerLSquare)); + BreakBeforeParameter = EndsInComma; if (Current.ParameterCount > 1) NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1); } else { diff --git a/contrib/llvm/tools/clang/lib/Format/Format.cpp b/contrib/llvm/tools/clang/lib/Format/Format.cpp index 7659d56adf25..bb6781d79517 100644 --- a/contrib/llvm/tools/clang/lib/Format/Format.cpp +++ b/contrib/llvm/tools/clang/lib/Format/Format.cpp @@ -44,7 +44,6 @@ using clang::format::FormatStyle; -LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string) LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory) namespace llvm { @@ -414,7 +413,9 @@ template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> { IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch); IO.mapOptional("BeforeElse", Wrapping.BeforeElse); IO.mapOptional("IndentBraces", Wrapping.IndentBraces); - IO.mapOptional("SplitEmptyFunctionBody", Wrapping.SplitEmptyFunctionBody); + IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction); + IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord); + IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace); } }; @@ -490,7 +491,8 @@ static FormatStyle expandPresets(const FormatStyle &Style) { return Style; FormatStyle Expanded = Style; Expanded.BraceWrapping = {false, false, false, false, false, false, - false, false, false, false, false, true}; + false, false, false, false, false, true, + true, true}; switch (Style.BreakBeforeBraces) { case FormatStyle::BS_Linux: Expanded.BraceWrapping.AfterClass = true; @@ -503,7 +505,8 @@ static FormatStyle expandPresets(const FormatStyle &Style) { Expanded.BraceWrapping.AfterFunction = true; Expanded.BraceWrapping.AfterStruct = true; Expanded.BraceWrapping.AfterUnion = true; - Expanded.BraceWrapping.SplitEmptyFunctionBody = false; + Expanded.BraceWrapping.SplitEmptyFunction = false; + Expanded.BraceWrapping.SplitEmptyRecord = false; break; case FormatStyle::BS_Stroustrup: Expanded.BraceWrapping.AfterFunction = true; @@ -523,7 +526,8 @@ static FormatStyle expandPresets(const FormatStyle &Style) { break; case FormatStyle::BS_GNU: Expanded.BraceWrapping = {true, true, true, true, true, true, - true, true, true, true, true, true}; + true, true, true, true, true, true, + true, true}; break; case FormatStyle::BS_WebKit: Expanded.BraceWrapping.AfterFunction = true; @@ -560,7 +564,8 @@ FormatStyle getLLVMStyle() { LLVMStyle.BreakBeforeTernaryOperators = true; LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach; LLVMStyle.BraceWrapping = {false, false, false, false, false, false, - false, false, false, false, false, true}; + false, false, false, false, false, true, + true, true}; LLVMStyle.BreakAfterJavaFieldAnnotations = false; LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; LLVMStyle.BreakBeforeInheritanceComma = false; @@ -579,9 +584,9 @@ FormatStyle getLLVMStyle() { LLVMStyle.ForEachMacros.push_back("Q_FOREACH"); LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH"); LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2}, - {"^(<|\"(gtest|isl|json)/)", 3}, + {"^(<|\"(gtest|gmock|isl|json)/)", 3}, {".*", 1}}; - LLVMStyle.IncludeIsMainRegex = "$"; + LLVMStyle.IncludeIsMainRegex = "(Test)?$"; LLVMStyle.IndentCaseLabels = false; LLVMStyle.IndentWrappedFunctionNames = false; LLVMStyle.IndentWidth = 2; @@ -1409,7 +1414,7 @@ public: : Style(Style), FileName(FileName) { FileStem = llvm::sys::path::stem(FileName); for (const auto &Category : Style.IncludeCategories) - CategoryRegexs.emplace_back(Category.Regex); + CategoryRegexs.emplace_back(Category.Regex, llvm::Regex::IgnoreCase); IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") || FileName.endswith(".cpp") || FileName.endswith(".c++") || FileName.endswith(".cxx") || FileName.endswith(".m") || @@ -1437,9 +1442,11 @@ private: return false; StringRef HeaderStem = llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1)); - if (FileStem.startswith(HeaderStem)) { + if (FileStem.startswith(HeaderStem) || + FileStem.startswith_lower(HeaderStem)) { llvm::Regex MainIncludeRegex( - (HeaderStem + Style.IncludeIsMainRegex).str()); + (HeaderStem + Style.IncludeIsMainRegex).str(), + llvm::Regex::IgnoreCase); if (MainIncludeRegex.match(FileStem)) return true; } diff --git a/contrib/llvm/tools/clang/lib/Format/FormatToken.h b/contrib/llvm/tools/clang/lib/Format/FormatToken.h index c5bf48cdcc06..0fe91adcd472 100644 --- a/contrib/llvm/tools/clang/lib/Format/FormatToken.h +++ b/contrib/llvm/tools/clang/lib/Format/FormatToken.h @@ -465,7 +465,8 @@ struct FormatToken { return is(TT_ArrayInitializerLSquare) || (is(tok::l_brace) && (BlockKind == BK_Block || is(TT_DictLiteral) || - (!Style.Cpp11BracedListStyle && NestingLevel == 0))); + (!Style.Cpp11BracedListStyle && NestingLevel == 0))) || + (is(tok::less) && Style.Language == FormatStyle::LK_Proto); } /// \brief Same as opensBlockOrBlockTypeList, but for the closing token. @@ -475,6 +476,19 @@ struct FormatToken { return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style); } + /// \brief Return the actual namespace token, if this token starts a namespace + /// block. + const FormatToken *getNamespaceToken() const { + const FormatToken *NamespaceTok = this; + if (is(tok::comment)) + NamespaceTok = NamespaceTok->getNextNonComment(); + // Detect "(inline)? namespace" in the beginning of a line. + if (NamespaceTok && NamespaceTok->is(tok::kw_inline)) + NamespaceTok = NamespaceTok->getNextNonComment(); + return NamespaceTok && NamespaceTok->is(tok::kw_namespace) ? NamespaceTok + : nullptr; + } + private: // Disallow copying. FormatToken(const FormatToken &) = delete; diff --git a/contrib/llvm/tools/clang/lib/Format/NamespaceEndCommentsFixer.cpp b/contrib/llvm/tools/clang/lib/Format/NamespaceEndCommentsFixer.cpp index 1bbb41f757ae..85b70b8c0a76 100644 --- a/contrib/llvm/tools/clang/lib/Format/NamespaceEndCommentsFixer.cpp +++ b/contrib/llvm/tools/clang/lib/Format/NamespaceEndCommentsFixer.cpp @@ -174,7 +174,7 @@ tooling::Replacements NamespaceEndCommentsFixer::analyze( AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames; continue; } - NamespaceName += std::move(AllNamespaceNames); + NamespaceName += AllNamespaceNames; CompactedNamespacesCount = 0; AllNamespaceNames = std::string(); } diff --git a/contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp b/contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp index 505f42ec9a06..d78a37532fe8 100644 --- a/contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp +++ b/contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp @@ -89,7 +89,8 @@ private: continue; } if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) || - (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext)) + (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext && + Style.Language != FormatStyle::LK_Proto)) return false; // If a && or || is found and interpreted as a binary operator, this set // of angles is likely part of something like "a < b && c > d". If the @@ -103,6 +104,14 @@ private: !Line.startsWith(tok::kw_template)) return false; updateParameterCount(Left, CurrentToken); + if (Style.Language == FormatStyle::LK_Proto) { + if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) { + if (CurrentToken->is(tok::colon) || + (CurrentToken->isOneOf(tok::l_brace, tok::less) && + Previous->isNot(tok::colon))) + Previous->Type = TT_SelectorName; + } + } if (!consumeToken()) return false; } @@ -440,7 +449,7 @@ private: if (CurrentToken->isOneOf(tok::r_paren, tok::r_square)) return false; updateParameterCount(Left, CurrentToken); - if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) { + if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) { FormatToken *Previous = CurrentToken->getPreviousNonComment(); if (((CurrentToken->is(tok::colon) && (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) || @@ -1561,8 +1570,10 @@ private: const FormatToken *NextNonComment = Current->getNextNonComment(); if (Current->is(TT_ConditionalExpr)) return prec::Conditional; - if (NextNonComment && NextNonComment->is(tok::colon) && - NextNonComment->is(TT_DictLiteral)) + if (NextNonComment && Current->is(TT_SelectorName) && + (NextNonComment->is(TT_DictLiteral) || + (Style.Language == FormatStyle::LK_Proto && + NextNonComment->is(tok::less)))) return prec::Assignment; if (Current->is(TT_JsComputedPropertyName)) return prec::Assignment; @@ -2549,10 +2560,16 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, // deliberate choice and might have aligned the contents of the string // literal accordingly. Thus, we try keep existing line breaks. return Right.NewlinesBefore > 0; - if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 && - Style.Language == FormatStyle::LK_Proto) - // Don't put enums onto single lines in protocol buffers. + if ((Right.Previous->is(tok::l_brace) || + (Right.Previous->is(tok::less) && + Right.Previous->Previous && + Right.Previous->Previous->is(tok::equal)) + ) && + Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) { + // Don't put enums or option definitions onto single lines in protocol + // buffers. return true; + } if (Right.is(TT_InlineASMBrace)) return Right.HasUnescapedNewline; if (isAllmanBrace(Left) || isAllmanBrace(Right)) diff --git a/contrib/llvm/tools/clang/lib/Format/UnwrappedLineFormatter.cpp b/contrib/llvm/tools/clang/lib/Format/UnwrappedLineFormatter.cpp index 8836c07cac71..2005a2822924 100644 --- a/contrib/llvm/tools/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/contrib/llvm/tools/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -136,10 +136,7 @@ private: bool isNamespaceDeclaration(const AnnotatedLine *Line) { const FormatToken *NamespaceTok = Line->First; - // Detect "(inline)? namespace" in the beginning of a line. - if (NamespaceTok->is(tok::kw_inline)) - NamespaceTok = NamespaceTok->getNextNonComment(); - return NamespaceTok && NamespaceTok->is(tok::kw_namespace); + return NamespaceTok && NamespaceTok->getNamespaceToken(); } bool isEndOfNamespace(const AnnotatedLine *Line, @@ -216,10 +213,31 @@ private: if (TheLine->Last->is(TT_FunctionLBrace) && TheLine->First == TheLine->Last && - !Style.BraceWrapping.SplitEmptyFunctionBody && + !Style.BraceWrapping.SplitEmptyFunction && I[1]->First->is(tok::r_brace)) return tryMergeSimpleBlock(I, E, Limit); + // Handle empty record blocks where the brace has already been wrapped + if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last && + I != AnnotatedLines.begin()) { + bool EmptyBlock = I[1]->First->is(tok::r_brace); + + const FormatToken *Tok = I[-1]->First; + if (Tok && Tok->is(tok::comment)) + Tok = Tok->getNextNonComment(); + + if (Tok && Tok->getNamespaceToken()) + return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock + ? tryMergeSimpleBlock(I, E, Limit) : 0; + + if (Tok && Tok->is(tok::kw_typedef)) + Tok = Tok->getNextNonComment(); + if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union, + Keywords.kw_interface)) + return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock + ? tryMergeSimpleBlock(I, E, Limit) : 0; + } + // FIXME: TheLine->Level != 0 might or might not be the right check to do. // If necessary, change to something smarter. bool MergeShortFunctions = diff --git a/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.cpp b/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.cpp index f7678bb6b2a5..ba3a4c17ee12 100644 --- a/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.cpp +++ b/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.cpp @@ -1176,9 +1176,12 @@ void UnwrappedLineParser::parseStructuralElement() { } nextToken(); - if (FormatTok->Tok.is(tok::l_brace)) { + if (FormatTok->Tok.is(tok::l_brace)) parseBracedList(); - } + else if (Style.Language == FormatStyle::LK_Proto && + FormatTok->Tok.is(tok::less)) + parseBracedList(/*ContinueOnSemicolons=*/false, + /*ClosingBraceKind=*/tok::greater); break; case tok::l_square: parseSquare(); @@ -1346,7 +1349,8 @@ bool UnwrappedLineParser::tryToParseBracedList() { return true; } -bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) { +bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons, + tok::TokenKind ClosingBraceKind) { bool HasError = false; nextToken(); @@ -1375,6 +1379,10 @@ bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) { parseChildBlock(); } } + if (FormatTok->Tok.getKind() == ClosingBraceKind) { + nextToken(); + return !HasError; + } switch (FormatTok->Tok.getKind()) { case tok::caret: nextToken(); @@ -1401,9 +1409,6 @@ bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) { FormatTok->BlockKind = BK_BracedInit; parseBracedList(); break; - case tok::r_brace: - nextToken(); - return !HasError; case tok::semi: // JavaScript (or more precisely TypeScript) can have semicolons in braced // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be diff --git a/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.h b/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.h index 15d1d9cda7a2..a2aa2f006728 100644 --- a/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.h +++ b/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.h @@ -93,7 +93,8 @@ private: void readTokenWithJavaScriptASI(); void parseStructuralElement(); bool tryToParseBracedList(); - bool parseBracedList(bool ContinueOnSemicolons = false); + bool parseBracedList(bool ContinueOnSemicolons = false, + tok::TokenKind ClosingBraceKind = tok::r_brace); void parseParens(); void parseSquare(); void parseIfThenElse(); diff --git a/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp b/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp index 986f98ae598b..354527db7bad 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp @@ -44,9 +44,9 @@ void ASTMergeAction::ExecuteAction() { new ForwardingDiagnosticConsumer( *CI.getDiagnostics().getClient()), /*ShouldOwnClient=*/true)); - std::unique_ptr<ASTUnit> Unit = - ASTUnit::LoadFromASTFile(ASTFiles[I], CI.getPCHContainerReader(), - Diags, CI.getFileSystemOpts(), false); + std::unique_ptr<ASTUnit> Unit = ASTUnit::LoadFromASTFile( + ASTFiles[I], CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags, + CI.getFileSystemOpts(), false); if (!Unit) continue; diff --git a/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp b/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp index 1f34f10f55af..1094e6d089a6 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp @@ -458,7 +458,7 @@ namespace { /// a Preprocessor. class ASTInfoCollector : public ASTReaderListener { Preprocessor &PP; - ASTContext &Context; + ASTContext *Context; HeaderSearchOptions &HSOpts; PreprocessorOptions &PPOpts; LangOptions &LangOpt; @@ -468,7 +468,7 @@ class ASTInfoCollector : public ASTReaderListener { bool InitializedLanguage; public: - ASTInfoCollector(Preprocessor &PP, ASTContext &Context, + ASTInfoCollector(Preprocessor &PP, ASTContext *Context, HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts, LangOptions &LangOpt, std::shared_ptr<TargetOptions> &TargetOpts, @@ -536,12 +536,15 @@ private: // Initialize the preprocessor. PP.Initialize(*Target); + if (!Context) + return; + // Initialize the ASTContext - Context.InitBuiltinTypes(*Target); + Context->InitBuiltinTypes(*Target); // We didn't have access to the comment options when the ASTContext was // constructed, so register them now. - Context.getCommentCommandTraits().registerCommentOptions( + Context->getCommentCommandTraits().registerCommentOptions( LangOpt.CommentOpts); } }; @@ -671,7 +674,7 @@ void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags, std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( const std::string &Filename, const PCHContainerReader &PCHContainerRdr, - IntrusiveRefCntPtr<DiagnosticsEngine> Diags, + WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, const FileSystemOptions &FileSystemOpts, bool UseDebugInfo, bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors, @@ -722,21 +725,21 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( /*OwnsHeaderSearch=*/false); Preprocessor &PP = *AST->PP; - AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(), - PP.getIdentifierTable(), PP.getSelectorTable(), - PP.getBuiltinInfo()); - ASTContext &Context = *AST->Ctx; + if (ToLoad >= LoadASTOnly) + AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(), + PP.getIdentifierTable(), PP.getSelectorTable(), + PP.getBuiltinInfo()); bool disableValid = false; if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION")) disableValid = true; - AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { }, + AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, { }, /*isysroot=*/"", /*DisableValidation=*/disableValid, AllowPCHWithCompilerErrors); AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>( - *AST->PP, Context, *AST->HSOpts, *AST->PPOpts, *AST->LangOpts, + *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts, AST->TargetOpts, AST->Target, Counter)); // Attach the AST reader to the AST context as an external AST @@ -744,7 +747,8 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( // AST file as needed. // We need the external source to be set up before we read the AST, because // eagerly-deserialized declarations may use it. - Context.setExternalSource(AST->Reader); + if (AST->Ctx) + AST->Ctx->setExternalSource(AST->Reader); switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile, SourceLocation(), ASTReader::ARR_None)) { @@ -766,15 +770,18 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( PP.setCounterValue(Counter); // Create an AST consumer, even though it isn't used. - AST->Consumer.reset(new ASTConsumer); - + if (ToLoad >= LoadASTOnly) + AST->Consumer.reset(new ASTConsumer); + // Create a semantic analysis object and tell the AST reader about it. - AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer)); - AST->TheSema->Initialize(); - AST->Reader->InitializeSema(*AST->TheSema); + if (ToLoad >= LoadEverything) { + AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer)); + AST->TheSema->Initialize(); + AST->Reader->InitializeSema(*AST->TheSema); + } // Tell the diagnostic client that we have started a source file. - AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP); + AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP); return AST; } @@ -1638,7 +1645,7 @@ ASTUnit *ASTUnit::LoadFromCommandLine( &StoredDiagnostics, nullptr); CI = clang::createInvocationFromCommandLine( - llvm::makeArrayRef(ArgBegin, ArgEnd), Diags); + llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS); if (!CI) return nullptr; } diff --git a/contrib/llvm/tools/clang/lib/Frontend/ChainedIncludesSource.cpp b/contrib/llvm/tools/clang/lib/Frontend/ChainedIncludesSource.cpp index b984c2ed0dd5..534c7587f48d 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/ChainedIncludesSource.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/ChainedIncludesSource.cpp @@ -83,7 +83,7 @@ createASTReader(CompilerInstance &CI, StringRef pchFile, ASTDeserializationListener *deserialListener = nullptr) { Preprocessor &PP = CI.getPreprocessor(); std::unique_ptr<ASTReader> Reader; - Reader.reset(new ASTReader(PP, CI.getASTContext(), + Reader.reset(new ASTReader(PP, &CI.getASTContext(), CI.getPCHContainerReader(), /*Extensions=*/{ }, /*isysroot=*/"", /*DisableValidation=*/true)); diff --git a/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp b/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp index e5da2ae4f22e..bb6a665cb456 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp @@ -517,7 +517,7 @@ IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource( HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader( - PP, Context, PCHContainerRdr, Extensions, + PP, &Context, PCHContainerRdr, Extensions, Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation, AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false, HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex)); @@ -825,8 +825,11 @@ bool CompilerInstance::InitializeSourceManager( const FrontendInputFile &Input, DiagnosticsEngine &Diags, FileManager &FileMgr, SourceManager &SourceMgr, HeaderSearch *HS, DependencyOutputOptions &DepOpts, const FrontendOptions &Opts) { - SrcMgr::CharacteristicKind - Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; + SrcMgr::CharacteristicKind Kind = + Input.getKind().getFormat() == InputKind::ModuleMap + ? Input.isSystem() ? SrcMgr::C_System_ModuleMap + : SrcMgr::C_User_ModuleMap + : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; if (Input.isBuffer()) { SourceMgr.setMainFileID(SourceMgr.createFileID( @@ -933,8 +936,9 @@ bool CompilerInstance::ExecuteAction(FrontendAction &Act) { if (!hasTarget()) return false; - // Create TargetInfo for the other side of CUDA compilation. - if (getLangOpts().CUDA && !getFrontendOpts().AuxTriple.empty()) { + // Create TargetInfo for the other side of CUDA and OpenMP compilation. + if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) && + !getFrontendOpts().AuxTriple.empty()) { auto TO = std::make_shared<TargetOptions>(); TO->Triple = getFrontendOpts().AuxTriple; TO->HostTriple = getTarget().getTriple().str(); @@ -1469,7 +1473,7 @@ void CompilerInstance::createModuleManager() { "Reading modules", *FrontendTimerGroup); ModuleManager = new ASTReader( - getPreprocessor(), getASTContext(), getPCHContainerReader(), + getPreprocessor(), &getASTContext(), getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions, Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation, /*AllowASTWithCompilerErrors=*/false, diff --git a/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp b/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp index 6254b0013bab..00f6b9b46f03 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp @@ -476,6 +476,10 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, OPT_fexperimental_new_pass_manager, OPT_fno_experimental_new_pass_manager, /* Default */ false); + Opts.DebugPassManager = + Args.hasFlag(OPT_fdebug_pass_manager, OPT_fno_debug_pass_manager, + /* Default */ false); + if (Arg *A = Args.getLastArg(OPT_fveclib)) { StringRef Name = A->getValue(); if (Name == "Accelerate") @@ -668,7 +672,6 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.MSVolatile = Args.hasArg(OPT_fms_volatile); - Opts.VectorizeBB = Args.hasArg(OPT_vectorize_slp_aggressive); Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops); Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp); @@ -906,12 +909,18 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.DiagnosticsWithHotness = Args.hasArg(options::OPT_fdiagnostics_show_hotness); bool UsingSampleProfile = !Opts.SampleProfileFile.empty(); + bool UsingProfile = UsingSampleProfile || + (Opts.getProfileUse() != CodeGenOptions::ProfileNone); - if (Opts.DiagnosticsWithHotness && - Opts.getProfileUse() == CodeGenOptions::ProfileNone && - !UsingSampleProfile) { - Diags.Report(diag::warn_drv_fdiagnostics_show_hotness_requires_pgo); - } + if (Opts.DiagnosticsWithHotness && !UsingProfile) + Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) + << "-fdiagnostics-show-hotness"; + + Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value( + Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0); + if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile) + Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) + << "-fdiagnostics-hotness-threshold="; // If the user requested to use a sample profile for PGO, then the // backend will need to track source location information so the profile @@ -2106,6 +2115,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.AlignedAllocation = Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation, Opts.AlignedAllocation); + Opts.AlignedAllocationUnavailable = + Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable); Opts.NewAlignOverride = getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags); if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) { @@ -2557,7 +2568,7 @@ static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value; else - Opts.EABIVersion = Value; + Opts.EABIVersion = EABIVersion; } Opts.CPU = Args.getLastArgValue(OPT_target_cpu); Opts.FPMath = Args.getLastArgValue(OPT_mfpmath); @@ -2644,6 +2655,10 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; } + // Set the triple of the host for OpenMP device compile. + if (LangOpts.OpenMPIsDevice) + Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; + // FIXME: Override value name discarding when asan or msan is used because the // backend passes depend on the name of the alloca in order to print out // names. diff --git a/contrib/llvm/tools/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp b/contrib/llvm/tools/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp index 49d459e78c45..c3ce7ce2b742 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp @@ -31,8 +31,8 @@ using namespace llvm::opt; /// \return A CompilerInvocation, or 0 if none was built for the given /// argument vector. std::unique_ptr<CompilerInvocation> clang::createInvocationFromCommandLine( - ArrayRef<const char *> ArgList, - IntrusiveRefCntPtr<DiagnosticsEngine> Diags) { + ArrayRef<const char *> ArgList, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, + IntrusiveRefCntPtr<vfs::FileSystem> VFS) { if (!Diags.get()) { // No diagnostics engine was provided, so create our own diagnostics object // with the default options. @@ -46,7 +46,7 @@ std::unique_ptr<CompilerInvocation> clang::createInvocationFromCommandLine( // FIXME: We shouldn't have to pass in the path info. driver::Driver TheDriver(Args[0], llvm::sys::getDefaultTargetTriple(), - *Diags); + *Diags, VFS); // Don't check that inputs exist, they may have been remapped. TheDriver.setCheckInputsExist(false); diff --git a/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp b/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp index bd14c53e4d15..561eb9c4a316 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp @@ -55,8 +55,8 @@ struct DepCollectorPPCallbacks : public PPCallbacks { llvm::sys::path::remove_leading_dotslash(FE->getName()); DepCollector.maybeAddDependency(Filename, /*FromModule*/false, - FileType != SrcMgr::C_User, - /*IsModuleFile*/false, /*IsMissing*/false); + isSystem(FileType), + /*IsModuleFile*/false, /*IsMissing*/false); } void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, @@ -265,7 +265,7 @@ bool DFGImpl::FileMatchesDepCriteria(const char *Filename, if (IncludeSystemHeaders) return true; - return FileType == SrcMgr::C_User; + return !isSystem(FileType); } void DFGImpl::FileChanged(SourceLocation Loc, diff --git a/contrib/llvm/tools/clang/lib/Frontend/DiagnosticRenderer.cpp b/contrib/llvm/tools/clang/lib/Frontend/DiagnosticRenderer.cpp index 177feac97441..e3263843e29b 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/DiagnosticRenderer.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/DiagnosticRenderer.cpp @@ -76,20 +76,19 @@ static void mergeFixits(ArrayRef<FixItHint> FixItHints, } } -void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc, +void DiagnosticRenderer::emitDiagnostic(FullSourceLoc Loc, DiagnosticsEngine::Level Level, StringRef Message, ArrayRef<CharSourceRange> Ranges, ArrayRef<FixItHint> FixItHints, - const SourceManager *SM, DiagOrStoredDiag D) { - assert(SM || Loc.isInvalid()); + assert(Loc.hasManager() || Loc.isInvalid()); beginDiagnostic(D, Level); if (!Loc.isValid()) // If we have no source location, just emit the diagnostic message. - emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, SM, D); + emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, D); else { // Get the ranges into a local array we can hack on. SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(), @@ -97,7 +96,7 @@ void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc, SmallVector<FixItHint, 8> MergedFixits; if (!FixItHints.empty()) { - mergeFixits(FixItHints, *SM, LangOpts, MergedFixits); + mergeFixits(FixItHints, Loc.getManager(), LangOpts, MergedFixits); FixItHints = MergedFixits; } @@ -107,25 +106,25 @@ void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc, if (I->RemoveRange.isValid()) MutableRanges.push_back(I->RemoveRange); - SourceLocation UnexpandedLoc = Loc; + FullSourceLoc UnexpandedLoc = Loc; // Find the ultimate expansion location for the diagnostic. - Loc = SM->getFileLoc(Loc); + Loc = Loc.getFileLoc(); - PresumedLoc PLoc = SM->getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc); + PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc); // First, if this diagnostic is not in the main file, print out the // "included from" lines. - emitIncludeStack(Loc, PLoc, Level, *SM); + emitIncludeStack(Loc, PLoc, Level); // Next, emit the actual diagnostic message and caret. - emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, SM, D); - emitCaret(Loc, Level, MutableRanges, FixItHints, *SM); + emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, D); + emitCaret(Loc, Level, MutableRanges, FixItHints); // If this location is within a macro, walk from UnexpandedLoc up to Loc // and produce a macro backtrace. if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) { - emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints, *SM); + emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints); } } @@ -139,15 +138,12 @@ void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc, void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) { emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(), Diag.getRanges(), Diag.getFixIts(), - Diag.getLocation().isValid() ? &Diag.getLocation().getManager() - : nullptr, &Diag); } void DiagnosticRenderer::emitBasicNote(StringRef Message) { - emitDiagnosticMessage( - SourceLocation(), PresumedLoc(), DiagnosticsEngine::Note, Message, - None, nullptr, DiagOrStoredDiag()); + emitDiagnosticMessage(FullSourceLoc(), PresumedLoc(), DiagnosticsEngine::Note, + Message, None, DiagOrStoredDiag()); } /// \brief Prints an include stack when appropriate for a particular @@ -161,12 +157,11 @@ void DiagnosticRenderer::emitBasicNote(StringRef Message) { /// \param Loc The diagnostic location. /// \param PLoc The presumed location of the diagnostic location. /// \param Level The diagnostic level of the message this stack pertains to. -void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc, - PresumedLoc PLoc, - DiagnosticsEngine::Level Level, - const SourceManager &SM) { - SourceLocation IncludeLoc = - PLoc.isInvalid() ? SourceLocation() : PLoc.getIncludeLoc(); +void DiagnosticRenderer::emitIncludeStack(FullSourceLoc Loc, PresumedLoc PLoc, + DiagnosticsEngine::Level Level) { + FullSourceLoc IncludeLoc = + PLoc.isInvalid() ? FullSourceLoc() + : FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager()); // Skip redundant include stacks altogether. if (LastIncludeLoc == IncludeLoc) @@ -178,74 +173,70 @@ void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc, return; if (IncludeLoc.isValid()) - emitIncludeStackRecursively(IncludeLoc, SM); + emitIncludeStackRecursively(IncludeLoc); else { - emitModuleBuildStack(SM); - emitImportStack(Loc, SM); + emitModuleBuildStack(Loc.getManager()); + emitImportStack(Loc); } } /// \brief Helper to recursivly walk up the include stack and print each layer /// on the way back down. -void DiagnosticRenderer::emitIncludeStackRecursively(SourceLocation Loc, - const SourceManager &SM) { +void DiagnosticRenderer::emitIncludeStackRecursively(FullSourceLoc Loc) { if (Loc.isInvalid()) { - emitModuleBuildStack(SM); + emitModuleBuildStack(Loc.getManager()); return; } - - PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc); + + PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc); if (PLoc.isInvalid()) return; // If this source location was imported from a module, print the module // import stack rather than the // FIXME: We want submodule granularity here. - std::pair<SourceLocation, StringRef> Imported = SM.getModuleImportLoc(Loc); + std::pair<FullSourceLoc, StringRef> Imported = Loc.getModuleImportLoc(); if (!Imported.second.empty()) { // This location was imported by a module. Emit the module import stack. - emitImportStackRecursively(Imported.first, Imported.second, SM); + emitImportStackRecursively(Imported.first, Imported.second); return; } // Emit the other include frames first. - emitIncludeStackRecursively(PLoc.getIncludeLoc(), SM); - + emitIncludeStackRecursively( + FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager())); + // Emit the inclusion text/note. - emitIncludeLocation(Loc, PLoc, SM); + emitIncludeLocation(Loc, PLoc); } /// \brief Emit the module import stack associated with the current location. -void DiagnosticRenderer::emitImportStack(SourceLocation Loc, - const SourceManager &SM) { +void DiagnosticRenderer::emitImportStack(FullSourceLoc Loc) { if (Loc.isInvalid()) { - emitModuleBuildStack(SM); + emitModuleBuildStack(Loc.getManager()); return; } - std::pair<SourceLocation, StringRef> NextImportLoc - = SM.getModuleImportLoc(Loc); - emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM); + std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc(); + emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second); } /// \brief Helper to recursivly walk up the import stack and print each layer /// on the way back down. -void DiagnosticRenderer::emitImportStackRecursively(SourceLocation Loc, - StringRef ModuleName, - const SourceManager &SM) { +void DiagnosticRenderer::emitImportStackRecursively(FullSourceLoc Loc, + StringRef ModuleName) { if (ModuleName.empty()) { return; } - PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc); + PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc); // Emit the other import frames first. - std::pair<SourceLocation, StringRef> NextImportLoc - = SM.getModuleImportLoc(Loc); - emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM); + std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc(); + emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second); // Emit the inclusion text/note. - emitImportLocation(Loc, PLoc, ModuleName, SM); + emitImportLocation(Loc, PLoc, ModuleName); } /// \brief Emit the module build stack, for cases where a module is (re-)built @@ -253,13 +244,9 @@ void DiagnosticRenderer::emitImportStackRecursively(SourceLocation Loc, void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) { ModuleBuildStack Stack = SM.getModuleBuildStack(); for (unsigned I = 0, N = Stack.size(); I != N; ++I) { - const SourceManager &CurSM = Stack[I].second.getManager(); - SourceLocation CurLoc = Stack[I].second; - emitBuildingModuleLocation(CurLoc, - CurSM.getPresumedLoc(CurLoc, + emitBuildingModuleLocation(Stack[I].second, Stack[I].second.getPresumedLoc( DiagOpts->ShowPresumedLoc), - Stack[I].first, - CurSM); + Stack[I].first); } } @@ -348,12 +335,12 @@ static void computeCommonMacroArgExpansionFileIDs( // in the same expansion as the caret; otherwise, we crawl to the top of // each chain. Two locations are part of the same macro expansion // iff the FileID is the same. -static void mapDiagnosticRanges( - SourceLocation CaretLoc, - ArrayRef<CharSourceRange> Ranges, - SmallVectorImpl<CharSourceRange> &SpellingRanges, - const SourceManager *SM) { - FileID CaretLocFileID = SM->getFileID(CaretLoc); +static void +mapDiagnosticRanges(FullSourceLoc CaretLoc, ArrayRef<CharSourceRange> Ranges, + SmallVectorImpl<CharSourceRange> &SpellingRanges) { + FileID CaretLocFileID = CaretLoc.getFileID(); + + const SourceManager *SM = &CaretLoc.getManager(); for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { if (I->isInvalid()) continue; @@ -404,42 +391,39 @@ static void mapDiagnosticRanges( } } -void DiagnosticRenderer::emitCaret(SourceLocation Loc, +void DiagnosticRenderer::emitCaret(FullSourceLoc Loc, DiagnosticsEngine::Level Level, ArrayRef<CharSourceRange> Ranges, - ArrayRef<FixItHint> Hints, - const SourceManager &SM) { + ArrayRef<FixItHint> Hints) { SmallVector<CharSourceRange, 4> SpellingRanges; - mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM); - emitCodeContext(Loc, Level, SpellingRanges, Hints, SM); + mapDiagnosticRanges(Loc, Ranges, SpellingRanges); + emitCodeContext(Loc, Level, SpellingRanges, Hints); } /// \brief A helper function for emitMacroExpansion to print the /// macro expansion message void DiagnosticRenderer::emitSingleMacroExpansion( - SourceLocation Loc, - DiagnosticsEngine::Level Level, - ArrayRef<CharSourceRange> Ranges, - const SourceManager &SM) { + FullSourceLoc Loc, DiagnosticsEngine::Level Level, + ArrayRef<CharSourceRange> Ranges) { // Find the spelling location for the macro definition. We must use the // spelling location here to avoid emitting a macro backtrace for the note. - SourceLocation SpellingLoc = SM.getSpellingLoc(Loc); + FullSourceLoc SpellingLoc = Loc.getSpellingLoc(); // Map the ranges into the FileID of the diagnostic location. SmallVector<CharSourceRange, 4> SpellingRanges; - mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM); + mapDiagnosticRanges(Loc, Ranges, SpellingRanges); SmallString<100> MessageStorage; llvm::raw_svector_ostream Message(MessageStorage); - StringRef MacroName = - Lexer::getImmediateMacroNameForDiagnostics(Loc, SM, LangOpts); + StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( + Loc, Loc.getManager(), LangOpts); if (MacroName.empty()) Message << "expanded from here"; else Message << "expanded from macro '" << MacroName << "'"; emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(), - SpellingRanges, None, &SM); + SpellingRanges, None); } /// Check that the macro argument location of Loc starts with ArgumentLoc. @@ -473,13 +457,12 @@ static bool checkRangeForMacroArgExpansion(CharSourceRange Range, /// A helper function to check if the current ranges are all inside the same /// macro argument expansion as Loc. -static bool checkRangesForMacroArgExpansion(SourceLocation Loc, - ArrayRef<CharSourceRange> Ranges, - const SourceManager &SM) { +static bool checkRangesForMacroArgExpansion(FullSourceLoc Loc, + ArrayRef<CharSourceRange> Ranges) { assert(Loc.isMacroID() && "Must be a macro expansion!"); SmallVector<CharSourceRange, 4> SpellingRanges; - mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM); + mapDiagnosticRanges(Loc, Ranges, SpellingRanges); /// Count all valid ranges. unsigned ValidCount = 0; @@ -490,15 +473,15 @@ static bool checkRangesForMacroArgExpansion(SourceLocation Loc, return false; /// To store the source location of the argument location. - SourceLocation ArgumentLoc; + FullSourceLoc ArgumentLoc; /// Set the ArgumentLoc to the beginning location of the expansion of Loc /// so to check if the ranges expands to the same beginning location. - if (!SM.isMacroArgExpansion(Loc,&ArgumentLoc)) + if (!Loc.isMacroArgExpansion(&ArgumentLoc)) return false; for (auto I = SpellingRanges.begin(), E = SpellingRanges.end(); I != E; ++I) { - if (!checkRangeForMacroArgExpansion(*I, SM, ArgumentLoc)) + if (!checkRangeForMacroArgExpansion(*I, Loc.getManager(), ArgumentLoc)) return false; } @@ -516,34 +499,33 @@ static bool checkRangesForMacroArgExpansion(SourceLocation Loc, /// \param Level The diagnostic level currently being emitted. /// \param Ranges The underlined ranges for this code snippet. /// \param Hints The FixIt hints active for this diagnostic. -void DiagnosticRenderer::emitMacroExpansions(SourceLocation Loc, +void DiagnosticRenderer::emitMacroExpansions(FullSourceLoc Loc, DiagnosticsEngine::Level Level, ArrayRef<CharSourceRange> Ranges, - ArrayRef<FixItHint> Hints, - const SourceManager &SM) { + ArrayRef<FixItHint> Hints) { assert(Loc.isValid() && "must have a valid source location here"); // Produce a stack of macro backtraces. - SmallVector<SourceLocation, 8> LocationStack; + SmallVector<FullSourceLoc, 8> LocationStack; unsigned IgnoredEnd = 0; while (Loc.isMacroID()) { // If this is the expansion of a macro argument, point the caret at the // use of the argument in the definition of the macro, not the expansion. - if (SM.isMacroArgExpansion(Loc)) - LocationStack.push_back(SM.getImmediateExpansionRange(Loc).first); + if (Loc.isMacroArgExpansion()) + LocationStack.push_back(Loc.getImmediateExpansionRange().first); else LocationStack.push_back(Loc); - if (checkRangesForMacroArgExpansion(Loc, Ranges, SM)) + if (checkRangesForMacroArgExpansion(Loc, Ranges)) IgnoredEnd = LocationStack.size(); - Loc = SM.getImmediateMacroCallerLoc(Loc); + Loc = Loc.getImmediateMacroCallerLoc(); // Once the location no longer points into a macro, try stepping through // the last found location. This sometimes produces additional useful // backtraces. if (Loc.isFileID()) - Loc = SM.getImmediateMacroCallerLoc(LocationStack.back()); + Loc = LocationStack.back().getImmediateMacroCallerLoc(); assert(Loc.isValid() && "must have a valid source location here"); } @@ -555,7 +537,7 @@ void DiagnosticRenderer::emitMacroExpansions(SourceLocation Loc, if (MacroDepth <= MacroLimit || MacroLimit == 0) { for (auto I = LocationStack.rbegin(), E = LocationStack.rend(); I != E; ++I) - emitSingleMacroExpansion(*I, Level, Ranges, SM); + emitSingleMacroExpansion(*I, Level, Ranges); return; } @@ -565,7 +547,7 @@ void DiagnosticRenderer::emitMacroExpansions(SourceLocation Loc, for (auto I = LocationStack.rbegin(), E = LocationStack.rbegin() + MacroStartMessages; I != E; ++I) - emitSingleMacroExpansion(*I, Level, Ranges, SM); + emitSingleMacroExpansion(*I, Level, Ranges); SmallString<200> MessageStorage; llvm::raw_svector_ostream Message(MessageStorage); @@ -577,26 +559,24 @@ void DiagnosticRenderer::emitMacroExpansions(SourceLocation Loc, for (auto I = LocationStack.rend() - MacroEndMessages, E = LocationStack.rend(); I != E; ++I) - emitSingleMacroExpansion(*I, Level, Ranges, SM); + emitSingleMacroExpansion(*I, Level, Ranges); } DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {} -void DiagnosticNoteRenderer::emitIncludeLocation(SourceLocation Loc, - PresumedLoc PLoc, - const SourceManager &SM) { +void DiagnosticNoteRenderer::emitIncludeLocation(FullSourceLoc Loc, + PresumedLoc PLoc) { // Generate a note indicating the include location. SmallString<200> MessageStorage; llvm::raw_svector_ostream Message(MessageStorage); Message << "in file included from " << PLoc.getFilename() << ':' << PLoc.getLine() << ":"; - emitNote(Loc, Message.str(), &SM); + emitNote(Loc, Message.str()); } -void DiagnosticNoteRenderer::emitImportLocation(SourceLocation Loc, +void DiagnosticNoteRenderer::emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) { + StringRef ModuleName) { // Generate a note indicating the include location. SmallString<200> MessageStorage; llvm::raw_svector_ostream Message(MessageStorage); @@ -605,14 +585,12 @@ void DiagnosticNoteRenderer::emitImportLocation(SourceLocation Loc, Message << "' imported from " << PLoc.getFilename() << ':' << PLoc.getLine(); Message << ":"; - emitNote(Loc, Message.str(), &SM); + emitNote(Loc, Message.str()); } -void -DiagnosticNoteRenderer::emitBuildingModuleLocation(SourceLocation Loc, - PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) { +void DiagnosticNoteRenderer::emitBuildingModuleLocation(FullSourceLoc Loc, + PresumedLoc PLoc, + StringRef ModuleName) { // Generate a note indicating the include location. SmallString<200> MessageStorage; llvm::raw_svector_ostream Message(MessageStorage); @@ -621,5 +599,5 @@ DiagnosticNoteRenderer::emitBuildingModuleLocation(SourceLocation Loc, << PLoc.getFilename() << ':' << PLoc.getLine() << ":"; else Message << "while building module '" << ModuleName << "':"; - emitNote(Loc, Message.str(), &SM); + emitNote(Loc, Message.str()); } diff --git a/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp b/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp index f81a06b31869..704d51509851 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp @@ -200,12 +200,12 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI, /// /// \param CI The compiler instance. /// \param InputFile Populated with the filename from the line marker. -/// \param AddLineNote If \c true, add a line note corresponding to this line -/// directive. Only use this if the directive will not actually be -/// visited by the preprocessor. +/// \param IsModuleMap If \c true, add a line note corresponding to this line +/// directive. (We need to do this because the directive will not be +/// visited by the preprocessor.) static SourceLocation ReadOriginalFileName(CompilerInstance &CI, std::string &InputFile, - bool AddLineNote = false) { + bool IsModuleMap = false) { auto &SourceMgr = CI.getSourceManager(); auto MainFileID = SourceMgr.getMainFileID(); @@ -231,7 +231,7 @@ static SourceLocation ReadOriginalFileName(CompilerInstance &CI, unsigned LineNo; SourceLocation LineNoLoc = T.getLocation(); - if (AddLineNote) { + if (IsModuleMap) { llvm::SmallString<16> Buffer; if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts()) .getAsInteger(10, LineNo)) @@ -250,10 +250,10 @@ static SourceLocation ReadOriginalFileName(CompilerInstance &CI, return SourceLocation(); InputFile = Literal.GetString().str(); - if (AddLineNote) + if (IsModuleMap) CI.getSourceManager().AddLineNote( LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false, - false, SrcMgr::C_User); + false, SrcMgr::C_User_ModuleMap); return T.getLocation(); } @@ -403,7 +403,7 @@ static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem, Offset = 0; if (IsPreprocessed) { SourceLocation EndOfLineMarker = - ReadOriginalFileName(CI, PresumedModuleMapFile, /*AddLineNote*/true); + ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true); if (EndOfLineMarker.isValid()) Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second; } @@ -536,8 +536,8 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false); std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile( - InputFile, CI.getPCHContainerReader(), ASTDiags, CI.getFileSystemOpts(), - CI.getCodeGenOpts().DebugTypeExtRefs); + InputFile, CI.getPCHContainerReader(), ASTUnit::LoadPreprocessorOnly, + ASTDiags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs); if (!AST) goto failure; @@ -547,27 +547,36 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, CI.getPreprocessorOpts() = AST->getPreprocessorOpts(); CI.getLangOpts() = AST->getLangOpts(); - // Preload all the module files loaded transitively by the AST unit. - if (auto ASTReader = AST->getASTReader()) { - auto &MM = ASTReader->getModuleManager(); - for (ModuleFile &MF : MM) - if (&MF != &MM.getPrimaryModule()) - CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName); - } - // FIXME: Preload module maps loaded by the AST unit. - // Set the shared objects, these are reset when we finish processing the // file, otherwise the CompilerInstance will happily destroy them. CI.setFileManager(&AST->getFileManager()); CI.createSourceManager(CI.getFileManager()); CI.getSourceManager().initializeForReplay(AST->getSourceManager()); + // Preload all the module files loaded transitively by the AST unit. Also + // load all module map files that were parsed as part of building the AST + // unit. + if (auto ASTReader = AST->getASTReader()) { + auto &MM = ASTReader->getModuleManager(); + auto &PrimaryModule = MM.getPrimaryModule(); + + for (ModuleFile &MF : MM) + if (&MF != &PrimaryModule) + CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName); + + ASTReader->visitTopLevelModuleMaps(PrimaryModule, + [&](const FileEntry *FE) { + CI.getFrontendOpts().ModuleMapFiles.push_back(FE->getName()); + }); + } + // Set up the input file for replay purposes. auto Kind = AST->getInputKind(); if (Kind.getFormat() == InputKind::ModuleMap) { Module *ASTModule = AST->getPreprocessor().getHeaderSearchInfo().lookupModule( AST->getLangOpts().CurrentModule, /*AllowSearch*/ false); + assert(ASTModule && "module file does not define its own module"); Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind); } else { auto &SM = CI.getSourceManager(); @@ -590,8 +599,8 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics()); std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile( - InputFile, CI.getPCHContainerReader(), Diags, CI.getFileSystemOpts(), - CI.getCodeGenOpts().DebugTypeExtRefs); + InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags, + CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs); if (!AST) goto failure; diff --git a/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp b/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp index 9621889b27ad..0fbcc1c7399e 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp @@ -230,7 +230,7 @@ void VerifyPCHAction::ExecuteAction() { bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot; std::unique_ptr<ASTReader> Reader(new ASTReader( - CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(), + CI.getPreprocessor(), &CI.getASTContext(), CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions, Sysroot.empty() ? "" : Sysroot.c_str(), /*DisableValidation*/ false, diff --git a/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp b/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp index 08befb33c962..71420df00025 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp @@ -1043,7 +1043,7 @@ void clang::InitializePreprocessor( if (InitOpts.UsePredefines) { // FIXME: This will create multiple definitions for most of the predefined // macros. This is not the right way to handle this. - if (LangOpts.CUDA && PP.getAuxTargetInfo()) + if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice) && PP.getAuxTargetInfo()) InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts, Builder); diff --git a/contrib/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp b/contrib/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp index 9b34d4211353..ede12aab6e69 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp @@ -248,7 +248,7 @@ std::error_code ModuleDependencyCollector::copyToRoot(StringRef Src, // Always map a canonical src path to its real path into the YAML, by doing // this we map different virtual src paths to the same entry in the VFS // overlay, which is a way to emulate symlink inside the VFS; this is also - // needed for correctness, not doing that can lead to module redifinition + // needed for correctness, not doing that can lead to module redefinition // errors. addFileMapping(VirtualPath, CacheDst); return std::error_code(); diff --git a/contrib/llvm/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp b/contrib/llvm/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp index b5a5acd8ad9a..7666fe10b381 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp @@ -63,27 +63,20 @@ public: ~SDiagsRenderer() override {} protected: - void emitDiagnosticMessage(SourceLocation Loc, - PresumedLoc PLoc, - DiagnosticsEngine::Level Level, - StringRef Message, + void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc, + DiagnosticsEngine::Level Level, StringRef Message, ArrayRef<CharSourceRange> Ranges, - const SourceManager *SM, DiagOrStoredDiag D) override; - void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, + void emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, - ArrayRef<CharSourceRange> Ranges, - const SourceManager &SM) override {} + ArrayRef<CharSourceRange> Ranges) override {} - void emitNote(SourceLocation Loc, StringRef Message, - const SourceManager *SM) override; + void emitNote(FullSourceLoc Loc, StringRef Message) override; - void emitCodeContext(SourceLocation Loc, - DiagnosticsEngine::Level Level, - SmallVectorImpl<CharSourceRange>& Ranges, - ArrayRef<FixItHint> Hints, - const SourceManager &SM) override; + void emitCodeContext(FullSourceLoc Loc, DiagnosticsEngine::Level Level, + SmallVectorImpl<CharSourceRange> &Ranges, + ArrayRef<FixItHint> Hints) override; void beginDiagnostic(DiagOrStoredDiag D, DiagnosticsEngine::Level Level) override; @@ -193,11 +186,8 @@ private: void ExitDiagBlock(); /// \brief Emit a DIAG record. - void EmitDiagnosticMessage(SourceLocation Loc, - PresumedLoc PLoc, - DiagnosticsEngine::Level Level, - StringRef Message, - const SourceManager *SM, + void EmitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc, + DiagnosticsEngine::Level Level, StringRef Message, DiagOrStoredDiag D); /// \brief Emit FIXIT and SOURCE_RANGE records for a diagnostic. @@ -220,16 +210,14 @@ private: /// \brief Emit (lazily) the file string and retrieved the file identifier. unsigned getEmitFile(const char *Filename); - /// \brief Add SourceLocation information the specified record. - void AddLocToRecord(SourceLocation Loc, const SourceManager *SM, - PresumedLoc PLoc, RecordDataImpl &Record, - unsigned TokSize = 0); + /// \brief Add SourceLocation information the specified record. + void AddLocToRecord(FullSourceLoc Loc, PresumedLoc PLoc, + RecordDataImpl &Record, unsigned TokSize = 0); /// \brief Add SourceLocation information the specified record. - void AddLocToRecord(SourceLocation Loc, RecordDataImpl &Record, - const SourceManager *SM, + void AddLocToRecord(FullSourceLoc Loc, RecordDataImpl &Record, unsigned TokSize = 0) { - AddLocToRecord(Loc, SM, SM ? SM->getPresumedLoc(Loc) : PresumedLoc(), + AddLocToRecord(Loc, Loc.hasManager() ? Loc.getPresumedLoc() : PresumedLoc(), Record, TokSize); } @@ -350,11 +338,8 @@ static void EmitRecordID(unsigned ID, const char *Name, Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record); } -void SDiagsWriter::AddLocToRecord(SourceLocation Loc, - const SourceManager *SM, - PresumedLoc PLoc, - RecordDataImpl &Record, - unsigned TokSize) { +void SDiagsWriter::AddLocToRecord(FullSourceLoc Loc, PresumedLoc PLoc, + RecordDataImpl &Record, unsigned TokSize) { if (PLoc.isInvalid()) { // Emit a "sentinel" location. Record.push_back((unsigned)0); // File. @@ -367,19 +352,19 @@ void SDiagsWriter::AddLocToRecord(SourceLocation Loc, Record.push_back(getEmitFile(PLoc.getFilename())); Record.push_back(PLoc.getLine()); Record.push_back(PLoc.getColumn()+TokSize); - Record.push_back(SM->getFileOffset(Loc)); + Record.push_back(Loc.getFileOffset()); } void SDiagsWriter::AddCharSourceRangeToRecord(CharSourceRange Range, RecordDataImpl &Record, const SourceManager &SM) { - AddLocToRecord(Range.getBegin(), Record, &SM); + AddLocToRecord(FullSourceLoc(Range.getBegin(), SM), Record); unsigned TokSize = 0; if (Range.isTokenRange()) TokSize = Lexer::MeasureTokenLength(Range.getEnd(), SM, *LangOpts); - - AddLocToRecord(Range.getEnd(), Record, &SM, TokSize); + + AddLocToRecord(FullSourceLoc(Range.getEnd(), SM), Record, TokSize); } unsigned SDiagsWriter::getEmitFile(const char *FileName){ @@ -606,8 +591,8 @@ void SDiagsWriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, if (DiagLevel == DiagnosticsEngine::Note) EnterDiagBlock(); - EmitDiagnosticMessage(SourceLocation(), PresumedLoc(), DiagLevel, - State->diagBuf, nullptr, &Info); + EmitDiagnosticMessage(FullSourceLoc(), PresumedLoc(), DiagLevel, + State->diagBuf, &Info); if (DiagLevel == DiagnosticsEngine::Note) ExitDiagBlock(); @@ -618,12 +603,9 @@ void SDiagsWriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, assert(Info.hasSourceManager() && LangOpts && "Unexpected diagnostic with valid location outside of a source file"); SDiagsRenderer Renderer(*this, *LangOpts, &*State->DiagOpts); - Renderer.emitDiagnostic(Info.getLocation(), DiagLevel, - State->diagBuf, - Info.getRanges(), - Info.getFixItHints(), - &Info.getSourceManager(), - &Info); + Renderer.emitDiagnostic( + FullSourceLoc(Info.getLocation(), Info.getSourceManager()), DiagLevel, + State->diagBuf, Info.getRanges(), Info.getFixItHints(), &Info); } static serialized_diags::Level getStableLevel(DiagnosticsEngine::Level Level) { @@ -641,11 +623,9 @@ static serialized_diags::Level getStableLevel(DiagnosticsEngine::Level Level) { llvm_unreachable("invalid diagnostic level"); } -void SDiagsWriter::EmitDiagnosticMessage(SourceLocation Loc, - PresumedLoc PLoc, +void SDiagsWriter::EmitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, StringRef Message, - const SourceManager *SM, DiagOrStoredDiag D) { llvm::BitstreamWriter &Stream = State->Stream; RecordData &Record = State->Record; @@ -655,7 +635,7 @@ void SDiagsWriter::EmitDiagnosticMessage(SourceLocation Loc, Record.clear(); Record.push_back(RECORD_DIAG); Record.push_back(getStableLevel(Level)); - AddLocToRecord(Loc, SM, PLoc, Record); + AddLocToRecord(Loc, PLoc, Record); if (const Diagnostic *Info = D.dyn_cast<const Diagnostic*>()) { // Emit the category string lazily and get the category ID. @@ -672,15 +652,11 @@ void SDiagsWriter::EmitDiagnosticMessage(SourceLocation Loc, Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_DIAG), Record, Message); } -void -SDiagsRenderer::emitDiagnosticMessage(SourceLocation Loc, - PresumedLoc PLoc, - DiagnosticsEngine::Level Level, - StringRef Message, - ArrayRef<clang::CharSourceRange> Ranges, - const SourceManager *SM, - DiagOrStoredDiag D) { - Writer.EmitDiagnosticMessage(Loc, PLoc, Level, Message, SM, D); +void SDiagsRenderer::emitDiagnosticMessage( + FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, + StringRef Message, ArrayRef<clang::CharSourceRange> Ranges, + DiagOrStoredDiag D) { + Writer.EmitDiagnosticMessage(Loc, PLoc, Level, Message, D); } void SDiagsWriter::EnterDiagBlock() { @@ -733,20 +709,18 @@ void SDiagsWriter::EmitCodeContext(SmallVectorImpl<CharSourceRange> &Ranges, } } -void SDiagsRenderer::emitCodeContext(SourceLocation Loc, +void SDiagsRenderer::emitCodeContext(FullSourceLoc Loc, DiagnosticsEngine::Level Level, SmallVectorImpl<CharSourceRange> &Ranges, - ArrayRef<FixItHint> Hints, - const SourceManager &SM) { - Writer.EmitCodeContext(Ranges, Hints, SM); + ArrayRef<FixItHint> Hints) { + Writer.EmitCodeContext(Ranges, Hints, Loc.getManager()); } -void SDiagsRenderer::emitNote(SourceLocation Loc, StringRef Message, - const SourceManager *SM) { +void SDiagsRenderer::emitNote(FullSourceLoc Loc, StringRef Message) { Writer.EnterDiagBlock(); - PresumedLoc PLoc = SM ? SM->getPresumedLoc(Loc) : PresumedLoc(); - Writer.EmitDiagnosticMessage(Loc, PLoc, DiagnosticsEngine::Note, - Message, SM, DiagOrStoredDiag()); + PresumedLoc PLoc = Loc.hasManager() ? Loc.getPresumedLoc() : PresumedLoc(); + Writer.EmitDiagnosticMessage(Loc, PLoc, DiagnosticsEngine::Note, Message, + DiagOrStoredDiag()); Writer.ExitDiagBlock(); } diff --git a/contrib/llvm/tools/clang/lib/Frontend/TextDiagnostic.cpp b/contrib/llvm/tools/clang/lib/Frontend/TextDiagnostic.cpp index a24d5768f558..1e12ea5e597a 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/TextDiagnostic.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/TextDiagnostic.cpp @@ -672,20 +672,16 @@ TextDiagnostic::TextDiagnostic(raw_ostream &OS, TextDiagnostic::~TextDiagnostic() {} -void -TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc, - PresumedLoc PLoc, - DiagnosticsEngine::Level Level, - StringRef Message, - ArrayRef<clang::CharSourceRange> Ranges, - const SourceManager *SM, - DiagOrStoredDiag D) { +void TextDiagnostic::emitDiagnosticMessage( + FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, + StringRef Message, ArrayRef<clang::CharSourceRange> Ranges, + DiagOrStoredDiag D) { uint64_t StartOfLocationInfo = OS.tell(); // Emit the location of this particular diagnostic. if (Loc.isValid()) - emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM); - + emitDiagnosticLoc(Loc, PLoc, Level, Ranges); + if (DiagOpts->ShowColors) OS.resetColor(); @@ -787,17 +783,16 @@ void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) { /// This includes extracting as much location information as is present for /// the diagnostic and printing it, as well as any include stack or source /// ranges necessary. -void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, +void TextDiagnostic::emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, - ArrayRef<CharSourceRange> Ranges, - const SourceManager &SM) { + ArrayRef<CharSourceRange> Ranges) { if (PLoc.isInvalid()) { // At least print the file name if available: - FileID FID = SM.getFileID(Loc); + FileID FID = Loc.getFileID(); if (FID.isValid()) { - const FileEntry* FE = SM.getFileEntryForID(FID); + const FileEntry *FE = Loc.getFileEntry(); if (FE && FE->isValid()) { - emitFilename(FE->getName(), SM); + emitFilename(FE->getName(), Loc.getManager()); if (FE->isInPCH()) OS << " (in PCH)"; OS << ": "; @@ -813,7 +808,7 @@ void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, if (DiagOpts->ShowColors) OS.changeColor(savedColor, true); - emitFilename(PLoc.getFilename(), SM); + emitFilename(PLoc.getFilename(), Loc.getManager()); switch (DiagOpts->getFormat()) { case DiagnosticOptions::Clang: OS << ':' << LineNo; break; case DiagnosticOptions::MSVC: OS << '(' << LineNo; break; @@ -848,8 +843,7 @@ void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, } if (DiagOpts->ShowSourceRanges && !Ranges.empty()) { - FileID CaretFileID = - SM.getFileID(SM.getExpansionLoc(Loc)); + FileID CaretFileID = Loc.getExpansionLoc().getFileID(); bool PrintedRange = false; for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(), @@ -858,8 +852,10 @@ void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, // Ignore invalid ranges. if (!RI->isValid()) continue; - SourceLocation B = SM.getExpansionLoc(RI->getBegin()); - SourceLocation E = SM.getExpansionLoc(RI->getEnd()); + FullSourceLoc B = + FullSourceLoc(RI->getBegin(), Loc.getManager()).getExpansionLoc(); + FullSourceLoc E = + FullSourceLoc(RI->getEnd(), Loc.getManager()).getExpansionLoc(); // If the End location and the start location are the same and are a // macro location, then the range was something that came from a @@ -867,10 +863,12 @@ void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, // best we can do is to highlight the range. If this is a // function-like macro, we'd also like to highlight the arguments. if (B == E && RI->getEnd().isMacroID()) - E = SM.getExpansionRange(RI->getEnd()).second; + E = FullSourceLoc(RI->getEnd(), Loc.getManager()) + .getExpansionRange() + .second; - std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B); - std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E); + std::pair<FileID, unsigned> BInfo = B.getDecomposedLoc(); + std::pair<FileID, unsigned> EInfo = E.getDecomposedLoc(); // If the start or end of the range is in another file, just discard // it. @@ -881,13 +879,10 @@ void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, // tokens. unsigned TokSize = 0; if (RI->isTokenRange()) - TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts); + TokSize = Lexer::MeasureTokenLength(E, E.getManager(), LangOpts); - OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':' - << SM.getColumnNumber(BInfo.first, BInfo.second) << '-' - << SM.getLineNumber(EInfo.first, EInfo.second) << ':' - << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) - << '}'; + OS << '{' << B.getLineNumber() << ':' << B.getColumnNumber() << '-' + << E.getLineNumber() << ':' << (E.getColumnNumber() + TokSize) << '}'; PrintedRange = true; } @@ -897,9 +892,7 @@ void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, OS << ' '; } -void TextDiagnostic::emitIncludeLocation(SourceLocation Loc, - PresumedLoc PLoc, - const SourceManager &SM) { +void TextDiagnostic::emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) { if (DiagOpts->ShowLocation && PLoc.isValid()) OS << "In file included from " << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n"; @@ -907,9 +900,8 @@ void TextDiagnostic::emitIncludeLocation(SourceLocation Loc, OS << "In included file:\n"; } -void TextDiagnostic::emitImportLocation(SourceLocation Loc, PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) { +void TextDiagnostic::emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc, + StringRef ModuleName) { if (DiagOpts->ShowLocation && PLoc.isValid()) OS << "In module '" << ModuleName << "' imported from " << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n"; @@ -917,10 +909,9 @@ void TextDiagnostic::emitImportLocation(SourceLocation Loc, PresumedLoc PLoc, OS << "In module '" << ModuleName << "':\n"; } -void TextDiagnostic::emitBuildingModuleLocation(SourceLocation Loc, +void TextDiagnostic::emitBuildingModuleLocation(FullSourceLoc Loc, PresumedLoc PLoc, - StringRef ModuleName, - const SourceManager &SM) { + StringRef ModuleName) { if (DiagOpts->ShowLocation && PLoc.isValid()) OS << "While building module '" << ModuleName << "' imported from " << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n"; @@ -1134,10 +1125,8 @@ static std::string buildFixItInsertionLine(unsigned LineNo, /// \param Ranges The underlined ranges for this code snippet. /// \param Hints The FixIt hints active for this diagnostic. void TextDiagnostic::emitSnippetAndCaret( - SourceLocation Loc, DiagnosticsEngine::Level Level, - SmallVectorImpl<CharSourceRange>& Ranges, - ArrayRef<FixItHint> Hints, - const SourceManager &SM) { + FullSourceLoc Loc, DiagnosticsEngine::Level Level, + SmallVectorImpl<CharSourceRange> &Ranges, ArrayRef<FixItHint> Hints) { assert(Loc.isValid() && "must have a valid source location here"); assert(Loc.isFileID() && "must have a file location here"); @@ -1154,18 +1143,18 @@ void TextDiagnostic::emitSnippetAndCaret( return; // Decompose the location into a FID/Offset pair. - std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); + std::pair<FileID, unsigned> LocInfo = Loc.getDecomposedLoc(); FileID FID = LocInfo.first; - unsigned CaretFileOffset = LocInfo.second; + const SourceManager &SM = Loc.getManager(); // Get information about the buffer it points into. bool Invalid = false; - StringRef BufData = SM.getBufferData(FID, &Invalid); + StringRef BufData = Loc.getBufferData(&Invalid); if (Invalid) return; - unsigned CaretLineNo = SM.getLineNumber(FID, CaretFileOffset); - unsigned CaretColNo = SM.getColumnNumber(FID, CaretFileOffset); + unsigned CaretLineNo = Loc.getLineNumber(); + unsigned CaretColNo = Loc.getColumnNumber(); // Arbitrarily stop showing snippets when the line is too long. static const size_t MaxLineLengthToPrint = 4096; diff --git a/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticPrinter.cpp b/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticPrinter.cpp index 17646b48e23d..5dd3252d5b1e 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticPrinter.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticPrinter.cpp @@ -150,10 +150,9 @@ void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level, "Unexpected diagnostic with no source manager"); assert(TextDiag && "Unexpected diagnostic outside source file processing"); - TextDiag->emitDiagnostic(Info.getLocation(), Level, DiagMessageStream.str(), - Info.getRanges(), - Info.getFixItHints(), - &Info.getSourceManager()); + TextDiag->emitDiagnostic( + FullSourceLoc(Info.getLocation(), Info.getSourceManager()), Level, + DiagMessageStream.str(), Info.getRanges(), Info.getFixItHints()); OS.flush(); } diff --git a/contrib/llvm/tools/clang/lib/Lex/ModuleMap.cpp b/contrib/llvm/tools/clang/lib/Lex/ModuleMap.cpp index 018d59e5e871..40f78ce25ceb 100644 --- a/contrib/llvm/tools/clang/lib/Lex/ModuleMap.cpp +++ b/contrib/llvm/tools/clang/lib/Lex/ModuleMap.cpp @@ -2710,7 +2710,8 @@ bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem, // If the module map file wasn't already entered, do so now. if (ID.isInvalid()) { - auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User; + auto FileCharacter = + IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap; ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter); } diff --git a/contrib/llvm/tools/clang/lib/Lex/PPMacroExpansion.cpp b/contrib/llvm/tools/clang/lib/Lex/PPMacroExpansion.cpp index a6bfc32e2213..8af9a50cc204 100644 --- a/contrib/llvm/tools/clang/lib/Lex/PPMacroExpansion.cpp +++ b/contrib/llvm/tools/clang/lib/Lex/PPMacroExpansion.cpp @@ -1315,6 +1315,8 @@ static bool HasExtension(const Preprocessor &PP, StringRef Extension) { .Case("cxx_binary_literals", true) .Case("cxx_init_captures", LangOpts.CPlusPlus11) .Case("cxx_variable_templates", LangOpts.CPlusPlus) + // Miscellaneous language extensions + .Case("overloadable_unmarked", true) .Default(false); } diff --git a/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp b/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp index d0ce9fc89583..07054546f42f 100644 --- a/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp +++ b/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp @@ -71,11 +71,18 @@ TypeResult Parser::ParseTypeName(SourceRange *Range, return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); } +/// \brief Normalizes an attribute name by dropping prefixed and suffixed __. +static StringRef normalizeAttrName(StringRef Name) { + if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__")) + return Name.drop_front(2).drop_back(2); + return Name; +} + /// isAttributeLateParsed - Return true if the attribute has arguments that /// require late parsing. static bool isAttributeLateParsed(const IdentifierInfo &II) { #define CLANG_ATTR_LATE_PARSED_LIST - return llvm::StringSwitch<bool>(II.getName()) + return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) #include "clang/Parse/AttrParserStringSwitches.inc" .Default(false); #undef CLANG_ATTR_LATE_PARSED_LIST @@ -200,13 +207,6 @@ void Parser::ParseGNUAttributes(ParsedAttributes &attrs, } } -/// \brief Normalizes an attribute name by dropping prefixed and suffixed __. -static StringRef normalizeAttrName(StringRef Name) { - if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__")) - Name = Name.drop_front(2).drop_back(2); - return Name; -} - /// \brief Determine whether the given attribute has an identifier argument. static bool attributeHasIdentifierArg(const IdentifierInfo &II) { #define CLANG_ATTR_IDENTIFIER_ARG_LIST @@ -4319,8 +4319,15 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, return; } - if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) - ParseEnumBody(StartLoc, TagDecl); + if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { + Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl; + ParseEnumBody(StartLoc, D); + if (SkipBody.CheckSameAsPrevious && + !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) { + DS.SetTypeSpecError(); + return; + } + } if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, @@ -4392,11 +4399,9 @@ void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { } // Install the enumerator constant into EnumDecl. - Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, - LastEnumConstDecl, - IdentLoc, Ident, - attrs.getList(), EqualLoc, - AssignedVal.get()); + Decl *EnumConstDecl = Actions.ActOnEnumConstant( + getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, + attrs.getList(), EqualLoc, AssignedVal.get()); EnumAvailabilityDiags.back().done(); EnumConstantDecls.push_back(EnumConstDecl); diff --git a/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp b/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp index a724fa242268..2301284b7f43 100644 --- a/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp +++ b/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp @@ -1910,12 +1910,22 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, else if (getLangOpts().CPlusPlus) ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType, TagOrTempResult.get()); - else - ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); + else { + Decl *D = + SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get(); + // Parse the definition body. + ParseStructUnionBody(StartLoc, TagType, D); + if (SkipBody.CheckSameAsPrevious && + !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(), + SkipBody)) { + DS.SetTypeSpecError(); + return; + } + } } if (!TagOrTempResult.isInvalid()) - // Delayed proccessing of attributes. + // Delayed processing of attributes. Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList()); const char *PrevSpec = nullptr; diff --git a/contrib/llvm/tools/clang/lib/Sema/AnalysisBasedWarnings.cpp b/contrib/llvm/tools/clang/lib/Sema/AnalysisBasedWarnings.cpp index 934e13e72d05..fd2d07957c2b 100644 --- a/contrib/llvm/tools/clang/lib/Sema/AnalysisBasedWarnings.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/AnalysisBasedWarnings.cpp @@ -305,10 +305,14 @@ static bool isThrowCaught(const CXXThrowExpr *Throw, CaughtType = CaughtType->castAs<ReferenceType>() ->getPointeeType() ->getUnqualifiedDesugaredType(); + if (ThrowType->isPointerType() && CaughtType->isPointerType()) { + ThrowType = ThrowType->getPointeeType()->getUnqualifiedDesugaredType(); + CaughtType = CaughtType->getPointeeType()->getUnqualifiedDesugaredType(); + } if (CaughtType == ThrowType) return true; const CXXRecordDecl *CaughtAsRecordType = - CaughtType->getPointeeCXXRecordDecl(); + CaughtType->getAsCXXRecordDecl(); const CXXRecordDecl *ThrowTypeAsRecordType = ThrowType->getAsCXXRecordDecl(); if (CaughtAsRecordType && ThrowTypeAsRecordType) return ThrowTypeAsRecordType->isDerivedFrom(CaughtAsRecordType); diff --git a/contrib/llvm/tools/clang/lib/Sema/Sema.cpp b/contrib/llvm/tools/clang/lib/Sema/Sema.cpp index 007a5e483e6c..34f5e26be810 100644 --- a/contrib/llvm/tools/clang/lib/Sema/Sema.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/Sema.cpp @@ -1688,7 +1688,8 @@ bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) { QT, OpenCLTypeExtMap); } -bool Sema::checkOpenCLDisabledDecl(const Decl &D, const Expr &E) { - return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), "", +bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) { + IdentifierInfo *FnName = D.getIdentifier(); + return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), FnName, OpenCLDeclExtMap, 1, D.getSourceRange()); } diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp index b794628db738..845c4bf61b7a 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp @@ -6000,6 +6000,7 @@ shouldNotPrintDirectly(const ASTContext &Context, while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { StringRef Name = UserTy->getDecl()->getName(); QualType CastTy = llvm::StringSwitch<QualType>(Name) + .Case("CFIndex", Context.LongTy) .Case("NSInteger", Context.LongTy) .Case("NSUInteger", Context.UnsignedLongTy) .Case("SInt32", Context.IntTy) @@ -9935,6 +9936,28 @@ void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { ::CheckBoolLikeConversion(*this, E, CC); } +/// Diagnose when expression is an integer constant expression and its evaluation +/// results in integer overflow +void Sema::CheckForIntOverflow (Expr *E) { + // Use a work list to deal with nested struct initializers. + SmallVector<Expr *, 2> Exprs(1, E); + + do { + Expr *E = Exprs.pop_back_val(); + + if (isa<BinaryOperator>(E->IgnoreParenCasts())) { + E->IgnoreParenCasts()->EvaluateForOverflow(Context); + continue; + } + + if (auto InitList = dyn_cast<InitListExpr>(E)) + Exprs.append(InitList->inits().begin(), InitList->inits().end()); + + if (isa<ObjCBoxedExpr>(E)) + E->IgnoreParenCasts()->EvaluateForOverflow(Context); + } while (!Exprs.empty()); +} + namespace { /// \brief Visitor for expressions which looks for unsequenced operations on the /// same object. @@ -10436,7 +10459,7 @@ void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, if (!E->isInstantiationDependent()) CheckUnsequencedOperations(E); if (!IsConstexpr && !E->isValueDependent()) - E->EvaluateForOverflow(Context); + CheckForIntOverflow(E); DiagnoseMisalignedMembers(); } diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp index e340456bc6da..ef8a408f90de 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp @@ -1327,15 +1327,17 @@ void Sema::ActOnExitFunctionContext() { /// overloaded function declaration or has the "overloadable" /// attribute. static bool AllowOverloadingOfFunction(LookupResult &Previous, - ASTContext &Context) { + ASTContext &Context, + const FunctionDecl *New) { if (Context.getLangOpts().CPlusPlus) return true; if (Previous.getResultKind() == LookupResult::FoundOverloaded) return true; - return (Previous.getResultKind() == LookupResult::Found - && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); + return Previous.getResultKind() == LookupResult::Found && + (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || + New->hasAttr<OverloadableAttr>()); } /// Add this decl to the scope shadowed decl chains. @@ -2933,6 +2935,41 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, New->dropAttr<InternalLinkageAttr>(); } + if (!getLangOpts().CPlusPlus) { + bool OldOvl = Old->hasAttr<OverloadableAttr>(); + if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { + Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) + << New << OldOvl; + + // Try our best to find a decl that actually has the overloadable + // attribute for the note. In most cases (e.g. programs with only one + // broken declaration/definition), this won't matter. + // + // FIXME: We could do this if we juggled some extra state in + // OverloadableAttr, rather than just removing it. + const Decl *DiagOld = Old; + if (OldOvl) { + auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { + const auto *A = D->getAttr<OverloadableAttr>(); + return A && !A->isImplicit(); + }); + // If we've implicitly added *all* of the overloadable attrs to this + // chain, emitting a "previous redecl" note is pointless. + DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; + } + + if (DiagOld) + Diag(DiagOld->getLocation(), + diag::note_attribute_overloadable_prev_overload) + << OldOvl; + + if (OldOvl) + New->addAttr(OverloadableAttr::CreateImplicit(Context)); + else + New->dropAttr<OverloadableAttr>(); + } + } + // If a function is first declared with a calling convention, but is later // declared or defined without one, all following decls assume the calling // convention of the first. @@ -9179,6 +9216,7 @@ bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, bool Redeclaration = false; NamedDecl *OldDecl = nullptr; + bool MayNeedOverloadableChecks = false; // Merge or overload the declaration with an existing declaration of // the same name, if appropriate. @@ -9187,13 +9225,14 @@ bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, // a declaration that requires merging. If it's an overload, // there's no more work to do here; we'll just add the new // function to the scope. - if (!AllowOverloadingOfFunction(Previous, Context)) { + if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { NamedDecl *Candidate = Previous.getRepresentativeDecl(); if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { Redeclaration = true; OldDecl = Candidate; } } else { + MayNeedOverloadableChecks = true; switch (CheckOverload(S, NewFD, Previous, OldDecl, /*NewIsUsingDecl*/ false)) { case Ovl_Match: @@ -9208,18 +9247,6 @@ bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, Redeclaration = false; break; } - - if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { - // If a function name is overloadable in C, then every function - // with that name must be marked "overloadable". - Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) - << Redeclaration << NewFD; - NamedDecl *OverloadedDecl = - Redeclaration ? OldDecl : Previous.getRepresentativeDecl(); - Diag(OverloadedDecl->getLocation(), - diag::note_attribute_overloadable_prev_overload); - NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); - } } } @@ -9234,15 +9261,10 @@ bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, MergeTypeWithPrevious = false; // ... except in the presence of __attribute__((overloadable)). - if (OldDecl->hasAttr<OverloadableAttr>()) { - if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { - Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) - << Redeclaration << NewFD; - Diag(Previous.getFoundDecl()->getLocation(), - diag::note_attribute_overloadable_prev_overload); - NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); - } + if (OldDecl->hasAttr<OverloadableAttr>() || + NewFD->hasAttr<OverloadableAttr>()) { if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { + MayNeedOverloadableChecks = true; Redeclaration = false; OldDecl = nullptr; } @@ -9337,6 +9359,29 @@ bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, NewFD->setAccess(OldDecl->getAccess()); } } + } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && + !NewFD->getAttr<OverloadableAttr>()) { + assert((Previous.empty() || + llvm::any_of(Previous, + [](const NamedDecl *ND) { + return ND->hasAttr<OverloadableAttr>(); + })) && + "Non-redecls shouldn't happen without overloadable present"); + + auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { + const auto *FD = dyn_cast<FunctionDecl>(ND); + return FD && !FD->hasAttr<OverloadableAttr>(); + }); + + if (OtherUnmarkedIter != Previous.end()) { + Diag(NewFD->getLocation(), + diag::err_attribute_overloadable_multiple_unmarked_overloads); + Diag((*OtherUnmarkedIter)->getLocation(), + diag::note_attribute_overloadable_prev_overload) + << false; + + NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); + } } // Semantic checking for this function declaration (in isolation). @@ -11100,9 +11145,7 @@ void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { bool IsGlobal = GlobalStorage && !var->isStaticLocal(); QualType baseType = Context.getBaseElementType(type); - if (!var->getDeclContext()->isDependentContext() && - Init && !Init->isValueDependent()) { - + if (Init && !Init->isValueDependent()) { if (var->isConstexpr()) { SmallVector<PartialDiagnosticAt, 8> Notes; if (!var->evaluateValue(Notes) || !var->isInitICE()) { @@ -11932,7 +11975,7 @@ Sema::CheckForFunctionRedefinition(FunctionDecl *FD, if (canRedefineFunction(Definition, getLangOpts())) return; - // Don't emit an error when this is redifinition of a typo-corrected + // Don't emit an error when this is redefinition of a typo-corrected // definition. if (TypoCorrectedFunctionDefinitions.count(Definition)) return; @@ -13190,6 +13233,55 @@ Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, if (TUK == TUK_Friend || TUK == TUK_Reference) Redecl = NotForRedeclaration; + /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C + /// implemented asks for structural equivalence checking, the returned decl + /// here is passed back to the parser, allowing the tag body to be parsed. + auto createTagFromNewDecl = [&]() -> TagDecl * { + assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); + // If there is an identifier, use the location of the identifier as the + // location of the decl, otherwise use the location of the struct/union + // keyword. + SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; + TagDecl *New = nullptr; + + if (Kind == TTK_Enum) { + New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, + ScopedEnum, ScopedEnumUsesClassTag, + !EnumUnderlying.isNull()); + // If this is an undefined enum, bail. + if (TUK != TUK_Definition && !Invalid) + return nullptr; + if (EnumUnderlying) { + EnumDecl *ED = cast<EnumDecl>(New); + if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) + ED->setIntegerTypeSourceInfo(TI); + else + ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); + ED->setPromotionType(ED->getIntegerType()); + } + } else { // struct/union + New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, + nullptr); + } + + if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { + // Add alignment attributes if necessary; these attributes are checked + // when the ASTContext lays out the structure. + // + // It is important for implementing the correct semantics that this + // happen here (in ActOnTag). The #pragma pack stack is + // maintained as a result of parser callbacks which can occur at + // many points during the parsing of a struct declaration (because + // the #pragma tokens are effectively skipped over during the + // parsing of the struct). + if (TUK == TUK_Definition) { + AddAlignmentAttributesForRecord(RD); + AddMsStructLayoutForRecord(RD); + } + } + return New; + }; + LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); if (Name && SS.isNotEmpty()) { // We have a nested-name tag ('struct foo::bar'). @@ -13595,16 +13687,28 @@ Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, TSK_ExplicitSpecialization; } + // Note that clang allows ODR-like semantics for ObjC/C, i.e., do + // not keep more that one definition around (merge them). However, + // ensure the decl passes the structural compatibility check in + // C11 6.2.7/1 (or 6.1.2.6/1 in C89). NamedDecl *Hidden = nullptr; - if (SkipBody && getLangOpts().CPlusPlus && - !hasVisibleDefinition(Def, &Hidden)) { + if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { // There is a definition of this tag, but it is not visible. We // explicitly make use of C++'s one definition rule here, and // assume that this definition is identical to the hidden one // we already have. Make the existing definition visible and // use it in place of this one. - SkipBody->ShouldSkip = true; - makeMergedDefinitionVisible(Hidden); + if (!getLangOpts().CPlusPlus) { + // Postpone making the old definition visible until after we + // complete parsing the new one and do the structural + // comparison. + SkipBody->CheckSameAsPrevious = true; + SkipBody->New = createTagFromNewDecl(); + SkipBody->Previous = Hidden; + } else { + SkipBody->ShouldSkip = true; + makeMergedDefinitionVisible(Hidden); + } return Def; } else if (!IsExplicitSpecializationAfterInstantiation) { // A redeclaration in function prototype scope in C isn't @@ -13832,7 +13936,7 @@ CreateNewDecl: // the ASTContext lays out the structure. // // It is important for implementing the correct semantics that this - // happen here (in act on tag decl). The #pragma pack stack is + // happen here (in ActOnTag). The #pragma pack stack is // maintained as a result of parser callbacks which can occur at // many points during the parsing of a struct declaration (because // the #pragma tokens are effectively skipped over during the @@ -13968,6 +14072,16 @@ void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { AddPushedVisibilityAttribute(Tag); } +bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, + SkipBodyInfo &SkipBody) { + if (!hasStructuralCompatLayout(Prev, SkipBody.New)) + return false; + + // Make the previous decl visible. + makeMergedDefinitionVisible(SkipBody.Previous); + return true; +} + Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { assert(isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); @@ -15389,7 +15503,7 @@ Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, // different from T: // - every enumerator of every member of class T that is an unscoped // enumerated type - if (!TheEnumDecl->isScoped()) + if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), DeclarationNameInfo(Id, IdLoc)); diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp index e8503427536d..1929bc539188 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp @@ -6571,7 +6571,7 @@ void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, } } -// Helper for delayed proccessing TransparentUnion attribute. +// Helper for delayed processing TransparentUnion attribute. void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) { for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext()) if (Attr->getKind() == AttributeList::AT_TransparentUnion) { diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaDeclCXX.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaDeclCXX.cpp index 453ece9d9c4d..e9070881afe4 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaDeclCXX.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaDeclCXX.cpp @@ -3778,6 +3778,15 @@ Sema::BuildMemInitializer(Decl *ConstructorD, if (BaseType.isNull()) return true; + TInfo = Context.CreateTypeSourceInfo(BaseType); + DependentNameTypeLoc TL = + TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); + if (!TL.isNull()) { + TL.setNameLoc(IdLoc); + TL.setElaboratedKeywordLoc(SourceLocation()); + TL.setQualifierLoc(SS.getWithLocInContext(Context)); + } + R.clear(); R.setLookupName(MemberOrBase); } diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp index 710ead30790f..a9cf3ec7990b 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp @@ -1646,6 +1646,27 @@ static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, return false; } +// Emit a diagnostic if an aligned allocation/deallocation function that is not +// implemented in the standard library is selected. +static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, + SourceLocation Loc, bool IsDelete, + Sema &S) { + if (!S.getLangOpts().AlignedAllocationUnavailable) + return; + + // Return if there is a definition. + if (FD.isDefined()) + return; + + bool IsAligned = false; + if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) { + S.Diag(Loc, diag::warn_aligned_allocation_unavailable) + << IsDelete << FD.getType().getAsString() + << S.getASTContext().getTargetInfo().getTriple().str(); + S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable); + } +} + ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, @@ -2023,11 +2044,13 @@ Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) return ExprError(); MarkFunctionReferenced(StartLoc, OperatorNew); + diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this); } if (OperatorDelete) { if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) return ExprError(); MarkFunctionReferenced(StartLoc, OperatorDelete); + diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this); } // C++0x [expr.new]p17: @@ -3243,6 +3266,9 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, PDiag(diag::err_access_dtor) << PointeeElem); } } + + diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, + *this); } CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( @@ -4093,15 +4119,9 @@ static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, case UTT_IsStandardLayout: case UTT_IsPOD: case UTT_IsLiteral: - ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); - LLVM_FALLTHROUGH; - - // C++1z [meta.unary.prop]: - // T shall be a complete type, cv void, or an array of unknown bound. - case UTT_IsDestructible: - case UTT_IsNothrowDestructible: - case UTT_IsTriviallyDestructible: - // Per the GCC type traits documentation, the same constraints apply to these. + // Per the GCC type traits documentation, T shall be a complete type, cv void, + // or an array of unknown bound. But GCC actually imposes the same constraints + // as above. case UTT_HasNothrowAssign: case UTT_HasNothrowMoveAssign: case UTT_HasNothrowConstructor: @@ -4113,6 +4133,14 @@ static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, case UTT_HasTrivialCopy: case UTT_HasTrivialDestructor: case UTT_HasVirtualDestructor: + ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); + LLVM_FALLTHROUGH; + + // C++1z [meta.unary.prop]: + // T shall be a complete type, cv void, or an array of unknown bound. + case UTT_IsDestructible: + case UTT_IsNothrowDestructible: + case UTT_IsTriviallyDestructible: if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) return true; diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaOpenMP.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaOpenMP.cpp index 2b7733d2adbd..49da0e499771 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaOpenMP.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaOpenMP.cpp @@ -412,6 +412,30 @@ public: return false; } + /// Do the check specified in \a Check to all component lists at a given level + /// and return true if any issue is found. + bool checkMappableExprComponentListsForDeclAtLevel( + ValueDecl *VD, unsigned Level, + const llvm::function_ref< + bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, + OpenMPClauseKind)> &Check) { + if (isStackEmpty()) + return false; + + auto StartI = Stack.back().first.begin(); + auto EndI = Stack.back().first.end(); + if (std::distance(StartI, EndI) <= (int)Level) + return false; + std::advance(StartI, Level); + + auto MI = StartI->MappedExprComponents.find(VD); + if (MI != StartI->MappedExprComponents.end()) + for (auto &L : MI->second.Components) + if (Check(L, MI->second.Kind)) + return true; + return false; + } + /// Create a new mappable expression component list associated with a given /// declaration and initialize it with the provided list of components. void addMappableExpressionComponents( @@ -994,9 +1018,8 @@ bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { bool IsVariableUsedInMapClause = false; bool IsVariableAssociatedWithSection = false; - DSAStack->checkMappableExprComponentListsForDecl( - D, /*CurrentRegionOnly=*/true, - [&](OMPClauseMappableExprCommon::MappableExprComponentListRef + DSAStack->checkMappableExprComponentListsForDeclAtLevel( + D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef MapExprComponents, OpenMPClauseKind WhereFoundClauseKind) { // Only the map clause information influences how a variable is diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp index 8c8402e75e37..b19dcb2a5099 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp @@ -15,6 +15,7 @@ #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTMutationListener.h" +#include "clang/AST/ASTStructuralEquivalence.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" @@ -7111,6 +7112,20 @@ bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, return false; } +bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { + llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; + if (!Suggested) + return false; + + // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext + // and isolate from other C++ specific checks. + StructuralEquivalenceContext Ctx( + D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, + false /*StrictTypeSpelling*/, true /*Complain*/, + true /*ErrorOnTagTypeMismatch*/); + return Ctx.IsStructurallyEquivalent(D, Suggested); +} + /// \brief Determine whether there is any declaration of \p D that was ever a /// definition (perhaps before module merging) and is currently visible. /// \param D The definition of the entity. diff --git a/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp b/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp index ef2841849ff6..3aee3c04001d 100644 --- a/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp +++ b/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp @@ -856,7 +856,7 @@ static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II, II.isPoisoned() || (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) || II.hasRevertedTokenIDToIdentifier() || - (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) && + (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) && II.getFETokenInfo<void>()); } @@ -1148,7 +1148,7 @@ bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M, void ASTReader::Error(StringRef Msg) const { Error(diag::err_fe_pch_malformed, Msg); - if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() && + if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() && !PP.getHeaderSearchInfo().getModuleCachePath().empty()) { Diag(diag::note_module_cache_path) << PP.getHeaderSearchInfo().getModuleCachePath(); @@ -1391,15 +1391,14 @@ bool ASTReader::ReadSLocEntry(int ID) { const DeclID *FirstDecl = F->FileSortedDecls + Record[6]; unsigned NumFileDecls = Record[7]; - if (NumFileDecls) { + if (NumFileDecls && ContextObj) { assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?"); FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl, NumFileDecls)); } const SrcMgr::ContentCache *ContentCache - = SourceMgr.getOrCreateContentCache(File, - /*isSystemFile=*/FileCharacter != SrcMgr::C_User); + = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter)); if (OverriddenBuffer && !ContentCache->BufferOverridden && ContentCache->ContentsEntry == ContentCache->OrigEntry && !ContentCache->getRawBuffer()) { @@ -1697,9 +1696,9 @@ HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d, HeaderFileInfo HFI; unsigned Flags = *d++; // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp. - HFI.isImport |= (Flags >> 4) & 0x01; - HFI.isPragmaOnce |= (Flags >> 3) & 0x01; - HFI.DirInfo = (Flags >> 1) & 0x03; + HFI.isImport |= (Flags >> 5) & 0x01; + HFI.isPragmaOnce |= (Flags >> 4) & 0x01; + HFI.DirInfo = (Flags >> 1) & 0x07; HFI.IndexHeaderMapHeader = Flags & 0x01; // FIXME: Find a better way to handle this. Maybe just store a // "has been included" flag? @@ -2029,6 +2028,7 @@ ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) { R.StoredTime = static_cast<time_t>(Record[2]); R.Overridden = static_cast<bool>(Record[3]); R.Transient = static_cast<bool>(Record[4]); + R.TopLevelModuleMap = static_cast<bool>(Record[5]); R.Filename = Blob; ResolveImportedPath(F, R.Filename); return R; @@ -2614,10 +2614,11 @@ ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { // contains any declarations lexically within it (which it always does!). // This usually has no cost, since we very rarely need the lookup map for // the translation unit outside C++. - DeclContext *DC = Context.getTranslationUnitDecl(); - if (DC->hasExternalLexicalStorage() && - !getContext().getLangOpts().CPlusPlus) - DC->setMustBuildLookupTable(); + if (ASTContext *Ctx = ContextObj) { + DeclContext *DC = Ctx->getTranslationUnitDecl(); + if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus) + DC->setMustBuildLookupTable(); + } return Success; } @@ -2706,7 +2707,33 @@ ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { // Read and process a record. Record.clear(); StringRef Blob; - switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) { + auto RecordType = + (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob); + + // If we're not loading an AST context, we don't care about most records. + if (!ContextObj) { + switch (RecordType) { + case IDENTIFIER_TABLE: + case IDENTIFIER_OFFSET: + case INTERESTING_IDENTIFIERS: + case STATISTICS: + case PP_CONDITIONAL_STACK: + case PP_COUNTER_VALUE: + case SOURCE_LOCATION_OFFSETS: + case MODULE_OFFSET_MAP: + case SOURCE_MANAGER_LINE_TABLE: + case SOURCE_LOCATION_PRELOADS: + case PPD_ENTITIES_OFFSETS: + case HEADER_SEARCH_TABLE: + case IMPORTED_MODULES: + case MACRO_OFFSET: + break; + default: + continue; + } + } + + switch (RecordType) { default: // Default behavior: ignore. break; @@ -2765,7 +2792,7 @@ ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { } case TU_UPDATE_LEXICAL: { - DeclContext *TU = Context.getTranslationUnitDecl(); + DeclContext *TU = ContextObj->getTranslationUnitDecl(); LexicalContents Contents( reinterpret_cast<const llvm::support::unaligned_uint32_t *>( Blob.data()), @@ -3455,12 +3482,6 @@ ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, unsigned Idx = 0; F.ModuleMapPath = ReadPath(F, Record, Idx); - if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) { - // For an explicitly-loaded module, we don't care whether the original - // module map file exists or matches. - return Success; - } - // Try to resolve ModuleName in the current header search context and // verify that it is found in the same module map file as we saved. If the // top-level AST file is a main file, skip this check because there is no @@ -3667,7 +3688,7 @@ bool ASTReader::loadGlobalIndex() { return false; if (TriedLoadingGlobalIndex || !UseGlobalIndex || - !Context.getLangOpts().Modules) + !PP.getLangOpts().Modules) return true; // Try to load the global index. @@ -3685,7 +3706,7 @@ bool ASTReader::loadGlobalIndex() { } bool ASTReader::isGlobalIndexUnavailable() const { - return Context.getLangOpts().Modules && UseGlobalIndex && + return PP.getLangOpts().Modules && UseGlobalIndex && !hasGlobalIndex() && TriedLoadingGlobalIndex; } @@ -3743,7 +3764,9 @@ ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, Deserializing AnASTFile(this); // Bump the generation number. - unsigned PreviousGeneration = incrementGeneration(Context); + unsigned PreviousGeneration = 0; + if (ContextObj) + PreviousGeneration = incrementGeneration(*ContextObj); unsigned NumModules = ModuleMgr.size(); SmallVector<ImportedModule, 4> Loaded; @@ -3762,7 +3785,7 @@ ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, LoadedSet.insert(IM.Mod); ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet, - Context.getLangOpts().Modules + PP.getLangOpts().Modules ? &PP.getHeaderSearchInfo().getModuleMap() : nullptr); @@ -3858,7 +3881,7 @@ ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc); } - if (!Context.getLangOpts().CPlusPlus || + if (!PP.getLangOpts().CPlusPlus || (Type != MK_ImplicitModule && Type != MK_ExplicitModule && Type != MK_PrebuiltModule)) { // Mark all of the identifiers in the identifier table as being out of date, @@ -3915,7 +3938,8 @@ ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, // Might be unnecessary as use declarations are only used to build the // module itself. - InitializeContext(); + if (ContextObj) + InitializeContext(); if (SemaObj) UpdateSema(); @@ -3937,10 +3961,12 @@ ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, // For any Objective-C class definitions we have already loaded, make sure // that we load any additional categories. - for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { - loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), - ObjCClassesLoaded[I], - PreviousGeneration); + if (ContextObj) { + for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { + loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), + ObjCClassesLoaded[I], + PreviousGeneration); + } } if (PP.getHeaderSearchInfo() @@ -4320,6 +4346,9 @@ ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) { } void ASTReader::InitializeContext() { + assert(ContextObj && "no context to initialize"); + ASTContext &Context = *ContextObj; + // If there's a listener, notify them that we "read" the translation unit. if (DeserializationListener) DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, @@ -5054,8 +5083,8 @@ ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { break; } case SUBMODULE_REQUIRES: { - CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(), - Context.getTargetInfo()); + CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(), + PP.getTargetInfo()); break; } @@ -5081,10 +5110,12 @@ ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { } case SUBMODULE_INITIALIZERS: + if (!ContextObj) + break; SmallVector<uint32_t, 16> Inits; for (auto &ID : Record) Inits.push_back(getGlobalDeclID(F, ID)); - Context.addLazyModuleInitializers(CurrentModule, Inits); + ContextObj->addLazyModuleInitializers(CurrentModule, Inits); break; } } @@ -5705,6 +5736,8 @@ ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) { /// location. It is a helper routine for GetType, which deals with reading type /// IDs. QualType ASTReader::readTypeRecord(unsigned Index) { + assert(ContextObj && "reading type with no AST context"); + ASTContext &Context = *ContextObj; RecordLocation Loc = TypeCursorForIndex(Index); BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; @@ -6561,6 +6594,9 @@ ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record, } QualType ASTReader::GetType(TypeID ID) { + assert(ContextObj && "reading type with no AST context"); + ASTContext &Context = *ContextObj; + unsigned FastQuals = ID & Qualifiers::FastMask; unsigned Index = ID >> Qualifiers::FastWidth; @@ -6892,6 +6928,9 @@ ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) { } CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { + assert(ContextObj && "reading base specifiers with no AST context"); + ASTContext &Context = *ContextObj; + RecordLocation Loc = getLocalBitOffset(Offset); BitstreamCursor &Cursor = Loc.F->DeclsCursor; SavedStreamPosition SavedPosition(Cursor); @@ -7023,8 +7062,9 @@ static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) { } Decl *ASTReader::GetExistingDecl(DeclID ID) { + assert(ContextObj && "reading decl with no AST context"); if (ID < NUM_PREDEF_DECL_IDS) { - Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID); + Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID); if (D) { // Track that we have merged the declaration with ID \p ID into the // pre-existing predefined declaration \p D. @@ -7569,7 +7609,7 @@ IdentifierInfo *ASTReader::get(StringRef Name) { // all interesting declarations, and don't need to use the scope for name // lookups). Perform the lookup in PCH files, though, since we don't build // a complete initial identifier table if we're carrying on from a PCH. - if (Context.getLangOpts().CPlusPlus) { + if (PP.getLangOpts().CPlusPlus) { for (auto F : ModuleMgr.pch_modules()) if (Visitor(*F)) break; @@ -8223,7 +8263,7 @@ ASTReader::getSourceDescriptor(unsigned ID) { return ExternalASTSource::ASTSourceDescriptor(*M); // If there is only a single PCH, return it instead. - // Chained PCH are not suported. + // Chained PCH are not supported. const auto &PCHChain = ModuleMgr.pch_modules(); if (std::distance(std::begin(PCHChain), std::end(PCHChain))) { ModuleFile &MF = ModuleMgr.getPrimaryModule(); @@ -8299,6 +8339,7 @@ ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { DeclarationName ASTReader::ReadDeclarationName(ModuleFile &F, const RecordData &Record, unsigned &Idx) { + ASTContext &Context = getContext(); DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++]; switch (Kind) { case DeclarationName::Identifier: @@ -8389,7 +8430,8 @@ void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info, unsigned NumTPLists = Record[Idx++]; Info.NumTemplParamLists = NumTPLists; if (NumTPLists) { - Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists]; + Info.TemplParamLists = + new (getContext()) TemplateParameterList *[NumTPLists]; for (unsigned i = 0; i != NumTPLists; ++i) Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx); } @@ -8398,6 +8440,7 @@ void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info, TemplateName ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record, unsigned &Idx) { + ASTContext &Context = getContext(); TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++]; switch (Kind) { case TemplateName::Template: @@ -8458,6 +8501,7 @@ TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F, const RecordData &Record, unsigned &Idx, bool Canonicalize) { + ASTContext &Context = getContext(); if (Canonicalize) { // The caller wants a canonical template argument. Sometimes the AST only // wants template arguments in canonical form (particularly as the template @@ -8521,9 +8565,8 @@ ASTReader::ReadTemplateParameterList(ModuleFile &F, Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx)); // TODO: Concepts - TemplateParameterList* TemplateParams = - TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, - Params, RAngleLoc, nullptr); + TemplateParameterList *TemplateParams = TemplateParameterList::Create( + getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr); return TemplateParams; } @@ -8542,11 +8585,11 @@ ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs, void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set, const RecordData &Record, unsigned &Idx) { unsigned NumDecls = Record[Idx++]; - Set.reserve(Context, NumDecls); + Set.reserve(getContext(), NumDecls); while (NumDecls--) { DeclID ID = ReadDeclID(F, Record, Idx); AccessSpecifier AS = (AccessSpecifier)Record[Idx++]; - Set.addLazyDecl(Context, ID, AS); + Set.addLazyDecl(getContext(), ID, AS); } } @@ -8569,6 +8612,7 @@ ASTReader::ReadCXXBaseSpecifier(ModuleFile &F, CXXCtorInitializer ** ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record, unsigned &Idx) { + ASTContext &Context = getContext(); unsigned NumInitializers = Record[Idx++]; assert(NumInitializers && "wrote ctor initializers but have no inits"); auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; @@ -8634,6 +8678,7 @@ ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record, NestedNameSpecifier * ASTReader::ReadNestedNameSpecifier(ModuleFile &F, const RecordData &Record, unsigned &Idx) { + ASTContext &Context = getContext(); unsigned N = Record[Idx++]; NestedNameSpecifier *NNS = nullptr, *Prev = nullptr; for (unsigned I = 0; I != N; ++I) { @@ -8689,6 +8734,7 @@ ASTReader::ReadNestedNameSpecifier(ModuleFile &F, NestedNameSpecifierLoc ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx) { + ASTContext &Context = getContext(); unsigned N = Record[Idx++]; NestedNameSpecifierLocBuilder Builder; for (unsigned I = 0; I != N; ++I) { @@ -8810,7 +8856,7 @@ CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx) { CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx); - return CXXTemporary::Create(Context, Decl); + return CXXTemporary::Create(getContext(), Decl); } DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { @@ -8846,6 +8892,7 @@ void ASTReader::ClearSwitchCaseIDs() { } void ASTReader::ReadComments() { + ASTContext &Context = getContext(); std::vector<RawComment *> Comments; for (SmallVectorImpl<std::pair<BitstreamCursor, serialization::ModuleFile *> >::iterator @@ -8915,6 +8962,19 @@ void ASTReader::visitInputFiles(serialization::ModuleFile &MF, } } +void ASTReader::visitTopLevelModuleMaps( + serialization::ModuleFile &MF, + llvm::function_ref<void(const FileEntry *FE)> Visitor) { + unsigned NumInputs = MF.InputFilesLoaded.size(); + for (unsigned I = 0; I < NumInputs; ++I) { + InputFileInfo IFI = readInputFileInfo(MF, I + 1); + if (IFI.TopLevelModuleMap) + // FIXME: This unnecessarily re-reads the InputFileInfo. + if (auto *FE = getInputFile(MF, I + 1).getFile()) + Visitor(FE); + } +} + std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) { // If we know the owning module, use it. if (Module *M = D->getImportedOwningModule()) @@ -9514,8 +9574,8 @@ void ASTReader::diagnoseOdrViolations() { break; } - assert( - Context.hasSameType(FirstField->getType(), SecondField->getType())); + assert(getContext().hasSameType(FirstField->getType(), + SecondField->getType())); QualType FirstType = FirstField->getType(); QualType SecondType = SecondField->getType(); @@ -9966,10 +10026,10 @@ void ASTReader::FinishedDeserializing() { ProcessingUpdatesRAIIObj ProcessingUpdates(*this); auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); auto ESI = FPT->getExtProtoInfo().ExceptionSpec; - if (auto *Listener = Context.getASTMutationListener()) + if (auto *Listener = getContext().getASTMutationListener()) Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second)); for (auto *Redecl : Update.second->redecls()) - Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); + getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); } } @@ -10011,7 +10071,7 @@ void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { } } -ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, +ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, StringRef isysroot, bool DisableValidation, @@ -10024,7 +10084,7 @@ ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, : cast<ASTReaderListener>(new PCHValidator(PP, *this))), SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP), - Context(Context), + ContextObj(Context), ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr), PCMCache(PP.getPCMCache()), DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot), diff --git a/contrib/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp b/contrib/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp index 07ab421cfc51..4d9ddd2ff506 100644 --- a/contrib/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp +++ b/contrib/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp @@ -126,6 +126,9 @@ namespace clang { void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data); void MergeDefinitionData(ObjCInterfaceDecl *D, struct ObjCInterfaceDecl::DefinitionData &&NewDD); + void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data); + void MergeDefinitionData(ObjCProtocolDecl *D, + struct ObjCProtocolDecl::DefinitionData &&NewDD); static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC, @@ -216,6 +219,30 @@ namespace clang { TypedefNameForLinkage(nullptr), HasPendingBody(false), IsDeclMarkedUsed(false) {} + template <typename T> static + void AddLazySpecializations(T *D, + SmallVectorImpl<serialization::DeclID>& IDs) { + if (IDs.empty()) + return; + + // FIXME: We should avoid this pattern of getting the ASTContext. + ASTContext &C = D->getASTContext(); + + auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations; + + if (auto &Old = LazySpecializations) { + IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]); + std::sort(IDs.begin(), IDs.end()); + IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end()); + } + + auto *Result = new (C) serialization::DeclID[1 + IDs.size()]; + *Result = IDs.size(); + std::copy(IDs.begin(), IDs.end(), Result + 1); + + LazySpecializations = Result; + } + template <typename DeclT> static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D); static Decl *getMostRecentDeclImpl(...); @@ -244,7 +271,7 @@ namespace clang { void ReadFunctionDefinition(FunctionDecl *FD); void Visit(Decl *D); - void UpdateDecl(Decl *D); + void UpdateDecl(Decl *D, llvm::SmallVectorImpl<serialization::DeclID>&); static void setNextObjCCategory(ObjCCategoryDecl *Cat, ObjCCategoryDecl *Next) { @@ -1045,18 +1072,8 @@ void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) { IVD->setSynthesize(synth); } -void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) { - RedeclarableResult Redecl = VisitRedeclarable(PD); - VisitObjCContainerDecl(PD); - mergeRedeclarable(PD, Redecl); - - if (Record.readInt()) { - // Read the definition. - PD->allocateDefinitionData(); - - // Set the definition data of the canonical declaration, so other - // redeclarations will see it. - PD->getCanonicalDecl()->Data = PD->Data; +void ASTDeclReader::ReadObjCDefinitionData( + struct ObjCProtocolDecl::DefinitionData &Data) { unsigned NumProtoRefs = Record.readInt(); SmallVector<ObjCProtocolDecl *, 16> ProtoRefs; @@ -1067,9 +1084,37 @@ void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) { ProtoLocs.reserve(NumProtoRefs); for (unsigned I = 0; I != NumProtoRefs; ++I) ProtoLocs.push_back(ReadSourceLocation()); - PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(), - Reader.getContext()); + Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs, + ProtoLocs.data(), Reader.getContext()); +} + +void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D, + struct ObjCProtocolDecl::DefinitionData &&NewDD) { + // FIXME: odr checking? +} + +void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) { + RedeclarableResult Redecl = VisitRedeclarable(PD); + VisitObjCContainerDecl(PD); + mergeRedeclarable(PD, Redecl); + + if (Record.readInt()) { + // Read the definition. + PD->allocateDefinitionData(); + + ReadObjCDefinitionData(PD->data()); + ObjCProtocolDecl *Canon = PD->getCanonicalDecl(); + if (Canon->Data.getPointer()) { + // If we already have a definition, keep the definition invariant and + // merge the data. + MergeDefinitionData(Canon, std::move(PD->data())); + PD->Data = Canon->Data; + } else { + // Set the definition data of the canonical declaration, so other + // redeclarations will see it. + PD->getCanonicalDecl()->Data = PD->Data; + } // Note that we have deserialized a definition. Reader.PendingDefinitions.insert(PD); } else { @@ -1566,8 +1611,8 @@ void ASTDeclReader::ReadCXXDefinitionData( Lambda.NumExplicitCaptures = Record.readInt(); Lambda.ManglingNumber = Record.readInt(); Lambda.ContextDecl = ReadDeclID(); - Lambda.Captures - = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures); + Lambda.Captures = (Capture *)Reader.getContext().Allocate( + sizeof(Capture) * Lambda.NumCaptures); Capture *ToCapture = Lambda.Captures; Lambda.MethodTyInfo = GetTypeSourceInfo(); for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) { @@ -1950,21 +1995,6 @@ ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) { return Redecl; } -static DeclID *newDeclIDList(ASTContext &Context, DeclID *Old, - SmallVectorImpl<DeclID> &IDs) { - assert(!IDs.empty() && "no IDs to add to list"); - if (Old) { - IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]); - std::sort(IDs.begin(), IDs.end()); - IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end()); - } - - auto *Result = new (Context) DeclID[1 + IDs.size()]; - *Result = IDs.size(); - std::copy(IDs.begin(), IDs.end(), Result + 1); - return Result; -} - void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) { RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D); @@ -1973,19 +2003,14 @@ void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) { // the specializations. SmallVector<serialization::DeclID, 32> SpecIDs; ReadDeclIDList(SpecIDs); - - if (!SpecIDs.empty()) { - auto *CommonPtr = D->getCommonPtr(); - CommonPtr->LazySpecializations = newDeclIDList( - Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs); - } + ASTDeclReader::AddLazySpecializations(D, SpecIDs); } if (D->getTemplatedDecl()->TemplateOrInstantiation) { // We were loaded before our templated declaration was. We've not set up // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct // it now. - Reader.Context.getInjectedClassNameType( + Reader.getContext().getInjectedClassNameType( D->getTemplatedDecl(), D->getInjectedClassNameSpecialization()); } } @@ -2005,12 +2030,7 @@ void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) { // the specializations. SmallVector<serialization::DeclID, 32> SpecIDs; ReadDeclIDList(SpecIDs); - - if (!SpecIDs.empty()) { - auto *CommonPtr = D->getCommonPtr(); - CommonPtr->LazySpecializations = newDeclIDList( - Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs); - } + ASTDeclReader::AddLazySpecializations(D, SpecIDs); } } @@ -2116,12 +2136,7 @@ void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { // This FunctionTemplateDecl owns a CommonPtr; read it. SmallVector<serialization::DeclID, 32> SpecIDs; ReadDeclIDList(SpecIDs); - - if (!SpecIDs.empty()) { - auto *CommonPtr = D->getCommonPtr(); - CommonPtr->LazySpecializations = newDeclIDList( - Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs); - } + ASTDeclReader::AddLazySpecializations(D, SpecIDs); } } @@ -2472,8 +2487,8 @@ void ASTDeclReader::mergeMergeable(Mergeable<T> *D) { if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D))) if (T *Existing = ExistingRes) - Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D), - Existing->getCanonicalDecl()); + Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D), + Existing->getCanonicalDecl()); } void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) { @@ -2509,6 +2524,7 @@ void ASTReader::ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs) { Attr *New = nullptr; attr::Kind Kind = (attr::Kind)Record.readInt(); SourceRange Range = Record.readSourceRange(); + ASTContext &Context = getContext(); #include "clang/Serialization/AttrPCHRead.inc" @@ -2907,7 +2923,7 @@ DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader, // commit to DC being the canonical definition now, and will fix this when // we load the update record. if (!DD) { - DD = new (Reader.Context) struct CXXRecordDecl::DefinitionData(RD); + DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD); RD->IsCompleteDefinition = true; RD->DefinitionData = DD; RD->getCanonicalDecl()->DefinitionData = DD; @@ -3352,6 +3368,7 @@ Decl *ASTReader::ReadDeclRecord(DeclID ID) { ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc); unsigned Code = DeclsCursor.ReadCode(); + ASTContext &Context = getContext(); Decl *D = nullptr; switch ((DeclCode)Record.readRecord(DeclsCursor, Code)) { case DECL_CONTEXT_LEXICAL: @@ -3652,7 +3669,7 @@ void ASTReader::PassInterestingDeclsToConsumer() { while (!PotentiallyInterestingDecls.empty()) { InterestingDecl D = PotentiallyInterestingDecls.front(); PotentiallyInterestingDecls.pop_front(); - if (isConsumerInterestedIn(Context, D.getDecl(), D.hasPendingBody())) + if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody())) PassInterestingDeclToConsumer(D.getDecl()); } } @@ -3665,6 +3682,9 @@ void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) { Decl *D = Record.D; ProcessingUpdatesRAIIObj ProcessingUpdates(*this); DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID); + + llvm::SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs; + if (UpdI != DeclUpdateOffsets.end()) { auto UpdateOffsets = std::move(UpdI->second); DeclUpdateOffsets.erase(UpdI); @@ -3674,7 +3694,7 @@ void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) { // to isConsumerInterestedIn because it is unsafe to call in the // current ASTReader state. bool WasInteresting = - Record.JustLoaded || isConsumerInterestedIn(Context, D, false); + Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false); for (auto &FileAndOffset : UpdateOffsets) { ModuleFile *F = FileAndOffset.first; uint64_t Offset = FileAndOffset.second; @@ -3689,18 +3709,29 @@ void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) { ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID, SourceLocation()); - Reader.UpdateDecl(D); + Reader.UpdateDecl(D, PendingLazySpecializationIDs); // We might have made this declaration interesting. If so, remember that // we need to hand it off to the consumer. if (!WasInteresting && - isConsumerInterestedIn(Context, D, Reader.hasPendingBody())) { + isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) { PotentiallyInterestingDecls.push_back( InterestingDecl(D, Reader.hasPendingBody())); WasInteresting = true; } } } + // Add the lazy specializations to the template. + assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) || + isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) && + "Must not have pending specializations"); + if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) + ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs); + else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) + ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs); + else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) + ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs); + PendingLazySpecializationIDs.clear(); // Load the pending visible updates for this decl context, if it has any. auto I = PendingVisibleUpdates.find(ID); @@ -3897,7 +3928,8 @@ static void forAllLaterRedecls(DeclT *D, Fn F) { } } -void ASTDeclReader::UpdateDecl(Decl *D) { +void ASTDeclReader::UpdateDecl(Decl *D, + llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) { while (Record.getIdx() < Record.size()) { switch ((DeclUpdateKind)Record.readInt()) { case UPD_CXX_ADDED_IMPLICIT_MEMBER: { @@ -3913,8 +3945,8 @@ void ASTDeclReader::UpdateDecl(Decl *D) { } case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: - // It will be added to the template's specializations set when loaded. - (void)Record.readDecl(); + // It will be added to the template's lazy specialization set. + PendingLazySpecializationIDs.push_back(ReadDeclID()); break; case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: { @@ -4083,7 +4115,7 @@ void ASTDeclReader::UpdateDecl(Decl *D) { // FIXME: If the exception specification is already present, check that it // matches. if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { - FD->setType(Reader.Context.getFunctionType( + FD->setType(Reader.getContext().getFunctionType( FPT->getReturnType(), FPT->getParamTypes(), FPT->getExtProtoInfo().withExceptionSpec(ESI))); @@ -4101,28 +4133,31 @@ void ASTDeclReader::UpdateDecl(Decl *D) { for (auto *Redecl : merged_redecls(D)) { // FIXME: If the return type is already deduced, check that it matches. FunctionDecl *FD = cast<FunctionDecl>(Redecl); - Reader.Context.adjustDeducedFunctionResultType(FD, DeducedResultType); + Reader.getContext().adjustDeducedFunctionResultType(FD, + DeducedResultType); } break; } case UPD_DECL_MARKED_USED: { // Maintain AST consistency: any later redeclarations are used too. - D->markUsed(Reader.Context); + D->markUsed(Reader.getContext()); break; } case UPD_MANGLING_NUMBER: - Reader.Context.setManglingNumber(cast<NamedDecl>(D), Record.readInt()); + Reader.getContext().setManglingNumber(cast<NamedDecl>(D), + Record.readInt()); break; case UPD_STATIC_LOCAL_NUMBER: - Reader.Context.setStaticLocalNumber(cast<VarDecl>(D), Record.readInt()); + Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D), + Record.readInt()); break; case UPD_DECL_MARKED_OPENMP_THREADPRIVATE: - D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( - Reader.Context, ReadSourceRange())); + D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(Reader.getContext(), + ReadSourceRange())); break; case UPD_DECL_EXPORTED: { diff --git a/contrib/llvm/tools/clang/lib/Serialization/ASTReaderStmt.cpp b/contrib/llvm/tools/clang/lib/Serialization/ASTReaderStmt.cpp index 3d314a85ff17..afee50ffa3b9 100644 --- a/contrib/llvm/tools/clang/lib/Serialization/ASTReaderStmt.cpp +++ b/contrib/llvm/tools/clang/lib/Serialization/ASTReaderStmt.cpp @@ -2954,6 +2954,7 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { break; } + ASTContext &Context = getContext(); Stmt *S = nullptr; bool Finished = false; bool IsStmtReference = false; diff --git a/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp b/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp index 1c0db14ced14..c6129d326cb6 100644 --- a/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp +++ b/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp @@ -1692,6 +1692,7 @@ namespace { bool IsSystemFile; bool IsTransient; bool BufferOverridden; + bool IsTopLevelModuleMap; }; } // end anonymous namespace @@ -1710,6 +1711,7 @@ void ASTWriter::WriteInputFiles(SourceManager &SourceMgr, IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient + IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev)); @@ -1724,7 +1726,8 @@ void ASTWriter::WriteInputFiles(SourceManager &SourceMgr, // We only care about file entries that were not overridden. if (!SLoc->isFile()) continue; - const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache(); + const SrcMgr::FileInfo &File = SLoc->getFile(); + const SrcMgr::ContentCache *Cache = File.getContentCache(); if (!Cache->OrigEntry) continue; @@ -1733,6 +1736,8 @@ void ASTWriter::WriteInputFiles(SourceManager &SourceMgr, Entry.IsSystemFile = Cache->IsSystemFile; Entry.IsTransient = Cache->IsTransient; Entry.BufferOverridden = Cache->BufferOverridden; + Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) && + File.getIncludeLoc().isInvalid(); if (Cache->IsSystemFile) SortedFiles.push_back(Entry); else @@ -1763,7 +1768,8 @@ void ASTWriter::WriteInputFiles(SourceManager &SourceMgr, (uint64_t)Entry.File->getSize(), (uint64_t)getTimestampForOutput(Entry.File), Entry.BufferOverridden, - Entry.IsTransient}; + Entry.IsTransient, + Entry.IsTopLevelModuleMap}; EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName()); } @@ -1798,7 +1804,7 @@ static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location - Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic + Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives // FileEntry fields. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID @@ -1817,7 +1823,7 @@ static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location - Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic + Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob return Stream.EmitAbbrev(std::move(Abbrev)); @@ -1925,8 +1931,8 @@ namespace { endian::Writer<little> LE(Out); uint64_t Start = Out.tell(); (void)Start; - unsigned char Flags = (Data.HFI.isImport << 4) - | (Data.HFI.isPragmaOnce << 3) + unsigned char Flags = (Data.HFI.isImport << 5) + | (Data.HFI.isPragmaOnce << 4) | (Data.HFI.DirInfo << 1) | Data.HFI.IndexHeaderMapHeader; LE.write<uint8_t>(Flags); diff --git a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp index 26bf597bd950..7f9a00ff876d 100644 --- a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp +++ b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp @@ -45,6 +45,8 @@ class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > { mutable Optional<uint64_t> Val_O_CREAT; public: + DefaultBool CheckMisuse, CheckPortability; + void checkPreStmt(const CallExpr *CE, CheckerContext &C) const; void CheckOpen(CheckerContext &C, const CallExpr *CE) const; @@ -437,29 +439,42 @@ void UnixAPIChecker::checkPreStmt(const CallExpr *CE, if (FName.empty()) return; - SubChecker SC = - llvm::StringSwitch<SubChecker>(FName) - .Case("open", &UnixAPIChecker::CheckOpen) - .Case("openat", &UnixAPIChecker::CheckOpenAt) - .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce) - .Case("calloc", &UnixAPIChecker::CheckCallocZero) - .Case("malloc", &UnixAPIChecker::CheckMallocZero) - .Case("realloc", &UnixAPIChecker::CheckReallocZero) - .Case("reallocf", &UnixAPIChecker::CheckReallocfZero) - .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero) - .Case("__builtin_alloca_with_align", - &UnixAPIChecker::CheckAllocaWithAlignZero) - .Case("valloc", &UnixAPIChecker::CheckVallocZero) - .Default(nullptr); - - if (SC) - (this->*SC)(C, CE); + if (CheckMisuse) { + if (SubChecker SC = + llvm::StringSwitch<SubChecker>(FName) + .Case("open", &UnixAPIChecker::CheckOpen) + .Case("openat", &UnixAPIChecker::CheckOpenAt) + .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce) + .Default(nullptr)) { + (this->*SC)(C, CE); + } + } + if (CheckPortability) { + if (SubChecker SC = + llvm::StringSwitch<SubChecker>(FName) + .Case("calloc", &UnixAPIChecker::CheckCallocZero) + .Case("malloc", &UnixAPIChecker::CheckMallocZero) + .Case("realloc", &UnixAPIChecker::CheckReallocZero) + .Case("reallocf", &UnixAPIChecker::CheckReallocfZero) + .Cases("alloca", "__builtin_alloca", + &UnixAPIChecker::CheckAllocaZero) + .Case("__builtin_alloca_with_align", + &UnixAPIChecker::CheckAllocaWithAlignZero) + .Case("valloc", &UnixAPIChecker::CheckVallocZero) + .Default(nullptr)) { + (this->*SC)(C, CE); + } + } } //===----------------------------------------------------------------------===// // Registration. //===----------------------------------------------------------------------===// -void ento::registerUnixAPIChecker(CheckerManager &mgr) { - mgr.registerChecker<UnixAPIChecker>(); -} +#define REGISTER_CHECKER(Name) \ + void ento::registerUnixAPI##Name##Checker(CheckerManager &mgr) { \ + mgr.registerChecker<UnixAPIChecker>()->Check##Name = true; \ + } + +REGISTER_CHECKER(Misuse) +REGISTER_CHECKER(Portability) diff --git a/contrib/llvm/tools/clang/lib/Tooling/CompilationDatabase.cpp b/contrib/llvm/tools/clang/lib/Tooling/CompilationDatabase.cpp index 77c5b547ca09..0e835579e04e 100644 --- a/contrib/llvm/tools/clang/lib/Tooling/CompilationDatabase.cpp +++ b/contrib/llvm/tools/clang/lib/Tooling/CompilationDatabase.cpp @@ -255,10 +255,12 @@ static bool stripPositionalArgs(std::vector<const char *> Args, CompileJobAnalyzer CompileAnalyzer; for (const auto &Cmd : Jobs) { - // Collect only for Assemble jobs. If we do all jobs we get duplicates - // since Link jobs point to Assemble jobs as inputs. - if (Cmd.getSource().getKind() == driver::Action::AssembleJobClass) + // Collect only for Assemble and Compile jobs. If we do all jobs we get + // duplicates since Link jobs point to Assemble jobs as inputs. + if (Cmd.getSource().getKind() == driver::Action::AssembleJobClass || + Cmd.getSource().getKind() == driver::Action::CompileJobClass) { CompileAnalyzer.run(&Cmd.getSource()); + } } if (CompileAnalyzer.Inputs.empty()) { diff --git a/contrib/llvm/tools/clang/lib/Tooling/Refactoring/AtomicChange.cpp b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/AtomicChange.cpp index 321bbfa2866a..79dd346acf72 100644 --- a/contrib/llvm/tools/clang/lib/Tooling/Refactoring/AtomicChange.cpp +++ b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/AtomicChange.cpp @@ -12,7 +12,6 @@ #include "llvm/Support/YAMLTraits.h" #include <string> -LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string) LLVM_YAML_IS_SEQUENCE_VECTOR(clang::tooling::AtomicChange) namespace { diff --git a/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp new file mode 100644 index 000000000000..de6aba944a4a --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp @@ -0,0 +1,134 @@ +//===--- RenamingAction.cpp - Clang refactoring library -------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// \brief Provides an action to rename every symbol at a point. +/// +//===----------------------------------------------------------------------===// + +#include "clang/Tooling/Refactoring/Rename/RenamingAction.h" +#include "clang/AST/ASTConsumer.h" +#include "clang/AST/ASTContext.h" +#include "clang/Basic/FileManager.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Frontend/FrontendAction.h" +#include "clang/Lex/Lexer.h" +#include "clang/Lex/Preprocessor.h" +#include "clang/Tooling/CommonOptionsParser.h" +#include "clang/Tooling/Refactoring.h" +#include "clang/Tooling/Refactoring/Rename/USRLocFinder.h" +#include "clang/Tooling/Tooling.h" +#include <string> +#include <vector> + +using namespace llvm; + +namespace clang { +namespace tooling { + +class RenamingASTConsumer : public ASTConsumer { +public: + RenamingASTConsumer( + const std::vector<std::string> &NewNames, + const std::vector<std::string> &PrevNames, + const std::vector<std::vector<std::string>> &USRList, + std::map<std::string, tooling::Replacements> &FileToReplaces, + bool PrintLocations) + : NewNames(NewNames), PrevNames(PrevNames), USRList(USRList), + FileToReplaces(FileToReplaces), PrintLocations(PrintLocations) {} + + void HandleTranslationUnit(ASTContext &Context) override { + for (unsigned I = 0; I < NewNames.size(); ++I) + HandleOneRename(Context, NewNames[I], PrevNames[I], USRList[I]); + } + + void HandleOneRename(ASTContext &Context, const std::string &NewName, + const std::string &PrevName, + const std::vector<std::string> &USRs) { + const SourceManager &SourceMgr = Context.getSourceManager(); + std::vector<SourceLocation> RenamingCandidates; + std::vector<SourceLocation> NewCandidates; + + NewCandidates = tooling::getLocationsOfUSRs( + USRs, PrevName, Context.getTranslationUnitDecl()); + RenamingCandidates.insert(RenamingCandidates.end(), NewCandidates.begin(), + NewCandidates.end()); + + unsigned PrevNameLen = PrevName.length(); + for (const auto &Loc : RenamingCandidates) { + if (PrintLocations) { + FullSourceLoc FullLoc(Loc, SourceMgr); + errs() << "clang-rename: renamed at: " << SourceMgr.getFilename(Loc) + << ":" << FullLoc.getSpellingLineNumber() << ":" + << FullLoc.getSpellingColumnNumber() << "\n"; + } + // FIXME: better error handling. + tooling::Replacement Replace(SourceMgr, Loc, PrevNameLen, NewName); + llvm::Error Err = FileToReplaces[Replace.getFilePath()].add(Replace); + if (Err) + llvm::errs() << "Renaming failed in " << Replace.getFilePath() << "! " + << llvm::toString(std::move(Err)) << "\n"; + } + } + +private: + const std::vector<std::string> &NewNames, &PrevNames; + const std::vector<std::vector<std::string>> &USRList; + std::map<std::string, tooling::Replacements> &FileToReplaces; + bool PrintLocations; +}; + +// A renamer to rename symbols which are identified by a give USRList to +// new name. +// +// FIXME: Merge with the above RenamingASTConsumer. +class USRSymbolRenamer : public ASTConsumer { +public: + USRSymbolRenamer(const std::vector<std::string> &NewNames, + const std::vector<std::vector<std::string>> &USRList, + std::map<std::string, tooling::Replacements> &FileToReplaces) + : NewNames(NewNames), USRList(USRList), FileToReplaces(FileToReplaces) { + assert(USRList.size() == NewNames.size()); + } + + void HandleTranslationUnit(ASTContext &Context) override { + for (unsigned I = 0; I < NewNames.size(); ++I) { + // FIXME: Apply AtomicChanges directly once the refactoring APIs are + // ready. + auto AtomicChanges = tooling::createRenameAtomicChanges( + USRList[I], NewNames[I], Context.getTranslationUnitDecl()); + for (const auto AtomicChange : AtomicChanges) { + for (const auto &Replace : AtomicChange.getReplacements()) { + llvm::Error Err = FileToReplaces[Replace.getFilePath()].add(Replace); + if (Err) { + llvm::errs() << "Renaming failed in " << Replace.getFilePath() + << "! " << llvm::toString(std::move(Err)) << "\n"; + } + } + } + } + } + +private: + const std::vector<std::string> &NewNames; + const std::vector<std::vector<std::string>> &USRList; + std::map<std::string, tooling::Replacements> &FileToReplaces; +}; + +std::unique_ptr<ASTConsumer> RenamingAction::newASTConsumer() { + return llvm::make_unique<RenamingASTConsumer>(NewNames, PrevNames, USRList, + FileToReplaces, PrintLocations); +} + +std::unique_ptr<ASTConsumer> QualifiedRenamingAction::newASTConsumer() { + return llvm::make_unique<USRSymbolRenamer>(NewNames, USRList, FileToReplaces); +} + +} // end namespace tooling +} // end namespace clang diff --git a/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/USRFinder.cpp b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/USRFinder.cpp new file mode 100644 index 000000000000..f36387dafdbf --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/USRFinder.cpp @@ -0,0 +1,213 @@ +//===--- USRFinder.cpp - Clang refactoring library ------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file Implements a recursive AST visitor that finds the USR of a symbol at a +/// point. +/// +//===----------------------------------------------------------------------===// + +#include "clang/Tooling/Refactoring/Rename/USRFinder.h" +#include "clang/AST/AST.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/RecursiveASTVisitor.h" +#include "clang/Index/USRGeneration.h" +#include "clang/Lex/Lexer.h" +#include "llvm/ADT/SmallVector.h" + +using namespace llvm; + +namespace clang { +namespace tooling { + +// NamedDeclFindingASTVisitor recursively visits each AST node to find the +// symbol underneath the cursor. +// FIXME: move to separate .h/.cc file if this gets too large. +namespace { +class NamedDeclFindingASTVisitor + : public clang::RecursiveASTVisitor<NamedDeclFindingASTVisitor> { +public: + // \brief Finds the NamedDecl at a point in the source. + // \param Point the location in the source to search for the NamedDecl. + explicit NamedDeclFindingASTVisitor(const SourceLocation Point, + const ASTContext &Context) + : Result(nullptr), Point(Point), Context(Context) {} + + // \brief Finds the NamedDecl for a name in the source. + // \param Name the fully qualified name. + explicit NamedDeclFindingASTVisitor(const std::string &Name, + const ASTContext &Context) + : Result(nullptr), Name(Name), Context(Context) {} + + // Declaration visitors: + + // \brief Checks if the point falls within the NameDecl. This covers every + // declaration of a named entity that we may come across. Usually, just + // checking if the point lies within the length of the name of the declaration + // and the start location is sufficient. + bool VisitNamedDecl(const NamedDecl *Decl) { + return dyn_cast<CXXConversionDecl>(Decl) + ? true + : setResult(Decl, Decl->getLocation(), + Decl->getNameAsString().length()); + } + + // Expression visitors: + + bool VisitDeclRefExpr(const DeclRefExpr *Expr) { + const NamedDecl *Decl = Expr->getFoundDecl(); + return setResult(Decl, Expr->getLocation(), + Decl->getNameAsString().length()); + } + + bool VisitMemberExpr(const MemberExpr *Expr) { + const NamedDecl *Decl = Expr->getFoundDecl().getDecl(); + return setResult(Decl, Expr->getMemberLoc(), + Decl->getNameAsString().length()); + } + + // Other visitors: + + bool VisitTypeLoc(const TypeLoc Loc) { + const SourceLocation TypeBeginLoc = Loc.getBeginLoc(); + const SourceLocation TypeEndLoc = Lexer::getLocForEndOfToken( + TypeBeginLoc, 0, Context.getSourceManager(), Context.getLangOpts()); + if (const auto *TemplateTypeParm = + dyn_cast<TemplateTypeParmType>(Loc.getType())) + return setResult(TemplateTypeParm->getDecl(), TypeBeginLoc, TypeEndLoc); + if (const auto *TemplateSpecType = + dyn_cast<TemplateSpecializationType>(Loc.getType())) { + return setResult(TemplateSpecType->getTemplateName().getAsTemplateDecl(), + TypeBeginLoc, TypeEndLoc); + } + return setResult(Loc.getType()->getAsCXXRecordDecl(), TypeBeginLoc, + TypeEndLoc); + } + + bool VisitCXXConstructorDecl(clang::CXXConstructorDecl *ConstructorDecl) { + for (const auto *Initializer : ConstructorDecl->inits()) { + // Ignore implicit initializers. + if (!Initializer->isWritten()) + continue; + if (const clang::FieldDecl *FieldDecl = Initializer->getMember()) { + const SourceLocation InitBeginLoc = Initializer->getSourceLocation(), + InitEndLoc = Lexer::getLocForEndOfToken( + InitBeginLoc, 0, Context.getSourceManager(), + Context.getLangOpts()); + if (!setResult(FieldDecl, InitBeginLoc, InitEndLoc)) + return false; + } + } + return true; + } + + // Other: + + const NamedDecl *getNamedDecl() { return Result; } + + // \brief Determines if a namespace qualifier contains the point. + // \returns false on success and sets Result. + void handleNestedNameSpecifierLoc(NestedNameSpecifierLoc NameLoc) { + while (NameLoc) { + const NamespaceDecl *Decl = + NameLoc.getNestedNameSpecifier()->getAsNamespace(); + setResult(Decl, NameLoc.getLocalBeginLoc(), NameLoc.getLocalEndLoc()); + NameLoc = NameLoc.getPrefix(); + } + } + +private: + // \brief Sets Result to Decl if the Point is within Start and End. + // \returns false on success. + bool setResult(const NamedDecl *Decl, SourceLocation Start, + SourceLocation End) { + if (!Decl) + return true; + if (Name.empty()) { + // Offset is used to find the declaration. + if (!Start.isValid() || !Start.isFileID() || !End.isValid() || + !End.isFileID() || !isPointWithin(Start, End)) + return true; + } else { + // Fully qualified name is used to find the declaration. + if (Name != Decl->getQualifiedNameAsString() && + Name != "::" + Decl->getQualifiedNameAsString()) + return true; + } + Result = Decl; + return false; + } + + // \brief Sets Result to Decl if Point is within Loc and Loc + Offset. + // \returns false on success. + bool setResult(const NamedDecl *Decl, SourceLocation Loc, unsigned Offset) { + // FIXME: Add test for Offset == 0. Add test for Offset - 1 (vs -2 etc). + return Offset == 0 || + setResult(Decl, Loc, Loc.getLocWithOffset(Offset - 1)); + } + + // \brief Determines if the Point is within Start and End. + bool isPointWithin(const SourceLocation Start, const SourceLocation End) { + // FIXME: Add tests for Point == End. + return Point == Start || Point == End || + (Context.getSourceManager().isBeforeInTranslationUnit(Start, + Point) && + Context.getSourceManager().isBeforeInTranslationUnit(Point, End)); + } + + const NamedDecl *Result; + const SourceLocation Point; // The location to find the NamedDecl. + const std::string Name; + const ASTContext &Context; +}; +} // namespace + +const NamedDecl *getNamedDeclAt(const ASTContext &Context, + const SourceLocation Point) { + const SourceManager &SM = Context.getSourceManager(); + NamedDeclFindingASTVisitor Visitor(Point, Context); + + // Try to be clever about pruning down the number of top-level declarations we + // see. If both start and end is either before or after the point we're + // looking for the point cannot be inside of this decl. Don't even look at it. + for (auto *CurrDecl : Context.getTranslationUnitDecl()->decls()) { + SourceLocation StartLoc = CurrDecl->getLocStart(); + SourceLocation EndLoc = CurrDecl->getLocEnd(); + if (StartLoc.isValid() && EndLoc.isValid() && + SM.isBeforeInTranslationUnit(StartLoc, Point) != + SM.isBeforeInTranslationUnit(EndLoc, Point)) + Visitor.TraverseDecl(CurrDecl); + } + + NestedNameSpecifierLocFinder Finder(const_cast<ASTContext &>(Context)); + for (const auto &Location : Finder.getNestedNameSpecifierLocations()) + Visitor.handleNestedNameSpecifierLoc(Location); + + return Visitor.getNamedDecl(); +} + +const NamedDecl *getNamedDeclFor(const ASTContext &Context, + const std::string &Name) { + NamedDeclFindingASTVisitor Visitor(Name, Context); + Visitor.TraverseDecl(Context.getTranslationUnitDecl()); + + return Visitor.getNamedDecl(); +} + +std::string getUSRForDecl(const Decl *Decl) { + llvm::SmallVector<char, 128> Buff; + + // FIXME: Add test for the nullptr case. + if (Decl == nullptr || index::generateUSRForDecl(Decl, Buff)) + return ""; + + return std::string(Buff.data(), Buff.size()); +} + +} // end namespace tooling +} // end namespace clang diff --git a/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp new file mode 100644 index 000000000000..2769802ad2bc --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp @@ -0,0 +1,236 @@ +//===--- USRFindingAction.cpp - Clang refactoring library -----------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// \brief Provides an action to find USR for the symbol at <offset>, as well as +/// all additional USRs. +/// +//===----------------------------------------------------------------------===// + +#include "clang/Tooling/Refactoring/Rename/USRFindingAction.h" +#include "clang/AST/AST.h" +#include "clang/AST/ASTConsumer.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/Decl.h" +#include "clang/AST/RecursiveASTVisitor.h" +#include "clang/Basic/FileManager.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Frontend/FrontendAction.h" +#include "clang/Lex/Lexer.h" +#include "clang/Lex/Preprocessor.h" +#include "clang/Tooling/CommonOptionsParser.h" +#include "clang/Tooling/Refactoring.h" +#include "clang/Tooling/Refactoring/Rename/USRFinder.h" +#include "clang/Tooling/Tooling.h" + +#include <algorithm> +#include <set> +#include <string> +#include <vector> + +using namespace llvm; + +namespace clang { +namespace tooling { + +namespace { +// \brief NamedDeclFindingConsumer should delegate finding USRs of given Decl to +// AdditionalUSRFinder. AdditionalUSRFinder adds USRs of ctor and dtor if given +// Decl refers to class and adds USRs of all overridden methods if Decl refers +// to virtual method. +class AdditionalUSRFinder : public RecursiveASTVisitor<AdditionalUSRFinder> { +public: + AdditionalUSRFinder(const Decl *FoundDecl, ASTContext &Context) + : FoundDecl(FoundDecl), Context(Context) {} + + std::vector<std::string> Find() { + // Fill OverriddenMethods and PartialSpecs storages. + TraverseDecl(Context.getTranslationUnitDecl()); + if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FoundDecl)) { + addUSRsOfOverridenFunctions(MethodDecl); + for (const auto &OverriddenMethod : OverriddenMethods) { + if (checkIfOverriddenFunctionAscends(OverriddenMethod)) + USRSet.insert(getUSRForDecl(OverriddenMethod)); + } + } else if (const auto *RecordDecl = dyn_cast<CXXRecordDecl>(FoundDecl)) { + handleCXXRecordDecl(RecordDecl); + } else if (const auto *TemplateDecl = + dyn_cast<ClassTemplateDecl>(FoundDecl)) { + handleClassTemplateDecl(TemplateDecl); + } else { + USRSet.insert(getUSRForDecl(FoundDecl)); + } + return std::vector<std::string>(USRSet.begin(), USRSet.end()); + } + + bool VisitCXXMethodDecl(const CXXMethodDecl *MethodDecl) { + if (MethodDecl->isVirtual()) + OverriddenMethods.push_back(MethodDecl); + return true; + } + + bool VisitClassTemplatePartialSpecializationDecl( + const ClassTemplatePartialSpecializationDecl *PartialSpec) { + PartialSpecs.push_back(PartialSpec); + return true; + } + +private: + void handleCXXRecordDecl(const CXXRecordDecl *RecordDecl) { + RecordDecl = RecordDecl->getDefinition(); + if (const auto *ClassTemplateSpecDecl = + dyn_cast<ClassTemplateSpecializationDecl>(RecordDecl)) + handleClassTemplateDecl(ClassTemplateSpecDecl->getSpecializedTemplate()); + addUSRsOfCtorDtors(RecordDecl); + } + + void handleClassTemplateDecl(const ClassTemplateDecl *TemplateDecl) { + for (const auto *Specialization : TemplateDecl->specializations()) + addUSRsOfCtorDtors(Specialization); + + for (const auto *PartialSpec : PartialSpecs) { + if (PartialSpec->getSpecializedTemplate() == TemplateDecl) + addUSRsOfCtorDtors(PartialSpec); + } + addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl()); + } + + void addUSRsOfCtorDtors(const CXXRecordDecl *RecordDecl) { + RecordDecl = RecordDecl->getDefinition(); + + // Skip if the CXXRecordDecl doesn't have definition. + if (!RecordDecl) + return; + + for (const auto *CtorDecl : RecordDecl->ctors()) + USRSet.insert(getUSRForDecl(CtorDecl)); + + USRSet.insert(getUSRForDecl(RecordDecl->getDestructor())); + USRSet.insert(getUSRForDecl(RecordDecl)); + } + + void addUSRsOfOverridenFunctions(const CXXMethodDecl *MethodDecl) { + USRSet.insert(getUSRForDecl(MethodDecl)); + // Recursively visit each OverridenMethod. + for (const auto &OverriddenMethod : MethodDecl->overridden_methods()) + addUSRsOfOverridenFunctions(OverriddenMethod); + } + + bool checkIfOverriddenFunctionAscends(const CXXMethodDecl *MethodDecl) { + for (const auto &OverriddenMethod : MethodDecl->overridden_methods()) { + if (USRSet.find(getUSRForDecl(OverriddenMethod)) != USRSet.end()) + return true; + return checkIfOverriddenFunctionAscends(OverriddenMethod); + } + return false; + } + + const Decl *FoundDecl; + ASTContext &Context; + std::set<std::string> USRSet; + std::vector<const CXXMethodDecl *> OverriddenMethods; + std::vector<const ClassTemplatePartialSpecializationDecl *> PartialSpecs; +}; +} // namespace + +class NamedDeclFindingConsumer : public ASTConsumer { +public: + NamedDeclFindingConsumer(ArrayRef<unsigned> SymbolOffsets, + ArrayRef<std::string> QualifiedNames, + std::vector<std::string> &SpellingNames, + std::vector<std::vector<std::string>> &USRList, + bool Force, bool &ErrorOccurred) + : SymbolOffsets(SymbolOffsets), QualifiedNames(QualifiedNames), + SpellingNames(SpellingNames), USRList(USRList), Force(Force), + ErrorOccurred(ErrorOccurred) {} + +private: + bool FindSymbol(ASTContext &Context, const SourceManager &SourceMgr, + unsigned SymbolOffset, const std::string &QualifiedName) { + DiagnosticsEngine &Engine = Context.getDiagnostics(); + const FileID MainFileID = SourceMgr.getMainFileID(); + + if (SymbolOffset >= SourceMgr.getFileIDSize(MainFileID)) { + ErrorOccurred = true; + unsigned InvalidOffset = Engine.getCustomDiagID( + DiagnosticsEngine::Error, + "SourceLocation in file %0 at offset %1 is invalid"); + Engine.Report(SourceLocation(), InvalidOffset) + << SourceMgr.getFileEntryForID(MainFileID)->getName() << SymbolOffset; + return false; + } + + const SourceLocation Point = SourceMgr.getLocForStartOfFile(MainFileID) + .getLocWithOffset(SymbolOffset); + const NamedDecl *FoundDecl = QualifiedName.empty() + ? getNamedDeclAt(Context, Point) + : getNamedDeclFor(Context, QualifiedName); + + if (FoundDecl == nullptr) { + if (QualifiedName.empty()) { + FullSourceLoc FullLoc(Point, SourceMgr); + unsigned CouldNotFindSymbolAt = Engine.getCustomDiagID( + DiagnosticsEngine::Error, + "clang-rename could not find symbol (offset %0)"); + Engine.Report(Point, CouldNotFindSymbolAt) << SymbolOffset; + ErrorOccurred = true; + return false; + } + + if (Force) + return true; + + unsigned CouldNotFindSymbolNamed = Engine.getCustomDiagID( + DiagnosticsEngine::Error, "clang-rename could not find symbol %0"); + Engine.Report(CouldNotFindSymbolNamed) << QualifiedName; + ErrorOccurred = true; + return false; + } + + // If FoundDecl is a constructor or destructor, we want to instead take + // the Decl of the corresponding class. + if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(FoundDecl)) + FoundDecl = CtorDecl->getParent(); + else if (const auto *DtorDecl = dyn_cast<CXXDestructorDecl>(FoundDecl)) + FoundDecl = DtorDecl->getParent(); + + SpellingNames.push_back(FoundDecl->getNameAsString()); + AdditionalUSRFinder Finder(FoundDecl, Context); + USRList.push_back(Finder.Find()); + return true; + } + + void HandleTranslationUnit(ASTContext &Context) override { + const SourceManager &SourceMgr = Context.getSourceManager(); + for (unsigned Offset : SymbolOffsets) { + if (!FindSymbol(Context, SourceMgr, Offset, "")) + return; + } + for (const std::string &QualifiedName : QualifiedNames) { + if (!FindSymbol(Context, SourceMgr, 0, QualifiedName)) + return; + } + } + + ArrayRef<unsigned> SymbolOffsets; + ArrayRef<std::string> QualifiedNames; + std::vector<std::string> &SpellingNames; + std::vector<std::vector<std::string>> &USRList; + bool Force; + bool &ErrorOccurred; +}; + +std::unique_ptr<ASTConsumer> USRFindingAction::newASTConsumer() { + return llvm::make_unique<NamedDeclFindingConsumer>( + SymbolOffsets, QualifiedNames, SpellingNames, USRList, Force, + ErrorOccurred); +} + +} // end namespace tooling +} // end namespace clang diff --git a/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp new file mode 100644 index 000000000000..934507fe6eae --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp @@ -0,0 +1,509 @@ +//===--- USRLocFinder.cpp - Clang refactoring library ---------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// \brief Methods for finding all instances of a USR. Our strategy is very +/// simple; we just compare the USR at every relevant AST node with the one +/// provided. +/// +//===----------------------------------------------------------------------===// + +#include "clang/Tooling/Refactoring/Rename/USRLocFinder.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/RecursiveASTVisitor.h" +#include "clang/Basic/LLVM.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Basic/SourceManager.h" +#include "clang/Lex/Lexer.h" +#include "clang/Tooling/Core/Lookup.h" +#include "clang/Tooling/Refactoring/Rename/USRFinder.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/Casting.h" +#include <cstddef> +#include <set> +#include <string> +#include <vector> + +using namespace llvm; + +namespace clang { +namespace tooling { + +namespace { + +// \brief This visitor recursively searches for all instances of a USR in a +// translation unit and stores them for later usage. +class USRLocFindingASTVisitor + : public clang::RecursiveASTVisitor<USRLocFindingASTVisitor> { +public: + explicit USRLocFindingASTVisitor(const std::vector<std::string> &USRs, + StringRef PrevName, + const ASTContext &Context) + : USRSet(USRs.begin(), USRs.end()), PrevName(PrevName), Context(Context) { + } + + // Declaration visitors: + + bool VisitCXXConstructorDecl(clang::CXXConstructorDecl *ConstructorDecl) { + for (const auto *Initializer : ConstructorDecl->inits()) { + // Ignore implicit initializers. + if (!Initializer->isWritten()) + continue; + if (const clang::FieldDecl *FieldDecl = Initializer->getMember()) { + if (USRSet.find(getUSRForDecl(FieldDecl)) != USRSet.end()) + LocationsFound.push_back(Initializer->getSourceLocation()); + } + } + return true; + } + + bool VisitNamedDecl(const NamedDecl *Decl) { + if (USRSet.find(getUSRForDecl(Decl)) != USRSet.end()) + checkAndAddLocation(Decl->getLocation()); + return true; + } + + // Expression visitors: + + bool VisitDeclRefExpr(const DeclRefExpr *Expr) { + const NamedDecl *Decl = Expr->getFoundDecl(); + + if (USRSet.find(getUSRForDecl(Decl)) != USRSet.end()) { + const SourceManager &Manager = Decl->getASTContext().getSourceManager(); + SourceLocation Location = Manager.getSpellingLoc(Expr->getLocation()); + checkAndAddLocation(Location); + } + + return true; + } + + bool VisitMemberExpr(const MemberExpr *Expr) { + const NamedDecl *Decl = Expr->getFoundDecl().getDecl(); + if (USRSet.find(getUSRForDecl(Decl)) != USRSet.end()) { + const SourceManager &Manager = Decl->getASTContext().getSourceManager(); + SourceLocation Location = Manager.getSpellingLoc(Expr->getMemberLoc()); + checkAndAddLocation(Location); + } + return true; + } + + // Other visitors: + + bool VisitTypeLoc(const TypeLoc Loc) { + if (USRSet.find(getUSRForDecl(Loc.getType()->getAsCXXRecordDecl())) != + USRSet.end()) + checkAndAddLocation(Loc.getBeginLoc()); + if (const auto *TemplateTypeParm = + dyn_cast<TemplateTypeParmType>(Loc.getType())) { + if (USRSet.find(getUSRForDecl(TemplateTypeParm->getDecl())) != + USRSet.end()) + checkAndAddLocation(Loc.getBeginLoc()); + } + return true; + } + + // Non-visitors: + + // \brief Returns a list of unique locations. Duplicate or overlapping + // locations are erroneous and should be reported! + const std::vector<clang::SourceLocation> &getLocationsFound() const { + return LocationsFound; + } + + // Namespace traversal: + void handleNestedNameSpecifierLoc(NestedNameSpecifierLoc NameLoc) { + while (NameLoc) { + const NamespaceDecl *Decl = + NameLoc.getNestedNameSpecifier()->getAsNamespace(); + if (Decl && USRSet.find(getUSRForDecl(Decl)) != USRSet.end()) + checkAndAddLocation(NameLoc.getLocalBeginLoc()); + NameLoc = NameLoc.getPrefix(); + } + } + +private: + void checkAndAddLocation(SourceLocation Loc) { + const SourceLocation BeginLoc = Loc; + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( + BeginLoc, 0, Context.getSourceManager(), Context.getLangOpts()); + StringRef TokenName = + Lexer::getSourceText(CharSourceRange::getTokenRange(BeginLoc, EndLoc), + Context.getSourceManager(), Context.getLangOpts()); + size_t Offset = TokenName.find(PrevName); + + // The token of the source location we find actually has the old + // name. + if (Offset != StringRef::npos) + LocationsFound.push_back(BeginLoc.getLocWithOffset(Offset)); + } + + const std::set<std::string> USRSet; + const std::string PrevName; + std::vector<clang::SourceLocation> LocationsFound; + const ASTContext &Context; +}; + +SourceLocation StartLocationForType(TypeLoc TL) { + // For elaborated types (e.g. `struct a::A`) we want the portion after the + // `struct` but including the namespace qualifier, `a::`. + if (auto ElaboratedTypeLoc = TL.getAs<clang::ElaboratedTypeLoc>()) { + NestedNameSpecifierLoc NestedNameSpecifier = + ElaboratedTypeLoc.getQualifierLoc(); + if (NestedNameSpecifier.getNestedNameSpecifier()) + return NestedNameSpecifier.getBeginLoc(); + TL = TL.getNextTypeLoc(); + } + return TL.getLocStart(); +} + +SourceLocation EndLocationForType(TypeLoc TL) { + // Dig past any namespace or keyword qualifications. + while (TL.getTypeLocClass() == TypeLoc::Elaborated || + TL.getTypeLocClass() == TypeLoc::Qualified) + TL = TL.getNextTypeLoc(); + + // The location for template specializations (e.g. Foo<int>) includes the + // templated types in its location range. We want to restrict this to just + // before the `<` character. + if (TL.getTypeLocClass() == TypeLoc::TemplateSpecialization) { + return TL.castAs<TemplateSpecializationTypeLoc>() + .getLAngleLoc() + .getLocWithOffset(-1); + } + return TL.getEndLoc(); +} + +NestedNameSpecifier *GetNestedNameForType(TypeLoc TL) { + // Dig past any keyword qualifications. + while (TL.getTypeLocClass() == TypeLoc::Qualified) + TL = TL.getNextTypeLoc(); + + // For elaborated types (e.g. `struct a::A`) we want the portion after the + // `struct` but including the namespace qualifier, `a::`. + if (auto ElaboratedTypeLoc = TL.getAs<clang::ElaboratedTypeLoc>()) + return ElaboratedTypeLoc.getQualifierLoc().getNestedNameSpecifier(); + return nullptr; +} + +// Find all locations identified by the given USRs for rename. +// +// This class will traverse the AST and find every AST node whose USR is in the +// given USRs' set. +class RenameLocFinder : public RecursiveASTVisitor<RenameLocFinder> { +public: + RenameLocFinder(llvm::ArrayRef<std::string> USRs, ASTContext &Context) + : USRSet(USRs.begin(), USRs.end()), Context(Context) {} + + // A structure records all information of a symbol reference being renamed. + // We try to add as few prefix qualifiers as possible. + struct RenameInfo { + // The begin location of a symbol being renamed. + SourceLocation Begin; + // The end location of a symbol being renamed. + SourceLocation End; + // The declaration of a symbol being renamed (can be nullptr). + const NamedDecl *FromDecl; + // The declaration in which the nested name is contained (can be nullptr). + const Decl *Context; + // The nested name being replaced (can be nullptr). + const NestedNameSpecifier *Specifier; + }; + + // FIXME: Currently, prefix qualifiers will be added to the renamed symbol + // definition (e.g. "class Foo {};" => "class b::Bar {};" when renaming + // "a::Foo" to "b::Bar"). + // For renaming declarations/definitions, prefix qualifiers should be filtered + // out. + bool VisitNamedDecl(const NamedDecl *Decl) { + // UsingDecl has been handled in other place. + if (llvm::isa<UsingDecl>(Decl)) + return true; + + // DestructorDecl has been handled in Typeloc. + if (llvm::isa<CXXDestructorDecl>(Decl)) + return true; + + if (Decl->isImplicit()) + return true; + + if (isInUSRSet(Decl)) { + RenameInfo Info = {Decl->getLocation(), Decl->getLocation(), nullptr, + nullptr, nullptr}; + RenameInfos.push_back(Info); + } + return true; + } + + bool VisitDeclRefExpr(const DeclRefExpr *Expr) { + const NamedDecl *Decl = Expr->getFoundDecl(); + if (isInUSRSet(Decl)) { + RenameInfo Info = {Expr->getSourceRange().getBegin(), + Expr->getSourceRange().getEnd(), Decl, + getClosestAncestorDecl(*Expr), Expr->getQualifier()}; + RenameInfos.push_back(Info); + } + + return true; + } + + bool VisitUsingDecl(const UsingDecl *Using) { + for (const auto *UsingShadow : Using->shadows()) { + if (isInUSRSet(UsingShadow->getTargetDecl())) { + UsingDecls.push_back(Using); + break; + } + } + return true; + } + + bool VisitNestedNameSpecifierLocations(NestedNameSpecifierLoc NestedLoc) { + if (!NestedLoc.getNestedNameSpecifier()->getAsType()) + return true; + if (IsTypeAliasWhichWillBeRenamedElsewhere(NestedLoc.getTypeLoc())) + return true; + + if (const auto *TargetDecl = + getSupportedDeclFromTypeLoc(NestedLoc.getTypeLoc())) { + if (isInUSRSet(TargetDecl)) { + RenameInfo Info = {NestedLoc.getBeginLoc(), + EndLocationForType(NestedLoc.getTypeLoc()), + TargetDecl, getClosestAncestorDecl(NestedLoc), + NestedLoc.getNestedNameSpecifier()->getPrefix()}; + RenameInfos.push_back(Info); + } + } + return true; + } + + bool VisitTypeLoc(TypeLoc Loc) { + if (IsTypeAliasWhichWillBeRenamedElsewhere(Loc)) + return true; + + auto Parents = Context.getParents(Loc); + TypeLoc ParentTypeLoc; + if (!Parents.empty()) { + // Handle cases of nested name specificier locations. + // + // The VisitNestedNameSpecifierLoc interface is not impelmented in + // RecursiveASTVisitor, we have to handle it explicitly. + if (const auto *NSL = Parents[0].get<NestedNameSpecifierLoc>()) { + VisitNestedNameSpecifierLocations(*NSL); + return true; + } + + if (const auto *TL = Parents[0].get<TypeLoc>()) + ParentTypeLoc = *TL; + } + + // Handle the outermost TypeLoc which is directly linked to the interesting + // declaration and don't handle nested name specifier locations. + if (const auto *TargetDecl = getSupportedDeclFromTypeLoc(Loc)) { + if (isInUSRSet(TargetDecl)) { + // Only handle the outermost typeLoc. + // + // For a type like "a::Foo", there will be two typeLocs for it. + // One ElaboratedType, the other is RecordType: + // + // ElaboratedType 0x33b9390 'a::Foo' sugar + // `-RecordType 0x338fef0 'class a::Foo' + // `-CXXRecord 0x338fe58 'Foo' + // + // Skip if this is an inner typeLoc. + if (!ParentTypeLoc.isNull() && + isInUSRSet(getSupportedDeclFromTypeLoc(ParentTypeLoc))) + return true; + RenameInfo Info = {StartLocationForType(Loc), EndLocationForType(Loc), + TargetDecl, getClosestAncestorDecl(Loc), + GetNestedNameForType(Loc)}; + RenameInfos.push_back(Info); + return true; + } + } + + // Handle specific template class specialiation cases. + if (const auto *TemplateSpecType = + dyn_cast<TemplateSpecializationType>(Loc.getType())) { + TypeLoc TargetLoc = Loc; + if (!ParentTypeLoc.isNull()) { + if (llvm::isa<ElaboratedType>(ParentTypeLoc.getType())) + TargetLoc = ParentTypeLoc; + } + + if (isInUSRSet(TemplateSpecType->getTemplateName().getAsTemplateDecl())) { + TypeLoc TargetLoc = Loc; + // FIXME: Find a better way to handle this case. + // For the qualified template class specification type like + // "ns::Foo<int>" in "ns::Foo<int>& f();", we want the parent typeLoc + // (ElaboratedType) of the TemplateSpecializationType in order to + // catch the prefix qualifiers "ns::". + if (!ParentTypeLoc.isNull() && + llvm::isa<ElaboratedType>(ParentTypeLoc.getType())) + TargetLoc = ParentTypeLoc; + RenameInfo Info = { + StartLocationForType(TargetLoc), EndLocationForType(TargetLoc), + TemplateSpecType->getTemplateName().getAsTemplateDecl(), + getClosestAncestorDecl( + ast_type_traits::DynTypedNode::create(TargetLoc)), + GetNestedNameForType(TargetLoc)}; + RenameInfos.push_back(Info); + } + } + return true; + } + + // Returns a list of RenameInfo. + const std::vector<RenameInfo> &getRenameInfos() const { return RenameInfos; } + + // Returns a list of using declarations which are needed to update. + const std::vector<const UsingDecl *> &getUsingDecls() const { + return UsingDecls; + } + +private: + // FIXME: This method may not be suitable for renaming other types like alias + // types. Need to figure out a way to handle it. + bool IsTypeAliasWhichWillBeRenamedElsewhere(TypeLoc TL) const { + while (!TL.isNull()) { + // SubstTemplateTypeParm is the TypeLocation class for a substituted type + // inside a template expansion so we ignore these. For example: + // + // template<typename T> struct S { + // T t; // <-- this T becomes a TypeLoc(int) with class + // // SubstTemplateTypeParm when S<int> is instantiated + // } + if (TL.getTypeLocClass() == TypeLoc::SubstTemplateTypeParm) + return true; + + // Typedef is the TypeLocation class for a type which is a typedef to the + // type we want to replace. We ignore the use of the typedef as we will + // replace the definition of it. For example: + // + // typedef int T; + // T a; // <--- This T is a TypeLoc(int) with class Typedef. + if (TL.getTypeLocClass() == TypeLoc::Typedef) + return true; + TL = TL.getNextTypeLoc(); + } + return false; + } + + // Get the supported declaration from a given typeLoc. If the declaration type + // is not supported, returns nullptr. + // + // FIXME: support more types, e.g. enum, type alias. + const NamedDecl *getSupportedDeclFromTypeLoc(TypeLoc Loc) { + if (const auto *RD = Loc.getType()->getAsCXXRecordDecl()) + return RD; + return nullptr; + } + + // Get the closest ancester which is a declaration of a given AST node. + template <typename ASTNodeType> + const Decl *getClosestAncestorDecl(const ASTNodeType &Node) { + auto Parents = Context.getParents(Node); + // FIXME: figure out how to handle it when there are multiple parents. + if (Parents.size() != 1) + return nullptr; + if (ast_type_traits::ASTNodeKind::getFromNodeKind<Decl>().isBaseOf( + Parents[0].getNodeKind())) + return Parents[0].template get<Decl>(); + return getClosestAncestorDecl(Parents[0]); + } + + // Get the parent typeLoc of a given typeLoc. If there is no such parent, + // return nullptr. + const TypeLoc *getParentTypeLoc(TypeLoc Loc) const { + auto Parents = Context.getParents(Loc); + // FIXME: figure out how to handle it when there are multiple parents. + if (Parents.size() != 1) + return nullptr; + return Parents[0].get<TypeLoc>(); + } + + // Check whether the USR of a given Decl is in the USRSet. + bool isInUSRSet(const Decl *Decl) const { + auto USR = getUSRForDecl(Decl); + if (USR.empty()) + return false; + return llvm::is_contained(USRSet, USR); + } + + const std::set<std::string> USRSet; + ASTContext &Context; + std::vector<RenameInfo> RenameInfos; + // Record all interested using declarations which contains the using-shadow + // declarations of the symbol declarations being renamed. + std::vector<const UsingDecl *> UsingDecls; +}; + +} // namespace + +std::vector<SourceLocation> +getLocationsOfUSRs(const std::vector<std::string> &USRs, StringRef PrevName, + Decl *Decl) { + USRLocFindingASTVisitor Visitor(USRs, PrevName, Decl->getASTContext()); + Visitor.TraverseDecl(Decl); + NestedNameSpecifierLocFinder Finder(Decl->getASTContext()); + + for (const auto &Location : Finder.getNestedNameSpecifierLocations()) + Visitor.handleNestedNameSpecifierLoc(Location); + + return Visitor.getLocationsFound(); +} + +std::vector<tooling::AtomicChange> +createRenameAtomicChanges(llvm::ArrayRef<std::string> USRs, + llvm::StringRef NewName, Decl *TranslationUnitDecl) { + RenameLocFinder Finder(USRs, TranslationUnitDecl->getASTContext()); + Finder.TraverseDecl(TranslationUnitDecl); + + const SourceManager &SM = + TranslationUnitDecl->getASTContext().getSourceManager(); + + std::vector<tooling::AtomicChange> AtomicChanges; + auto Replace = [&](SourceLocation Start, SourceLocation End, + llvm::StringRef Text) { + tooling::AtomicChange ReplaceChange = tooling::AtomicChange(SM, Start); + llvm::Error Err = ReplaceChange.replace( + SM, CharSourceRange::getTokenRange(Start, End), Text); + if (Err) { + llvm::errs() << "Faile to add replacement to AtomicChange: " + << llvm::toString(std::move(Err)) << "\n"; + return; + } + AtomicChanges.push_back(std::move(ReplaceChange)); + }; + + for (const auto &RenameInfo : Finder.getRenameInfos()) { + std::string ReplacedName = NewName.str(); + if (RenameInfo.FromDecl && RenameInfo.Context) { + if (!llvm::isa<clang::TranslationUnitDecl>( + RenameInfo.Context->getDeclContext())) { + ReplacedName = tooling::replaceNestedName( + RenameInfo.Specifier, RenameInfo.Context->getDeclContext(), + RenameInfo.FromDecl, + NewName.startswith("::") ? NewName.str() : ("::" + NewName).str()); + } + } + // If the NewName contains leading "::", add it back. + if (NewName.startswith("::") && NewName.substr(2) == ReplacedName) + ReplacedName = NewName.str(); + Replace(RenameInfo.Begin, RenameInfo.End, ReplacedName); + } + + // Hanlde using declarations explicitly as "using a::Foo" don't trigger + // typeLoc for "a::Foo". + for (const auto *Using : Finder.getUsingDecls()) + Replace(Using->getLocStart(), Using->getLocEnd(), "using " + NewName.str()); + + return AtomicChanges; +} + +} // end namespace tooling +} // end namespace clang diff --git a/contrib/llvm/tools/clang/tools/driver/driver.cpp b/contrib/llvm/tools/clang/tools/driver/driver.cpp index af25d9598021..9f37c428ff93 100644 --- a/contrib/llvm/tools/clang/tools/driver/driver.cpp +++ b/contrib/llvm/tools/clang/tools/driver/driver.cpp @@ -462,7 +462,7 @@ int main(int argc_, const char **argv_) { std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv)); int Res = 1; - if (C.get()) { + if (C && !C->containsError()) { SmallVector<std::pair<int, const Command *>, 4> FailingCommands; Res = TheDriver.ExecuteCompilation(*C, FailingCommands); diff --git a/contrib/llvm/tools/llc/llc.cpp b/contrib/llvm/tools/llc/llc.cpp index e71c3c5bb705..f13a19213c69 100644 --- a/contrib/llvm/tools/llc/llc.cpp +++ b/contrib/llvm/tools/llc/llc.cpp @@ -149,6 +149,11 @@ static cl::opt<bool> PassRemarksWithHotness( cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden); +static cl::opt<unsigned> PassRemarksHotnessThreshold( + "pass-remarks-hotness-threshold", + cl::desc("Minimum profile count required for an optimization remark to be output"), + cl::Hidden); + static cl::opt<std::string> RemarksFilename("pass-remarks-output", cl::desc("YAML output filename for pass remarks"), @@ -323,7 +328,10 @@ int main(int argc, char **argv) { Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError); if (PassRemarksWithHotness) - Context.setDiagnosticHotnessRequested(true); + Context.setDiagnosticsHotnessRequested(true); + + if (PassRemarksHotnessThreshold) + Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold); std::unique_ptr<tool_output_file> YamlFile; if (RemarksFilename != "") { diff --git a/contrib/llvm/tools/lld/COFF/Chunks.cpp b/contrib/llvm/tools/lld/COFF/Chunks.cpp index 56124acaf9a1..9b642dcaf137 100644 --- a/contrib/llvm/tools/lld/COFF/Chunks.cpp +++ b/contrib/llvm/tools/lld/COFF/Chunks.cpp @@ -11,6 +11,7 @@ #include "Error.h" #include "InputFiles.h" #include "Symbols.h" +#include "Writer.h" #include "llvm/ADT/Twine.h" #include "llvm/BinaryFormat/COFF.h" #include "llvm/Object/COFF.h" @@ -52,18 +53,27 @@ static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); } static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); } static void or16(uint8_t *P, uint16_t V) { write16le(P, read16le(P) | V); } -static void applySecRel(const SectionChunk *Sec, uint8_t *Off, Defined *Sym) { - // Don't apply section relative relocations to absolute symbols in codeview - // debug info sections. MSVC does not treat such relocations as fatal errors, - // and they can be found in the standard library for linker-provided symbols - // like __guard_fids_table and __safe_se_handler_table. - if (!(isa<DefinedAbsolute>(Sym) && Sec->isCodeView())) - add32(Off, Sym->getSecrel()); +static void applySecRel(const SectionChunk *Sec, uint8_t *Off, + OutputSection *OS, uint64_t S) { + if (!OS) { + if (Sec->isCodeView()) + return; + fatal("SECREL relocation cannot be applied to absolute symbols"); + } + uint64_t SecRel = S - OS->getRVA(); + assert(SecRel < INT32_MAX && "overflow in SECREL relocation"); + add32(Off, SecRel); +} + +static void applySecIdx(uint8_t *Off, OutputSection *OS) { + // If we have no output section, this must be an absolute symbol. Use the + // sentinel absolute symbol section index. + uint16_t SecIdx = OS ? OS->SectionIndex : DefinedAbsolute::OutputSectionIndex; + add16(Off, SecIdx); } -void SectionChunk::applyRelX64(uint8_t *Off, uint16_t Type, Defined *Sym, - uint64_t P) const { - uint64_t S = Sym->getRVA(); +void SectionChunk::applyRelX64(uint8_t *Off, uint16_t Type, OutputSection *OS, + uint64_t S, uint64_t P) const { switch (Type) { case IMAGE_REL_AMD64_ADDR32: add32(Off, S + Config->ImageBase); break; case IMAGE_REL_AMD64_ADDR64: add64(Off, S + Config->ImageBase); break; @@ -74,23 +84,22 @@ void SectionChunk::applyRelX64(uint8_t *Off, uint16_t Type, Defined *Sym, case IMAGE_REL_AMD64_REL32_3: add32(Off, S - P - 7); break; case IMAGE_REL_AMD64_REL32_4: add32(Off, S - P - 8); break; case IMAGE_REL_AMD64_REL32_5: add32(Off, S - P - 9); break; - case IMAGE_REL_AMD64_SECTION: add16(Off, Sym->getSectionIndex()); break; - case IMAGE_REL_AMD64_SECREL: applySecRel(this, Off, Sym); break; + case IMAGE_REL_AMD64_SECTION: applySecIdx(Off, OS); break; + case IMAGE_REL_AMD64_SECREL: applySecRel(this, Off, OS, S); break; default: fatal("unsupported relocation type 0x" + Twine::utohexstr(Type)); } } -void SectionChunk::applyRelX86(uint8_t *Off, uint16_t Type, Defined *Sym, - uint64_t P) const { - uint64_t S = Sym->getRVA(); +void SectionChunk::applyRelX86(uint8_t *Off, uint16_t Type, OutputSection *OS, + uint64_t S, uint64_t P) const { switch (Type) { case IMAGE_REL_I386_ABSOLUTE: break; case IMAGE_REL_I386_DIR32: add32(Off, S + Config->ImageBase); break; case IMAGE_REL_I386_DIR32NB: add32(Off, S); break; case IMAGE_REL_I386_REL32: add32(Off, S - P - 4); break; - case IMAGE_REL_I386_SECTION: add16(Off, Sym->getSectionIndex()); break; - case IMAGE_REL_I386_SECREL: applySecRel(this, Off, Sym); break; + case IMAGE_REL_I386_SECTION: applySecIdx(Off, OS); break; + case IMAGE_REL_I386_SECREL: applySecRel(this, Off, OS, S); break; default: fatal("unsupported relocation type 0x" + Twine::utohexstr(Type)); } @@ -137,20 +146,21 @@ static void applyBranch24T(uint8_t *Off, int32_t V) { write16le(Off + 2, (read16le(Off + 2) & 0xd000) | (J1 << 13) | (J2 << 11) | ((V >> 1) & 0x7ff)); } -void SectionChunk::applyRelARM(uint8_t *Off, uint16_t Type, Defined *Sym, - uint64_t P) const { - uint64_t S = Sym->getRVA(); +void SectionChunk::applyRelARM(uint8_t *Off, uint16_t Type, OutputSection *OS, + uint64_t S, uint64_t P) const { // Pointer to thumb code must have the LSB set. - if (Sym->isExecutable()) - S |= 1; + uint64_t SX = S; + if (OS && (OS->getPermissions() & IMAGE_SCN_MEM_EXECUTE)) + SX |= 1; switch (Type) { - case IMAGE_REL_ARM_ADDR32: add32(Off, S + Config->ImageBase); break; - case IMAGE_REL_ARM_ADDR32NB: add32(Off, S); break; - case IMAGE_REL_ARM_MOV32T: applyMOV32T(Off, S + Config->ImageBase); break; - case IMAGE_REL_ARM_BRANCH20T: applyBranch20T(Off, S - P - 4); break; - case IMAGE_REL_ARM_BRANCH24T: applyBranch24T(Off, S - P - 4); break; - case IMAGE_REL_ARM_BLX23T: applyBranch24T(Off, S - P - 4); break; - case IMAGE_REL_ARM_SECREL: applySecRel(this, Off, Sym); break; + case IMAGE_REL_ARM_ADDR32: add32(Off, SX + Config->ImageBase); break; + case IMAGE_REL_ARM_ADDR32NB: add32(Off, SX); break; + case IMAGE_REL_ARM_MOV32T: applyMOV32T(Off, SX + Config->ImageBase); break; + case IMAGE_REL_ARM_BRANCH20T: applyBranch20T(Off, SX - P - 4); break; + case IMAGE_REL_ARM_BRANCH24T: applyBranch24T(Off, SX - P - 4); break; + case IMAGE_REL_ARM_BLX23T: applyBranch24T(Off, SX - P - 4); break; + case IMAGE_REL_ARM_SECTION: applySecIdx(Off, OS); break; + case IMAGE_REL_ARM_SECREL: applySecRel(this, Off, OS, S); break; default: fatal("unsupported relocation type 0x" + Twine::utohexstr(Type)); } @@ -166,18 +176,39 @@ void SectionChunk::writeTo(uint8_t *Buf) const { // Apply relocations. for (const coff_relocation &Rel : Relocs) { uint8_t *Off = Buf + OutputSectionOff + Rel.VirtualAddress; + + // Get the output section of the symbol for this relocation. The output + // section is needed to compute SECREL and SECTION relocations used in debug + // info. SymbolBody *Body = File->getSymbolBody(Rel.SymbolTableIndex); Defined *Sym = cast<Defined>(Body); + Chunk *C = Sym->getChunk(); + OutputSection *OS = C ? C->getOutputSection() : nullptr; + + // Only absolute and __ImageBase symbols lack an output section. For any + // other symbol, this indicates that the chunk was discarded. Normally + // relocations against discarded sections are an error. However, debug info + // sections are not GC roots and can end up with these kinds of relocations. + // Skip these relocations. + if (!OS && !isa<DefinedAbsolute>(Sym) && !isa<DefinedSynthetic>(Sym)) { + if (isCodeView()) + continue; + fatal("relocation against symbol in discarded section: " + + Sym->getName()); + } + uint64_t S = Sym->getRVA(); + + // Compute the RVA of the relocation for relative relocations. uint64_t P = RVA + Rel.VirtualAddress; switch (Config->Machine) { case AMD64: - applyRelX64(Off, Rel.Type, Sym, P); + applyRelX64(Off, Rel.Type, OS, S, P); break; case I386: - applyRelX86(Off, Rel.Type, Sym, P); + applyRelX86(Off, Rel.Type, OS, S, P); break; case ARMNT: - applyRelARM(Off, Rel.Type, Sym, P); + applyRelARM(Off, Rel.Type, OS, S, P); break; default: llvm_unreachable("unknown machine type"); diff --git a/contrib/llvm/tools/lld/COFF/Chunks.h b/contrib/llvm/tools/lld/COFF/Chunks.h index 54fffc5f6d08..6e1bf94da1a5 100644 --- a/contrib/llvm/tools/lld/COFF/Chunks.h +++ b/contrib/llvm/tools/lld/COFF/Chunks.h @@ -145,9 +145,12 @@ public: StringRef getSectionName() const override { return SectionName; } void getBaserels(std::vector<Baserel> *Res) override; bool isCOMDAT() const; - void applyRelX64(uint8_t *Off, uint16_t Type, Defined *Sym, uint64_t P) const; - void applyRelX86(uint8_t *Off, uint16_t Type, Defined *Sym, uint64_t P) const; - void applyRelARM(uint8_t *Off, uint16_t Type, Defined *Sym, uint64_t P) const; + void applyRelX64(uint8_t *Off, uint16_t Type, OutputSection *OS, uint64_t S, + uint64_t P) const; + void applyRelX86(uint8_t *Off, uint16_t Type, OutputSection *OS, uint64_t S, + uint64_t P) const; + void applyRelARM(uint8_t *Off, uint16_t Type, OutputSection *OS, uint64_t S, + uint64_t P) const; // Called if the garbage collector decides to not include this chunk // in a final output. It's supposed to print out a log message to stdout. diff --git a/contrib/llvm/tools/lld/COFF/Driver.h b/contrib/llvm/tools/lld/COFF/Driver.h index 2b5d1e7ae28b..6879be2eb0c7 100644 --- a/contrib/llvm/tools/lld/COFF/Driver.h +++ b/contrib/llvm/tools/lld/COFF/Driver.h @@ -34,7 +34,6 @@ extern LinkerDriver *Driver; using llvm::COFF::MachineTypes; using llvm::COFF::WindowsSubsystem; using llvm::Optional; -class InputFile; // Implemented in MarkLive.cpp. void markLive(const std::vector<Chunk *> &Chunks); diff --git a/contrib/llvm/tools/lld/COFF/MarkLive.cpp b/contrib/llvm/tools/lld/COFF/MarkLive.cpp index 25e5cc350673..a2756e5c89e0 100644 --- a/contrib/llvm/tools/lld/COFF/MarkLive.cpp +++ b/contrib/llvm/tools/lld/COFF/MarkLive.cpp @@ -52,6 +52,13 @@ void markLive(const std::vector<Chunk *> &Chunks) { while (!Worklist.empty()) { SectionChunk *SC = Worklist.pop_back_val(); + + // If this section was discarded, there are relocations referring to + // discarded sections. Ignore these sections to avoid crashing. They will be + // diagnosed during relocation processing. + if (SC->isDiscarded()) + continue; + assert(SC->isLive() && "We mark as live when pushing onto the worklist!"); // Mark all symbols listed in the relocation table for this section. diff --git a/contrib/llvm/tools/lld/COFF/Symbols.h b/contrib/llvm/tools/lld/COFF/Symbols.h index 8c1390c45876..a12ae1c01e07 100644 --- a/contrib/llvm/tools/lld/COFF/Symbols.h +++ b/contrib/llvm/tools/lld/COFF/Symbols.h @@ -110,17 +110,9 @@ public: // writer sets and uses RVAs. uint64_t getRVA(); - // Returns the RVA relative to the beginning of the output section. - // Used to implement SECREL relocation type. - uint32_t getSecrel(); - - // Returns the output section index. - // Used to implement SECTION relocation type. - uint16_t getSectionIndex(); - - // Returns true if this symbol points to an executable (e.g. .text) section. - // Used to implement ARM relocations. - bool isExecutable(); + // Returns the chunk containing this symbol. Absolute symbols and __ImageBase + // do not have chunks, so this may return null. + Chunk *getChunk(); }; // Symbols defined via a COFF object file or bitcode file. For COFF files, this @@ -167,7 +159,6 @@ public: bool isCOMDAT() { return IsCOMDAT; } SectionChunk *getChunk() { return *Data; } uint32_t getValue() { return Sym->Value; } - uint32_t getSecrel(); private: SectionChunk **Data; @@ -187,8 +178,7 @@ public: } uint64_t getRVA() { return Data->getRVA(); } - uint32_t getSecrel() { return Data->OutputSectionOff; } - uint16_t getSectionIndex(); + Chunk *getChunk() { return Data; } private: friend SymbolTable; @@ -219,6 +209,7 @@ public: // against absolute symbols resolve to this 16 bit number, and it is the // largest valid section index plus one. This is written by the Writer. static uint16_t OutputSectionIndex; + uint16_t getSecIdx() { return OutputSectionIndex; } private: uint64_t VA; @@ -237,9 +228,8 @@ public: // A null chunk indicates that this is __ImageBase. Otherwise, this is some // other synthesized chunk, like SEHTableChunk. - uint32_t getRVA() const { return C ? C->getRVA() : 0; } - uint32_t getSecrel() const { return C ? C->OutputSectionOff : 0; } - Chunk *getChunk() const { return C; } + uint32_t getRVA() { return C ? C->getRVA() : 0; } + Chunk *getChunk() { return C; } private: Chunk *C; @@ -304,9 +294,11 @@ public: } uint64_t getRVA() { return File->Location->getRVA(); } + Chunk *getChunk() { return File->Location; } + void setLocation(Chunk *AddressTable) { File->Location = AddressTable; } + StringRef getDLLName() { return File->DLLName; } StringRef getExternalName() { return File->ExternalName; } - void setLocation(Chunk *AddressTable) { File->Location = AddressTable; } uint16_t getOrdinal() { return File->Hdr->OrdinalHint; } ImportFile *File; @@ -378,6 +370,29 @@ inline uint64_t Defined::getRVA() { llvm_unreachable("unknown symbol kind"); } +inline Chunk *Defined::getChunk() { + switch (kind()) { + case DefinedRegularKind: + return cast<DefinedRegular>(this)->getChunk(); + case DefinedAbsoluteKind: + return nullptr; + case DefinedSyntheticKind: + return cast<DefinedSynthetic>(this)->getChunk(); + case DefinedImportDataKind: + return cast<DefinedImportData>(this)->getChunk(); + case DefinedImportThunkKind: + return cast<DefinedImportThunk>(this)->getChunk(); + case DefinedLocalImportKind: + return cast<DefinedLocalImport>(this)->getChunk(); + case DefinedCommonKind: + return cast<DefinedCommon>(this)->getChunk(); + case LazyKind: + case UndefinedKind: + llvm_unreachable("Cannot get the chunk of an undefined symbol."); + } + llvm_unreachable("unknown symbol kind"); +} + // A real symbol object, SymbolBody, is usually stored within a Symbol. There's // always one Symbol for each symbol name. The resolver updates the SymbolBody // stored in the Body field of this object as it resolves symbols. Symbol also diff --git a/contrib/llvm/tools/lld/COFF/Writer.cpp b/contrib/llvm/tools/lld/COFF/Writer.cpp index d32577b361fa..4cf718a48d8b 100644 --- a/contrib/llvm/tools/lld/COFF/Writer.cpp +++ b/contrib/llvm/tools/lld/COFF/Writer.cpp @@ -120,7 +120,6 @@ private: void writeSections(); void sortExceptionTable(); void writeBuildId(); - void applyRelocations(); llvm::Optional<coff_symbol16> createSymbol(Defined *D); size_t addEntryToStringTable(StringRef Str); @@ -210,55 +209,6 @@ void OutputSection::writeHeaderTo(uint8_t *Buf) { } } -uint32_t Defined::getSecrel() { - assert(this); - switch (kind()) { - case DefinedRegularKind: - return cast<DefinedRegular>(this)->getSecrel(); - case DefinedCommonKind: - return cast<DefinedCommon>(this)->getSecrel(); - case DefinedSyntheticKind: - return cast<DefinedSynthetic>(this)->getSecrel(); - default: - break; - } - fatal("SECREL relocation points to a non-regular symbol: " + toString(*this)); -} - -uint32_t DefinedRegular::getSecrel() { - assert(getChunk()->isLive() && "relocation against discarded section"); - uint64_t Diff = getRVA() - getChunk()->getOutputSection()->getRVA(); - assert(Diff < UINT32_MAX && "section offset too large"); - return (uint32_t)Diff; -} - -uint16_t Defined::getSectionIndex() { - if (auto *D = dyn_cast<DefinedRegular>(this)) - return D->getChunk()->getOutputSection()->SectionIndex; - if (isa<DefinedAbsolute>(this)) - return DefinedAbsolute::OutputSectionIndex; - if (auto *D = dyn_cast<DefinedCommon>(this)) - return D->getSectionIndex(); - if (auto *D = dyn_cast<DefinedSynthetic>(this)) { - if (!D->getChunk()) - return 0; - return D->getChunk()->getOutputSection()->SectionIndex; - } - fatal("SECTION relocation points to a non-regular symbol: " + - toString(*this)); -} - -uint16_t DefinedCommon::getSectionIndex() { - return Data->getOutputSection()->SectionIndex; -} - -bool Defined::isExecutable() { - const auto X = IMAGE_SCN_MEM_EXECUTE; - if (auto *D = dyn_cast<DefinedRegular>(this)) - return D->getChunk()->getOutputSection()->getPermissions() & X; - return isa<DefinedImportThunk>(this); -} - } // namespace coff } // namespace lld diff --git a/contrib/llvm/tools/lld/ELF/Arch/SPARCV9.cpp b/contrib/llvm/tools/lld/ELF/Arch/SPARCV9.cpp new file mode 100644 index 000000000000..1f977c1e9cf2 --- /dev/null +++ b/contrib/llvm/tools/lld/ELF/Arch/SPARCV9.cpp @@ -0,0 +1,149 @@ +//===- SPARCV9.cpp --------------------------------------------------------===// +// +// The LLVM Linker +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "Error.h" +#include "InputFiles.h" +#include "Symbols.h" +#include "SyntheticSections.h" +#include "Target.h" +#include "llvm/Support/Endian.h" + +using namespace llvm; +using namespace llvm::support::endian; +using namespace llvm::ELF; +using namespace lld; +using namespace lld::elf; + +namespace { +class SPARCV9 final : public TargetInfo { +public: + SPARCV9(); + RelExpr getRelExpr(uint32_t Type, const SymbolBody &S, + const uint8_t *Loc) const override; + void writePlt(uint8_t *Buf, uint64_t GotEntryAddr, uint64_t PltEntryAddr, + int32_t Index, unsigned RelOff) const override; + void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override; +}; +} // namespace + +SPARCV9::SPARCV9() { + CopyRel = R_SPARC_COPY; + GotRel = R_SPARC_GLOB_DAT; + PltRel = R_SPARC_JMP_SLOT; + RelativeRel = R_SPARC_RELATIVE; + GotEntrySize = 8; + PltEntrySize = 32; + PltHeaderSize = 4 * PltEntrySize; + + PageSize = 8192; + DefaultMaxPageSize = 0x100000; + DefaultImageBase = 0x100000; +} + +RelExpr SPARCV9::getRelExpr(uint32_t Type, const SymbolBody &S, + const uint8_t *Loc) const { + switch (Type) { + case R_SPARC_32: + case R_SPARC_UA32: + case R_SPARC_64: + case R_SPARC_UA64: + return R_ABS; + case R_SPARC_PC10: + case R_SPARC_PC22: + case R_SPARC_DISP32: + case R_SPARC_WDISP30: + return R_PC; + case R_SPARC_GOT10: + return R_GOT_OFF; + case R_SPARC_GOT22: + return R_GOT_OFF; + case R_SPARC_WPLT30: + return R_PLT_PC; + case R_SPARC_NONE: + return R_NONE; + default: + error(toString(S.File) + ": unknown relocation type: " + toString(Type)); + return R_HINT; + } +} + +void SPARCV9::relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const { + switch (Type) { + case R_SPARC_32: + case R_SPARC_UA32: + // V-word32 + checkUInt<32>(Loc, Val, Type); + write32be(Loc, Val); + break; + case R_SPARC_DISP32: + // V-disp32 + checkInt<32>(Loc, Val, Type); + write32be(Loc, Val); + break; + case R_SPARC_WDISP30: + case R_SPARC_WPLT30: + // V-disp30 + checkInt<32>(Loc, Val, Type); + write32be(Loc, (read32be(Loc) & ~0x3fffffff) | ((Val >> 2) & 0x3fffffff)); + break; + case R_SPARC_22: + // V-imm22 + checkUInt<22>(Loc, Val, Type); + write32be(Loc, (read32be(Loc) & ~0x003fffff) | (Val & 0x003fffff)); + break; + case R_SPARC_GOT22: + case R_SPARC_PC22: + // T-imm22 + write32be(Loc, (read32be(Loc) & ~0x003fffff) | ((Val >> 10) & 0x003fffff)); + break; + case R_SPARC_WDISP19: + // V-disp19 + checkInt<21>(Loc, Val, Type); + write32be(Loc, (read32be(Loc) & ~0x0007ffff) | ((Val >> 2) & 0x0007ffff)); + break; + case R_SPARC_GOT10: + case R_SPARC_PC10: + // T-simm10 + write32be(Loc, (read32be(Loc) & ~0x000003ff) | (Val & 0x000003ff)); + break; + case R_SPARC_64: + case R_SPARC_UA64: + case R_SPARC_GLOB_DAT: + // V-xword64 + write64be(Loc, Val); + break; + default: + error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type)); + } +} + +void SPARCV9::writePlt(uint8_t *Buf, uint64_t GotEntryAddr, + uint64_t PltEntryAddr, int32_t Index, + unsigned RelOff) const { + const uint8_t PltData[] = { + 0x03, 0x00, 0x00, 0x00, // sethi (. - .PLT0), %g1 + 0x30, 0x68, 0x00, 0x00, // ba,a %xcc, .PLT1 + 0x01, 0x00, 0x00, 0x00, // nop + 0x01, 0x00, 0x00, 0x00, // nop + 0x01, 0x00, 0x00, 0x00, // nop + 0x01, 0x00, 0x00, 0x00, // nop + 0x01, 0x00, 0x00, 0x00, // nop + 0x01, 0x00, 0x00, 0x00 // nop + }; + memcpy(Buf, PltData, sizeof(PltData)); + + uint64_t Off = PltHeaderSize + Index * PltEntrySize; + relocateOne(Buf, R_SPARC_22, Off); + relocateOne(Buf + 4, R_SPARC_WDISP19, -(Off + 4 - PltEntrySize)); +} + +TargetInfo *elf::getSPARCV9TargetInfo() { + static SPARCV9 Target; + return &Target; +} diff --git a/contrib/llvm/tools/lld/ELF/CMakeLists.txt b/contrib/llvm/tools/lld/ELF/CMakeLists.txt index b4bc215a77eb..77243bd494d1 100644 --- a/contrib/llvm/tools/lld/ELF/CMakeLists.txt +++ b/contrib/llvm/tools/lld/ELF/CMakeLists.txt @@ -15,6 +15,7 @@ add_lld_library(lldELF Arch/MipsArchTree.cpp Arch/PPC.cpp Arch/PPC64.cpp + Arch/SPARCV9.cpp Arch/X86.cpp Arch/X86_64.cpp Driver.cpp diff --git a/contrib/llvm/tools/lld/ELF/InputFiles.cpp b/contrib/llvm/tools/lld/ELF/InputFiles.cpp index 1ff0b4224e70..e07f24d665df 100644 --- a/contrib/llvm/tools/lld/ELF/InputFiles.cpp +++ b/contrib/llvm/tools/lld/ELF/InputFiles.cpp @@ -79,9 +79,9 @@ template <class ELFT> void elf::ObjectFile<ELFT>::initializeDwarfLine() { ObjectInfo ObjInfo; DWARFContextInMemory Dwarf(*Obj, &ObjInfo); - DwarfLine.reset(new DWARFDebugLine(&Dwarf.getLineSection().Relocs)); - DataExtractor LineData(Dwarf.getLineSection().Data, Config->IsLE, - Config->Wordsize); + DwarfLine.reset(new DWARFDebugLine); + DWARFDataExtractor LineData(Dwarf.getLineSection(), Config->IsLE, + Config->Wordsize); // The second parameter is offset in .debug_line section // for compilation unit (CU) of interest. We have only one diff --git a/contrib/llvm/tools/lld/ELF/SymbolTable.cpp b/contrib/llvm/tools/lld/ELF/SymbolTable.cpp index ab8802c86d8e..d75b89f17527 100644 --- a/contrib/llvm/tools/lld/ELF/SymbolTable.cpp +++ b/contrib/llvm/tools/lld/ELF/SymbolTable.cpp @@ -195,14 +195,8 @@ template <class ELFT> void SymbolTable<ELFT>::applySymbolRenames() { for (auto &KV : Config->RenamedSymbols) { Symbol *Dst = KV.first; Symbol *Src = KV.second.Target; + Dst->body()->copy(Src->body()); Dst->Binding = KV.second.OriginalBinding; - - // We rename symbols by replacing the old symbol's SymbolBody with - // the new symbol's SymbolBody. The only attribute we want to keep - // is the symbol name, so that two symbols don't have the same name. - StringRef S = Dst->body()->getName(); - memcpy(Dst->Body.buffer, Src->Body.buffer, sizeof(Symbol::Body)); - Dst->body()->setName(S); } } @@ -718,15 +712,31 @@ void SymbolTable<ELFT>::assignWildcardVersion(SymbolVersion Ver, B->symbol()->VersionId = VersionId; } +static bool isDefaultVersion(SymbolBody *B) { + return B->isInCurrentDSO() && B->getName().find("@@") != StringRef::npos; +} + // This function processes version scripts by updating VersionId // member of symbols. template <class ELFT> void SymbolTable<ELFT>::scanVersionScript() { // Symbol themselves might know their versions because symbols // can contain versions in the form of <name>@<version>. - // Let them parse their names. - if (!Config->VersionDefinitions.empty()) - for (Symbol *Sym : SymVector) - Sym->body()->parseSymbolVersion(); + // Let them parse and update their names to exclude version suffix. + for (Symbol *Sym : SymVector) { + SymbolBody *Body = Sym->body(); + bool IsDefault = isDefaultVersion(Body); + Body->parseSymbolVersion(); + + if (!IsDefault) + continue; + + // <name>@@<version> means the symbol is the default version. If that's the + // case, the symbol is not used only to resolve <name> of version <version> + // but also undefined unversioned symbols with name <name>. + SymbolBody *S = find(Body->getName()); + if (S && S->isUndefined()) + S->copy(Body); + } // Handle edge cases first. handleAnonymousVersion(); diff --git a/contrib/llvm/tools/lld/ELF/SymbolTable.h b/contrib/llvm/tools/lld/ELF/SymbolTable.h index 316d9c9bf373..4ba101fa5d50 100644 --- a/contrib/llvm/tools/lld/ELF/SymbolTable.h +++ b/contrib/llvm/tools/lld/ELF/SymbolTable.h @@ -18,7 +18,7 @@ namespace lld { namespace elf { -class Lazy; + struct Symbol; // SymbolTable is a bucket of all known symbols, including defined, diff --git a/contrib/llvm/tools/lld/ELF/Symbols.cpp b/contrib/llvm/tools/lld/ELF/Symbols.cpp index 5dce71a32c9c..e8cd662c69ac 100644 --- a/contrib/llvm/tools/lld/ELF/Symbols.cpp +++ b/contrib/llvm/tools/lld/ELF/Symbols.cpp @@ -159,6 +159,21 @@ bool SymbolBody::isPreemptible() const { return true; } +// Overwrites all attributes except symbol name with Other's so that +// this symbol becomes an alias to Other. This is useful for handling +// some options such as --wrap. +// +// The reason why we want to keep the symbol name is because, if we +// copy symbol names, we'll end up having symbol tables in resulting +// executables or DSOs containing two or more identical symbols, which +// is just inconvenient. +void SymbolBody::copy(SymbolBody *Other) { + StringRef S = Name; + memcpy(symbol()->Body.buffer, Other->symbol()->Body.buffer, + sizeof(Symbol::Body)); + Name = S; +} + uint64_t SymbolBody::getVA(int64_t Addend) const { uint64_t OutVA = getSymVA(*this, Addend); return OutVA + Addend; diff --git a/contrib/llvm/tools/lld/ELF/Symbols.h b/contrib/llvm/tools/lld/ELF/Symbols.h index 406fd8e0f57b..773e1ad9588a 100644 --- a/contrib/llvm/tools/lld/ELF/Symbols.h +++ b/contrib/llvm/tools/lld/ELF/Symbols.h @@ -69,9 +69,9 @@ public: bool isLocal() const { return IsLocal; } bool isPreemptible() const; StringRef getName() const { return Name; } - void setName(StringRef S) { Name = S; } uint8_t getVisibility() const { return StOther & 0x3; } void parseSymbolVersion(); + void copy(SymbolBody *Other); bool isInGot() const { return GotIndex != -1U; } bool isInPlt() const { return PltIndex != -1U; } diff --git a/contrib/llvm/tools/lld/ELF/SyntheticSections.cpp b/contrib/llvm/tools/lld/ELF/SyntheticSections.cpp index cb1494d427a0..995d05692ee2 100644 --- a/contrib/llvm/tools/lld/ELF/SyntheticSections.cpp +++ b/contrib/llvm/tools/lld/ELF/SyntheticSections.cpp @@ -1090,8 +1090,17 @@ template <class ELFT> void DynamicSection<ELFT>::finalizeContents() { if (In<ELFT>::RelaPlt->getParent()->Size > 0) { add({DT_JMPREL, In<ELFT>::RelaPlt}); add({DT_PLTRELSZ, In<ELFT>::RelaPlt->getParent()->Size}); - add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT, - InX::GotPlt}); + switch (Config->EMachine) { + case EM_MIPS: + add({DT_MIPS_PLTGOT, In<ELFT>::GotPlt}); + break; + case EM_SPARCV9: + add({DT_PLTGOT, In<ELFT>::Plt}); + break; + default: + add({DT_PLTGOT, In<ELFT>::GotPlt}); + break; + } add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)}); } @@ -1376,7 +1385,6 @@ template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) { } ESym->st_name = Ent.StrTabOffset; - ESym->st_size = Body->getSize<ELFT>(); // Set a section index. if (const OutputSection *OutSec = Body->getOutputSection()) @@ -1386,6 +1394,14 @@ template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) { else if (isa<DefinedCommon>(Body)) ESym->st_shndx = SHN_COMMON; + // Copy symbol size if it is a defined symbol. st_size is not significant + // for undefined symbols, so whether copying it or not is up to us if that's + // the case. We'll leave it as zero because by not setting a value, we can + // get the exact same outputs for two sets of input files that differ only + // in undefined symbol size in DSOs. + if (ESym->st_shndx != SHN_UNDEF) + ESym->st_size = Body->getSize<ELFT>(); + // st_value is usually an address of a symbol, but that has a // special meaining for uninstantiated common symbols (this can // occur if -r is given). @@ -1625,7 +1641,12 @@ template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) { PltSection::PltSection(size_t S) : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"), - HeaderSize(S) {} + HeaderSize(S) { + // The PLT needs to be writable on SPARC as the dynamic linker will + // modify the instructions in the PLT entries. + if (Config->EMachine == EM_SPARCV9) + this->Flags |= SHF_WRITE; +} void PltSection::writeTo(uint8_t *Buf) { // At beginning of PLT but not the IPLT, we have code to call the dynamic diff --git a/contrib/llvm/tools/lld/ELF/Target.cpp b/contrib/llvm/tools/lld/ELF/Target.cpp index c1a85e165258..c886419971bc 100644 --- a/contrib/llvm/tools/lld/ELF/Target.cpp +++ b/contrib/llvm/tools/lld/ELF/Target.cpp @@ -77,6 +77,8 @@ TargetInfo *elf::getTarget() { return getPPCTargetInfo(); case EM_PPC64: return getPPC64TargetInfo(); + case EM_SPARCV9: + return getSPARCV9TargetInfo(); case EM_X86_64: if (Config->EKind == ELF32LEKind) return getX32TargetInfo(); diff --git a/contrib/llvm/tools/lld/ELF/Target.h b/contrib/llvm/tools/lld/ELF/Target.h index bf703fd0086a..5914d9bbb7ef 100644 --- a/contrib/llvm/tools/lld/ELF/Target.h +++ b/contrib/llvm/tools/lld/ELF/Target.h @@ -112,6 +112,7 @@ TargetInfo *getARMTargetInfo(); TargetInfo *getAVRTargetInfo(); TargetInfo *getPPC64TargetInfo(); TargetInfo *getPPCTargetInfo(); +TargetInfo *getSPARCV9TargetInfo(); TargetInfo *getX32TargetInfo(); TargetInfo *getX86TargetInfo(); TargetInfo *getX86_64TargetInfo(); diff --git a/contrib/llvm/tools/lld/ELF/Writer.cpp b/contrib/llvm/tools/lld/ELF/Writer.cpp index 4c12b18836bf..080d8e787301 100644 --- a/contrib/llvm/tools/lld/ELF/Writer.cpp +++ b/contrib/llvm/tools/lld/ELF/Writer.cpp @@ -104,7 +104,7 @@ StringRef elf::getOutputSectionName(StringRef Name) { for (StringRef V : {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.", ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.", - ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) { + ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) { StringRef Prefix = V.drop_back(); if (Name.startswith(V) || Name == Prefix) return Prefix; @@ -1014,14 +1014,14 @@ findOrphanPos(std::vector<BaseCommand *>::iterator B, } template <class ELFT> void Writer<ELFT>::sortSections() { + if (Script->Opt.HasSections) + Script->adjustSectionsBeforeSorting(); + // Don't sort if using -r. It is not necessary and we want to preserve the // relative order for SHF_LINK_ORDER sections. if (Config->Relocatable) return; - if (Script->Opt.HasSections) - Script->adjustSectionsBeforeSorting(); - for (BaseCommand *Base : Script->Opt.Commands) if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) if (OutputSection *Sec = Cmd->Sec) diff --git a/contrib/llvm/tools/lld/lib/ReaderWriter/MachO/MachONormalizedFileYAML.cpp b/contrib/llvm/tools/lld/lib/ReaderWriter/MachO/MachONormalizedFileYAML.cpp index fe67fc88c467..5233e42e5fc5 100644 --- a/contrib/llvm/tools/lld/lib/ReaderWriter/MachO/MachONormalizedFileYAML.cpp +++ b/contrib/llvm/tools/lld/lib/ReaderWriter/MachO/MachONormalizedFileYAML.cpp @@ -44,7 +44,6 @@ LLVM_YAML_IS_SEQUENCE_VECTOR(DependentDylib) LLVM_YAML_IS_SEQUENCE_VECTOR(RebaseLocation) LLVM_YAML_IS_SEQUENCE_VECTOR(BindLocation) LLVM_YAML_IS_SEQUENCE_VECTOR(Export) -LLVM_YAML_IS_SEQUENCE_VECTOR(StringRef) LLVM_YAML_IS_SEQUENCE_VECTOR(DataInCode) diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Breakpoint.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Breakpoint.h index 408647c3b5da..41241334dcf9 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Breakpoint.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Breakpoint.h @@ -26,8 +26,8 @@ #include "lldb/Breakpoint/Stoppoint.h" #include "lldb/Core/Event.h" #include "lldb/Core/SearchFilter.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Utility/StringList.h" +#include "lldb/Utility/StructuredData.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointOptions.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointOptions.h index 4ed8469eba3d..420d5915fd44 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointOptions.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointOptions.h @@ -17,9 +17,9 @@ // Other libraries and framework includes // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Utility/Baton.h" #include "lldb/Utility/StringList.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Event.h b/contrib/llvm/tools/lldb/include/lldb/Core/Event.h index 5d297a719e73..f4c7f4769a37 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Event.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/Event.h @@ -11,9 +11,9 @@ #define liblldb_Event_h_ #include "lldb/Core/Broadcaster.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Host/Predicate.h" #include "lldb/Utility/ConstString.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-defines.h" // for DISALLOW_COPY_AND_ASSIGN #include "lldb/lldb-forward.h" // for EventDataSP, ProcessSP, Struct... diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/SearchFilter.h b/contrib/llvm/tools/lldb/include/lldb/Core/SearchFilter.h index 06fb94d8fbdf..5861afc801cb 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/SearchFilter.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/SearchFilter.h @@ -11,7 +11,7 @@ #define liblldb_SearchFilter_h_ #include "lldb/Core/FileSpecList.h" -#include "lldb/Core/StructuredData.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/Utility/FileSpec.h" // for FileSpec #include "lldb/lldb-forward.h" // for SearchFilterSP, TargetSP, Modu... diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/StructuredDataImpl.h b/contrib/llvm/tools/lldb/include/lldb/Core/StructuredDataImpl.h index 92f0417b354a..819d1d9e5d2f 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/StructuredDataImpl.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/StructuredDataImpl.h @@ -11,10 +11,10 @@ #define liblldb_StructuredDataImpl_h_ #include "lldb/Core/Event.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Target/StructuredDataPlugin.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-enumerations.h" #include "lldb/lldb-forward.h" #include "llvm/ADT/StringRef.h" diff --git a/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSummary.h b/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSummary.h index a4d51b065480..1bde565aa5c8 100644 --- a/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSummary.h +++ b/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSummary.h @@ -24,8 +24,8 @@ #include "lldb/lldb-public.h" #include "lldb/Core/FormatEntity.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Utility/Status.h" +#include "lldb/Utility/StructuredData.h" namespace lldb_private { class TypeSummaryOptions { diff --git a/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSynthetic.h b/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSynthetic.h index 6f5a8df585b6..59fb6d3fcdbb 100644 --- a/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSynthetic.h +++ b/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSynthetic.h @@ -25,8 +25,8 @@ #include "lldb/lldb-enumerations.h" #include "lldb/lldb-public.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Core/ValueObject.h" +#include "lldb/Utility/StructuredData.h" namespace lldb_private { class SyntheticChildrenFrontEnd { diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/File.h b/contrib/llvm/tools/lldb/include/lldb/Host/File.h index 560a655237f3..1dfa12ea593d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/File.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/File.h @@ -10,8 +10,8 @@ #ifndef liblldb_File_h_ #define liblldb_File_h_ -#include "lldb/Host/IOObject.h" #include "lldb/Host/PosixApi.h" +#include "lldb/Utility/IOObject.h" #include "lldb/Utility/Status.h" #include "lldb/lldb-private.h" diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/Host.h b/contrib/llvm/tools/lldb/include/lldb/Host/Host.h index bf48e207f1f2..c41e4796f532 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/Host.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/Host.h @@ -238,6 +238,9 @@ public: uint32_t line_no); static size_t GetEnvironment(StringList &env); + + static std::unique_ptr<Connection> + CreateDefaultConnection(llvm::StringRef url); }; } // namespace lldb_private diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/MainLoopBase.h b/contrib/llvm/tools/lldb/include/lldb/Host/MainLoopBase.h index 39ca9a0f0c9e..a87d262e9452 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/MainLoopBase.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/MainLoopBase.h @@ -10,12 +10,10 @@ #ifndef lldb_Host_posix_MainLoopBase_h_ #define lldb_Host_posix_MainLoopBase_h_ -#include <functional> - -#include "llvm/Support/ErrorHandling.h" - -#include "lldb/Host/IOObject.h" +#include "lldb/Utility/IOObject.h" #include "lldb/Utility/Status.h" +#include "llvm/Support/ErrorHandling.h" +#include <functional> namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/Socket.h b/contrib/llvm/tools/lldb/include/lldb/Host/Socket.h index c4233a233a89..37f468f23ce0 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/Socket.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/Socket.h @@ -15,9 +15,9 @@ #include "lldb/lldb-private.h" -#include "lldb/Host/IOObject.h" #include "lldb/Host/Predicate.h" #include "lldb/Host/SocketAddress.h" +#include "lldb/Utility/IOObject.h" #include "lldb/Utility/Status.h" #ifdef _WIN32 diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/XML.h b/contrib/llvm/tools/lldb/include/lldb/Host/XML.h index 04677625672c..96b5227305e1 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/XML.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/XML.h @@ -24,8 +24,8 @@ #include "llvm/ADT/StringRef.h" // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeProcessProtocol.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeProcessProtocol.h index c43299a1df3d..a97540499cd3 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeProcessProtocol.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeProcessProtocol.h @@ -10,10 +10,10 @@ #ifndef liblldb_NativeProcessProtocol_h_ #define liblldb_NativeProcessProtocol_h_ -#include "lldb/Core/TraceOptions.h" #include "lldb/Host/Host.h" #include "lldb/Host/MainLoop.h" #include "lldb/Utility/Status.h" +#include "lldb/Utility/TraceOptions.h" #include "lldb/lldb-private-forward.h" #include "lldb/lldb-types.h" #include "llvm/ADT/ArrayRef.h" @@ -333,7 +333,7 @@ public: //------------------------------------------------------------------ /// StopTracing API as the name suggests stops a tracing instance. /// - /// @param[in] uid + /// @param[in] traceid /// The user id of the trace intended to be stopped. Now a /// user_id may map to multiple threads in which case this API /// could be used to stop the tracing for a specific thread by @@ -346,7 +346,7 @@ public: /// @return /// Status indicating what went wrong. //------------------------------------------------------------------ - virtual Status StopTrace(lldb::user_id_t uid, + virtual Status StopTrace(lldb::user_id_t traceid, lldb::tid_t thread = LLDB_INVALID_THREAD_ID) { return Status("Not implemented"); } @@ -355,8 +355,8 @@ public: /// This API provides the trace data collected in the form of raw /// data. /// - /// @param[in] uid thread - /// The uid and thread provide the context for the trace + /// @param[in] traceid thread + /// The traceid and thread provide the context for the trace /// instance. /// /// @param[in] buffer @@ -372,7 +372,7 @@ public: /// @return /// The size of the data actually read. //------------------------------------------------------------------ - virtual Status GetData(lldb::user_id_t uid, lldb::tid_t thread, + virtual Status GetData(lldb::user_id_t traceid, lldb::tid_t thread, llvm::MutableArrayRef<uint8_t> &buffer, size_t offset = 0) { return Status("Not implemented"); @@ -382,7 +382,7 @@ public: /// Similar API as above except it aims to provide any extra data /// useful for decoding the actual trace data. //------------------------------------------------------------------ - virtual Status GetMetaData(lldb::user_id_t uid, lldb::tid_t thread, + virtual Status GetMetaData(lldb::user_id_t traceid, lldb::tid_t thread, llvm::MutableArrayRef<uint8_t> &buffer, size_t offset = 0) { return Status("Not implemented"); @@ -391,7 +391,7 @@ public: //------------------------------------------------------------------ /// API to query the TraceOptions for a given user id /// - /// @param[in] uid + /// @param[in] traceid /// The user id of the tracing instance. /// /// @param[in] config @@ -405,7 +405,7 @@ public: /// @param[out] config /// The actual configuration being used for tracing. //------------------------------------------------------------------ - virtual Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &config) { + virtual Status GetTraceConfig(lldb::user_id_t traceid, TraceOptions &config) { return Status("Not implemented"); } diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/posix/ConnectionFileDescriptorPosix.h b/contrib/llvm/tools/lldb/include/lldb/Host/posix/ConnectionFileDescriptorPosix.h index f57c93684002..b7e08eb33af7 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/posix/ConnectionFileDescriptorPosix.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/posix/ConnectionFileDescriptorPosix.h @@ -19,10 +19,10 @@ // Other libraries and framework includes // Project includes -#include "lldb/Core/Connection.h" -#include "lldb/Host/IOObject.h" #include "lldb/Host/Pipe.h" #include "lldb/Host/Predicate.h" +#include "lldb/Utility/Connection.h" +#include "lldb/Utility/IOObject.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/ScriptInterpreter.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/ScriptInterpreter.h index 01b342ae41ca..335231cb29ec 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/ScriptInterpreter.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/ScriptInterpreter.h @@ -19,8 +19,8 @@ #include "lldb/Breakpoint/BreakpointOptions.h" #include "lldb/Core/Broadcaster.h" #include "lldb/Core/PluginInterface.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Utility/Status.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/Host/PseudoTerminal.h" diff --git a/contrib/llvm/tools/lldb/include/lldb/Symbol/DWARFCallFrameInfo.h b/contrib/llvm/tools/lldb/include/lldb/Symbol/DWARFCallFrameInfo.h index 085def8ff0e5..a1bd1bc8b1c9 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Symbol/DWARFCallFrameInfo.h +++ b/contrib/llvm/tools/lldb/include/lldb/Symbol/DWARFCallFrameInfo.h @@ -34,10 +34,11 @@ namespace lldb_private { class DWARFCallFrameInfo { public: - DWARFCallFrameInfo(ObjectFile &objfile, lldb::SectionSP §ion, - lldb::RegisterKind reg_kind, bool is_eh_frame); + enum Type { EH, DWARF }; - ~DWARFCallFrameInfo(); + DWARFCallFrameInfo(ObjectFile &objfile, lldb::SectionSP §ion, Type type); + + ~DWARFCallFrameInfo() = default; // Locate an AddressRange that includes the provided Address in this // object's eh_frame/debug_info @@ -74,12 +75,20 @@ public: private: enum { CFI_AUG_MAX_SIZE = 8, CFI_HEADER_SIZE = 8 }; + enum CFIVersion { + CFI_VERSION1 = 1, // DWARF v.2 + CFI_VERSION3 = 3, // DWARF v.3 + CFI_VERSION4 = 4 // DWARF v.4, v.5 + }; struct CIE { dw_offset_t cie_offset; uint8_t version; char augmentation[CFI_AUG_MAX_SIZE]; // This is typically empty or very // short. + uint8_t address_size = sizeof(uint32_t); // The size of a target address. + uint8_t segment_size = 0; // The size of a segment selector. + uint32_t code_align; int32_t data_align; uint32_t return_addr_reg_num; @@ -134,21 +143,24 @@ private: ObjectFile &m_objfile; lldb::SectionSP m_section_sp; - lldb::RegisterKind m_reg_kind; - Flags m_flags; + Flags m_flags = 0; cie_map_t m_cie_map; DataExtractor m_cfi_data; - bool m_cfi_data_initialized; // only copy the section into the DE once + bool m_cfi_data_initialized = false; // only copy the section into the DE once FDEEntryMap m_fde_index; - bool m_fde_index_initialized; // only scan the section for FDEs once + bool m_fde_index_initialized = false; // only scan the section for FDEs once std::mutex m_fde_index_mutex; // and isolate the thread that does it - bool m_is_eh_frame; + Type m_type; CIESP ParseCIE(const uint32_t cie_offset); + + lldb::RegisterKind GetRegisterKind() const { + return m_type == EH ? lldb::eRegisterKindEHFrame : lldb::eRegisterKindDWARF; + } }; } // namespace lldb_private diff --git a/contrib/llvm/tools/lldb/include/lldb/Symbol/FuncUnwinders.h b/contrib/llvm/tools/lldb/include/lldb/Symbol/FuncUnwinders.h index a5b9b801e033..64c222cce585 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Symbol/FuncUnwinders.h +++ b/contrib/llvm/tools/lldb/include/lldb/Symbol/FuncUnwinders.h @@ -99,6 +99,13 @@ public: Thread &thread, int current_offset); + lldb::UnwindPlanSP GetDebugFrameUnwindPlan(Target &target, + int current_offset); + + lldb::UnwindPlanSP GetDebugFrameAugmentedUnwindPlan(Target &target, + Thread &thread, + int current_offset); + lldb::UnwindPlanSP GetCompactUnwindUnwindPlan(Target &target, int current_offset); @@ -126,10 +133,12 @@ private: lldb::UnwindPlanSP m_unwind_plan_assembly_sp; lldb::UnwindPlanSP m_unwind_plan_eh_frame_sp; - lldb::UnwindPlanSP m_unwind_plan_eh_frame_augmented_sp; // augmented by - // assembly inspection - // so it's valid - // everywhere + lldb::UnwindPlanSP m_unwind_plan_debug_frame_sp; + + // augmented by assembly inspection so it's valid everywhere + lldb::UnwindPlanSP m_unwind_plan_eh_frame_augmented_sp; + lldb::UnwindPlanSP m_unwind_plan_debug_frame_augmented_sp; + std::vector<lldb::UnwindPlanSP> m_unwind_plan_compact_unwind; lldb::UnwindPlanSP m_unwind_plan_arm_unwind_sp; lldb::UnwindPlanSP m_unwind_plan_fast_sp; @@ -139,7 +148,9 @@ private: // Fetching the UnwindPlans can be expensive - if we've already attempted // to get one & failed, don't try again. bool m_tried_unwind_plan_assembly : 1, m_tried_unwind_plan_eh_frame : 1, + m_tried_unwind_plan_debug_frame : 1, m_tried_unwind_plan_eh_frame_augmented : 1, + m_tried_unwind_plan_debug_frame_augmented : 1, m_tried_unwind_plan_compact_unwind : 1, m_tried_unwind_plan_arm_unwind : 1, m_tried_unwind_fast : 1, m_tried_unwind_arch_default : 1, diff --git a/contrib/llvm/tools/lldb/include/lldb/Symbol/UnwindTable.h b/contrib/llvm/tools/lldb/include/lldb/Symbol/UnwindTable.h index e730454b04d1..851d24bea03b 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Symbol/UnwindTable.h +++ b/contrib/llvm/tools/lldb/include/lldb/Symbol/UnwindTable.h @@ -27,6 +27,7 @@ public: ~UnwindTable(); lldb_private::DWARFCallFrameInfo *GetEHFrameInfo(); + lldb_private::DWARFCallFrameInfo *GetDebugFrameInfo(); lldb_private::CompactUnwindInfo *GetCompactUnwindInfo(); @@ -58,6 +59,8 @@ private: void Dump(Stream &s); void Initialize(); + llvm::Optional<AddressRange> GetAddressRange(const Address &addr, + SymbolContext &sc); typedef std::map<lldb::addr_t, lldb::FuncUnwindersSP> collection; typedef collection::iterator iterator; @@ -70,6 +73,7 @@ private: std::mutex m_mutex; std::unique_ptr<DWARFCallFrameInfo> m_eh_frame_up; + std::unique_ptr<DWARFCallFrameInfo> m_debug_frame_up; std::unique_ptr<CompactUnwindInfo> m_compact_unwind_up; std::unique_ptr<ArmUnwindInfo> m_arm_unwind_up; diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/ABI.h b/contrib/llvm/tools/lldb/include/lldb/Target/ABI.h index a8e08e1a800a..0418d683af63 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/ABI.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/ABI.h @@ -92,6 +92,16 @@ protected: virtual lldb::ValueObjectSP GetReturnValueObjectImpl(Thread &thread, llvm::Type &ir_type) const; + //------------------------------------------------------------------ + /// Request to get a Process shared pointer. + /// + /// This ABI object may not have been created with a Process object, + /// or the Process object may no longer be alive. Be sure to handle + /// the case where the shared pointer returned does not have an + /// object inside it. + //------------------------------------------------------------------ + lldb::ProcessSP GetProcessSP() const { return m_process_wp.lock(); } + public: virtual bool CreateFunctionEntryUnwindPlan(UnwindPlan &unwind_plan) = 0; @@ -131,13 +141,18 @@ public: virtual bool GetPointerReturnRegister(const char *&name) { return false; } - static lldb::ABISP FindPlugin(const ArchSpec &arch); + static lldb::ABISP FindPlugin(lldb::ProcessSP process_sp, const ArchSpec &arch); protected: //------------------------------------------------------------------ // Classes that inherit from ABI can see and modify these //------------------------------------------------------------------ - ABI(); + ABI(lldb::ProcessSP process_sp) { + if (process_sp.get()) + m_process_wp = process_sp; + } + + lldb::ProcessWP m_process_wp; private: DISALLOW_COPY_AND_ASSIGN(ABI); diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/InstrumentationRuntime.h b/contrib/llvm/tools/lldb/include/lldb/Target/InstrumentationRuntime.h index a40914d04ea9..21d66d5766a9 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/InstrumentationRuntime.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/InstrumentationRuntime.h @@ -18,7 +18,7 @@ // Other libraries and framework includes // Project includes #include "lldb/Core/PluginInterface.h" -#include "lldb/Core/StructuredData.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-forward.h" #include "lldb/lldb-private.h" #include "lldb/lldb-types.h" diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/InstrumentationRuntimeStopInfo.h b/contrib/llvm/tools/lldb/include/lldb/Target/InstrumentationRuntimeStopInfo.h index 0a4a17003d93..b11231960ac1 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/InstrumentationRuntimeStopInfo.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/InstrumentationRuntimeStopInfo.h @@ -16,8 +16,8 @@ // Other libraries and framework includes // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Target/StopInfo.h" +#include "lldb/Utility/StructuredData.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/Process.h b/contrib/llvm/tools/lldb/include/lldb/Target/Process.h index dbf6cba09f43..df09570057a1 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/Process.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/Process.h @@ -34,9 +34,7 @@ #include "lldb/Core/Listener.h" #include "lldb/Core/LoadedModuleInfoList.h" #include "lldb/Core/PluginInterface.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Core/ThreadSafeValue.h" -#include "lldb/Core/TraceOptions.h" #include "lldb/Core/UserSettingsController.h" #include "lldb/Host/HostThread.h" #include "lldb/Host/ProcessRunLock.h" @@ -50,6 +48,8 @@ #include "lldb/Target/ThreadList.h" #include "lldb/Utility/NameMatches.h" #include "lldb/Utility/Status.h" +#include "lldb/Utility/StructuredData.h" +#include "lldb/Utility/TraceOptions.h" #include "lldb/lldb-private.h" #include "llvm/ADT/ArrayRef.h" diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/StopInfo.h b/contrib/llvm/tools/lldb/include/lldb/Target/StopInfo.h index 46f34567350d..c99877cbd8ab 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/StopInfo.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/StopInfo.h @@ -16,8 +16,8 @@ // Other libraries and framework includes // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Target/Process.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-public.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/StructuredDataPlugin.h b/contrib/llvm/tools/lldb/include/lldb/Target/StructuredDataPlugin.h index a4d2c0382628..5ea265b05420 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/StructuredDataPlugin.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/StructuredDataPlugin.h @@ -11,7 +11,7 @@ #define StructuredDataPlugin_h #include "lldb/Core/PluginInterface.h" -#include "lldb/Core/StructuredData.h" +#include "lldb/Utility/StructuredData.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/SystemRuntime.h b/contrib/llvm/tools/lldb/include/lldb/Target/SystemRuntime.h index f50c9c1b4a56..8c6c2ece967f 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/SystemRuntime.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/SystemRuntime.h @@ -18,10 +18,10 @@ #include "lldb/Core/ModuleList.h" #include "lldb/Core/PluginInterface.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Target/QueueItem.h" #include "lldb/Target/QueueList.h" #include "lldb/Utility/ConstString.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private.h" #include "lldb/lldb-public.h" diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/Thread.h b/contrib/llvm/tools/lldb/include/lldb/Target/Thread.h index 954347b5814c..1b0b6ef557e8 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/Thread.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/Thread.h @@ -21,11 +21,11 @@ // Project includes #include "lldb/Core/Broadcaster.h" #include "lldb/Core/Event.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Core/UserSettingsController.h" #include "lldb/Target/ExecutionContextScope.h" #include "lldb/Target/RegisterCheckpoint.h" #include "lldb/Target/StackFrameList.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/Utility/UserID.h" #include "lldb/lldb-private.h" diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/ThreadPlanPython.h b/contrib/llvm/tools/lldb/include/lldb/Target/ThreadPlanPython.h index 9b7e5d029912..973c935b7c79 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/ThreadPlanPython.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/ThreadPlanPython.h @@ -17,13 +17,13 @@ // Other libraries and framework includes // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Target/Process.h" #include "lldb/Target/StopInfo.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlan.h" #include "lldb/Target/ThreadPlanTracer.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/Utility/UserID.h" #include "lldb/lldb-private.h" diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/ThreadSpec.h b/contrib/llvm/tools/lldb/include/lldb/Target/ThreadSpec.h index d00172d1763b..34baf8046261 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/ThreadSpec.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/ThreadSpec.h @@ -10,13 +10,9 @@ #ifndef liblldb_ThreadSpec_h_ #define liblldb_ThreadSpec_h_ -// C Includes -// C++ Includes -#include <string> - -// Other libraries and framework includes -// Project includes +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private.h" +#include <string> namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Connection.h b/contrib/llvm/tools/lldb/include/lldb/Utility/Connection.h index 27757b2f77e7..be5641d5fa63 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Connection.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/Connection.h @@ -31,7 +31,7 @@ template <typename Ratio> class Timeout; namespace lldb_private { //---------------------------------------------------------------------- -/// @class Connection Connection.h "lldb/Core/Connection.h" +/// @class Connection Connection.h "lldb/Utility/Connection.h" /// @brief A communication connection class. /// /// A class that implements that actual communication functions for @@ -48,7 +48,7 @@ public: //------------------------------------------------------------------ /// Default constructor //------------------------------------------------------------------ - Connection(); + Connection() = default; //------------------------------------------------------------------ /// Virtual destructor since this class gets subclassed and handed @@ -56,8 +56,6 @@ public: //------------------------------------------------------------------ virtual ~Connection(); - static Connection *CreateDefaultConnection(const char *url); - //------------------------------------------------------------------ /// Connect using the connect string \a url. /// diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/IOObject.h b/contrib/llvm/tools/lldb/include/lldb/Utility/IOObject.h index 98ad5056de74..61f288183850 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/IOObject.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/IOObject.h @@ -32,7 +32,7 @@ public: IOObject(FDType type, bool should_close) : m_fd_type(type), m_should_close_fd(should_close) {} - virtual ~IOObject() {} + virtual ~IOObject(); virtual Status Read(void *buf, size_t &num_bytes) = 0; virtual Status Write(const void *buf, size_t &num_bytes) = 0; @@ -51,6 +51,6 @@ protected: private: DISALLOW_COPY_AND_ASSIGN(IOObject); }; -} +} // namespace lldb_private #endif diff --git a/contrib/llvm/tools/lldb/include/lldb/Utility/JSON.h b/contrib/llvm/tools/lldb/include/lldb/Utility/JSON.h index bf8ed9afc008..8bf9c4b37b02 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Utility/JSON.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/JSON.h @@ -269,7 +269,7 @@ public: EndOfFile }; - JSONParser(const char *cstr); + JSONParser(llvm::StringRef data); int GetEscapedChar(bool &was_escaped); diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/StructuredData.h b/contrib/llvm/tools/lldb/include/lldb/Utility/StructuredData.h index 39c2f04bb382..2ea5fb98e055 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/StructuredData.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/StructuredData.h @@ -16,6 +16,9 @@ #include "lldb/Utility/FileSpec.h" // for FileSpec #include "lldb/lldb-enumerations.h" // for StructuredDataType +#include <cassert> // for assert +#include <cstddef> // for size_t +#include <cstdint> // for uint64_t #include <functional> #include <map> #include <memory> @@ -24,10 +27,6 @@ #include <utility> #include <vector> -#include <assert.h> // for assert -#include <stddef.h> // for size_t -#include <stdint.h> // for uint64_t - namespace lldb_private { class Status; } @@ -38,7 +37,7 @@ class Stream; namespace lldb_private { //---------------------------------------------------------------------- -/// @class StructuredData StructuredData.h "lldb/Core/StructuredData.h" +/// @class StructuredData StructuredData.h "lldb/Utility/StructuredData.h" /// @brief A class which can hold structured data /// /// The StructuredData class is designed to hold the data from a JSON @@ -94,10 +93,9 @@ public: } Dictionary *GetAsDictionary() { - return ( - (m_type == lldb::eStructuredDataTypeDictionary) - ? static_cast<Dictionary *>(this) - : nullptr); + return ((m_type == lldb::eStructuredDataTypeDictionary) + ? static_cast<Dictionary *>(this) + : nullptr); } Integer *GetAsInteger() { @@ -302,8 +300,8 @@ public: class Float : public Object { public: - Float(double d = 0.0) : Object(lldb::eStructuredDataTypeFloat), - m_value(d) {} + Float(double d = 0.0) + : Object(lldb::eStructuredDataTypeFloat), m_value(d) {} ~Float() override = default; @@ -319,8 +317,8 @@ public: class Boolean : public Object { public: - Boolean(bool b = false) : Object(lldb::eStructuredDataTypeBoolean), - m_value(b) {} + Boolean(bool b = false) + : Object(lldb::eStructuredDataTypeBoolean), m_value(b) {} ~Boolean() override = default; @@ -338,8 +336,7 @@ public: public: String() : Object(lldb::eStructuredDataTypeString) {} explicit String(llvm::StringRef S) - : Object(lldb::eStructuredDataTypeString), - m_value(S) {} + : Object(lldb::eStructuredDataTypeString), m_value(S) {} void SetValue(llvm::StringRef S) { m_value = S; } @@ -353,8 +350,7 @@ public: class Dictionary : public Object { public: - Dictionary() : Object(lldb::eStructuredDataTypeDictionary), - m_dict() {} + Dictionary() : Object(lldb::eStructuredDataTypeDictionary), m_dict() {} ~Dictionary() override = default; diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Timer.h b/contrib/llvm/tools/lldb/include/lldb/Utility/Timer.h index 55aab193032e..c06ac17d344d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Timer.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/Timer.h @@ -12,27 +12,15 @@ #include "lldb/lldb-defines.h" // for DISALLOW_COPY_AND_ASSIGN #include "llvm/Support/Chrono.h" - #include <atomic> - #include <stdint.h> // for uint32_t namespace lldb_private { class Stream; -} - -namespace lldb_private { //---------------------------------------------------------------------- -/// @class Timer Timer.h "lldb/Core/Timer.h" +/// @class Timer Timer.h "lldb/Utility/Timer.h" /// @brief A timer class that simplifies common timing metrics. -/// -/// A scoped timer class that allows a variety of pthread mutex -/// objects to have a mutex locked when a Timer::Locker -/// object is created, and unlocked when it goes out of scope or -/// when the Timer::Locker::Reset(pthread_mutex_t *) -/// is called. This provides an exception safe way to lock a mutex -/// in a scope. //---------------------------------------------------------------------- class Timer { diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/TraceOptions.h b/contrib/llvm/tools/lldb/include/lldb/Utility/TraceOptions.h index 91f48915c94b..325ff74e6f55 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/TraceOptions.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/TraceOptions.h @@ -13,7 +13,7 @@ #include "lldb/lldb-defines.h" #include "lldb/lldb-enumerations.h" -#include "lldb/Core/StructuredData.h" +#include "lldb/Utility/StructuredData.h" namespace lldb_private { class TraceOptions { diff --git a/contrib/llvm/tools/lldb/include/lldb/lldb-enumerations.h b/contrib/llvm/tools/lldb/include/lldb/lldb-enumerations.h index 3c60873f6796..14bae6ca206d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/lldb-enumerations.h +++ b/contrib/llvm/tools/lldb/include/lldb/lldb-enumerations.h @@ -456,6 +456,7 @@ enum InstrumentationRuntimeType { eInstrumentationRuntimeTypeThreadSanitizer = 0x0001, eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer = 0x0002, eInstrumentationRuntimeTypeMainThreadChecker = 0x0003, + eInstrumentationRuntimeTypeSwiftRuntimeReporting = 0x0004, eNumInstrumentationRuntimeTypes }; diff --git a/contrib/llvm/tools/lldb/include/lldb/lldb-private-interfaces.h b/contrib/llvm/tools/lldb/include/lldb/lldb-private-interfaces.h index 9f25eb1f9a29..806068ece7b6 100644 --- a/contrib/llvm/tools/lldb/include/lldb/lldb-private-interfaces.h +++ b/contrib/llvm/tools/lldb/include/lldb/lldb-private-interfaces.h @@ -21,7 +21,7 @@ #include <set> namespace lldb_private { -typedef lldb::ABISP (*ABICreateInstance)(const ArchSpec &arch); +typedef lldb::ABISP (*ABICreateInstance)(lldb::ProcessSP process_sp, const ArchSpec &arch); typedef Disassembler *(*DisassemblerCreateInstance)(const ArchSpec &arch, const char *flavor); typedef DynamicLoader *(*DynamicLoaderCreateInstance)(Process *process, diff --git a/contrib/llvm/tools/lldb/source/API/SBCommunication.cpp b/contrib/llvm/tools/lldb/source/API/SBCommunication.cpp index 8ebc33ca26a6..63b672efe3c0 100644 --- a/contrib/llvm/tools/lldb/source/API/SBCommunication.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBCommunication.cpp @@ -11,6 +11,7 @@ #include "lldb/API/SBBroadcaster.h" #include "lldb/Core/Communication.h" #include "lldb/Host/ConnectionFileDescriptor.h" +#include "lldb/Host/Host.h" #include "lldb/Utility/Log.h" using namespace lldb; @@ -51,7 +52,7 @@ void SBCommunication::SetCloseOnEOF(bool b) { ConnectionStatus SBCommunication::Connect(const char *url) { if (m_opaque) { if (!m_opaque->HasConnection()) - m_opaque->SetConnection(Connection::CreateDefaultConnection(url)); + m_opaque->SetConnection(Host::CreateDefaultConnection(url).release()); return m_opaque->Connect(url, NULL); } return eConnectionStatusNoConnection; diff --git a/contrib/llvm/tools/lldb/source/API/SBStructuredData.cpp b/contrib/llvm/tools/lldb/source/API/SBStructuredData.cpp index 54022390b80f..d506410f6d80 100644 --- a/contrib/llvm/tools/lldb/source/API/SBStructuredData.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBStructuredData.cpp @@ -11,11 +11,11 @@ #include "lldb/API/SBStream.h" #include "lldb/Core/Event.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Core/StructuredDataImpl.h" #include "lldb/Target/StructuredDataPlugin.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/StructuredData.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/API/SBTarget.cpp b/contrib/llvm/tools/lldb/source/API/SBTarget.cpp index 0ab7375ccc30..c706344ee4a3 100644 --- a/contrib/llvm/tools/lldb/source/API/SBTarget.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBTarget.cpp @@ -2170,7 +2170,7 @@ lldb::addr_t SBTarget::GetStackRedZoneSize() { if (process_sp) abi_sp = process_sp->GetABI(); else - abi_sp = ABI::FindPlugin(target_sp->GetArchitecture()); + abi_sp = ABI::FindPlugin(ProcessSP(), target_sp->GetArchitecture()); if (abi_sp) return abi_sp->GetRedZoneSize(); } diff --git a/contrib/llvm/tools/lldb/source/API/SBThread.cpp b/contrib/llvm/tools/lldb/source/API/SBThread.cpp index d9ce6be3f893..b34489603c8a 100644 --- a/contrib/llvm/tools/lldb/source/API/SBThread.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBThread.cpp @@ -16,7 +16,6 @@ #include "lldb/Core/Debugger.h" #include "lldb/Core/State.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Core/ValueObject.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Symbol/CompileUnit.h" @@ -34,6 +33,7 @@ #include "lldb/Target/ThreadPlanStepRange.h" #include "lldb/Target/UnixSignals.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBDebugger.h" diff --git a/contrib/llvm/tools/lldb/source/API/SBThreadPlan.cpp b/contrib/llvm/tools/lldb/source/API/SBThreadPlan.cpp index 7537a7645390..a19023f66de2 100644 --- a/contrib/llvm/tools/lldb/source/API/SBThreadPlan.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBThreadPlan.cpp @@ -16,7 +16,6 @@ #include "lldb/Core/Debugger.h" #include "lldb/Core/State.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/SymbolContext.h" @@ -33,6 +32,7 @@ #include "lldb/Target/ThreadPlanStepOut.h" #include "lldb/Target/ThreadPlanStepRange.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBDebugger.h" diff --git a/contrib/llvm/tools/lldb/source/API/SBTraceOptions.cpp b/contrib/llvm/tools/lldb/source/API/SBTraceOptions.cpp index 474fa911f7ec..20a8f25a768b 100644 --- a/contrib/llvm/tools/lldb/source/API/SBTraceOptions.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBTraceOptions.cpp @@ -10,9 +10,9 @@ #include "lldb/API/SBTraceOptions.h" #include "lldb/API/SBError.h" #include "lldb/API/SBStructuredData.h" -#include "lldb/Utility/Log.h" #include "lldb/Core/StructuredDataImpl.h" -#include "lldb/Core/TraceOptions.h" +#include "lldb/Utility/Log.h" +#include "lldb/Utility/TraceOptions.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/API/SystemInitializerFull.cpp b/contrib/llvm/tools/lldb/source/API/SystemInitializerFull.cpp index f4cc4581960a..eb1bc2ff50c1 100644 --- a/contrib/llvm/tools/lldb/source/API/SystemInitializerFull.cpp +++ b/contrib/llvm/tools/lldb/source/API/SystemInitializerFull.cpp @@ -20,7 +20,6 @@ #endif #include "lldb/Core/Debugger.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/Host.h" #include "lldb/Initialization/SystemInitializerCommon.h" #include "lldb/Interpreter/CommandInterpreter.h" @@ -28,6 +27,7 @@ #include "lldb/Symbol/GoASTContext.h" //#include "lldb/Symbol/JavaASTContext.h" #include "lldb/Symbol/OCamlASTContext.h" +#include "lldb/Utility/Timer.h" //#include "Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h" //#include "Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h" diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectFrame.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectFrame.cpp index 9e1805f2eed6..0bcc35062968 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectFrame.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectFrame.cpp @@ -17,7 +17,6 @@ #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/Timer.h" #include "lldb/Core/Value.h" #include "lldb/Core/ValueObject.h" #include "lldb/Core/ValueObjectVariable.h" @@ -47,6 +46,7 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectLog.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectLog.cpp index e545d5679725..ef82d07f15fb 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectLog.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectLog.cpp @@ -15,7 +15,6 @@ #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/OptionParser.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandInterpreter.h" @@ -31,6 +30,7 @@ #include "lldb/Utility/Log.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectTarget.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectTarget.cpp index 343530ea4f35..a80acf19be2d 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectTarget.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectTarget.cpp @@ -16,7 +16,6 @@ #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/Section.h" #include "lldb/Core/State.h" -#include "lldb/Core/Timer.h" #include "lldb/Core/ValueObjectVariable.h" #include "lldb/DataFormatters/ValueObjectPrinter.h" #include "lldb/Host/OptionParser.h" @@ -50,6 +49,7 @@ #include "lldb/Target/StackFrame.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadSpec.h" +#include "lldb/Utility/Timer.h" #include "llvm/Support/FileSystem.h" @@ -3426,6 +3426,23 @@ protected: result.GetOutputStream().Printf("\n"); } + if (UnwindPlanSP plan_sp = + func_unwinders_sp->GetDebugFrameUnwindPlan(*target, 0)) { + result.GetOutputStream().Printf("debug_frame UnwindPlan:\n"); + plan_sp->Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); + } + + if (UnwindPlanSP plan_sp = + func_unwinders_sp->GetDebugFrameAugmentedUnwindPlan(*target, + *thread, 0)) { + result.GetOutputStream().Printf("debug_frame augmented UnwindPlan:\n"); + plan_sp->Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); + } + UnwindPlanSP arm_unwind_sp = func_unwinders_sp->GetArmUnwindUnwindPlan(*target, 0); if (arm_unwind_sp) { diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectThread.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectThread.cpp index cfd8fcb7291d..687187b26ccd 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectThread.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectThread.cpp @@ -209,7 +209,7 @@ protected: Process *process = m_exe_ctx.GetProcessPtr(); Thread *thread = process->GetThreadList().FindThreadByID(tid).get(); if (thread == nullptr) { - result.AppendErrorWithFormat("Failed to process thread# %lu.\n", tid); + result.AppendErrorWithFormat("Failed to process thread# %llu.\n", tid); result.SetStatus(eReturnStatusFailed); return false; } diff --git a/contrib/llvm/tools/lldb/source/Core/Communication.cpp b/contrib/llvm/tools/lldb/source/Core/Communication.cpp index 72873a9510b5..38ab902ab4b7 100644 --- a/contrib/llvm/tools/lldb/source/Core/Communication.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Communication.cpp @@ -9,11 +9,11 @@ #include "lldb/Core/Communication.h" -#include "lldb/Core/Connection.h" #include "lldb/Core/Event.h" #include "lldb/Core/Listener.h" #include "lldb/Host/HostThread.h" #include "lldb/Host/ThreadLauncher.h" +#include "lldb/Utility/Connection.h" #include "lldb/Utility/ConstString.h" // for ConstString #include "lldb/Utility/Log.h" #include "lldb/Utility/Logging.h" // for LogIfAnyCategoriesSet, LIBLLDB... diff --git a/contrib/llvm/tools/lldb/source/Core/Connection.cpp b/contrib/llvm/tools/lldb/source/Core/Connection.cpp deleted file mode 100644 index 60d1221c160c..000000000000 --- a/contrib/llvm/tools/lldb/source/Core/Connection.cpp +++ /dev/null @@ -1,32 +0,0 @@ -//===-- Connection.cpp ------------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "lldb/Core/Connection.h" - -#if defined(_WIN32) -#include "lldb/Host/windows/ConnectionGenericFileWindows.h" -#endif - -#include "lldb/Host/ConnectionFileDescriptor.h" - -#include <string.h> // for strstr - -using namespace lldb_private; - -Connection::Connection() {} - -Connection::~Connection() {} - -Connection *Connection::CreateDefaultConnection(const char *url) { -#if defined(_WIN32) - if (strstr(url, "file://") == url) - return new ConnectionGenericFile(); -#endif - return new ConnectionFileDescriptor(); -} diff --git a/contrib/llvm/tools/lldb/source/Core/Disassembler.cpp b/contrib/llvm/tools/lldb/source/Core/Disassembler.cpp index 0a5d763b6d3f..6d463d552da6 100644 --- a/contrib/llvm/tools/lldb/source/Core/Disassembler.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Disassembler.cpp @@ -17,7 +17,6 @@ #include "lldb/Core/ModuleList.h" // for ModuleList #include "lldb/Core/PluginManager.h" #include "lldb/Core/SourceManager.h" // for SourceManager -#include "lldb/Core/Timer.h" #include "lldb/Host/FileSystem.h" #include "lldb/Interpreter/OptionValue.h" #include "lldb/Interpreter/OptionValueArray.h" @@ -37,8 +36,9 @@ #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Status.h" -#include "lldb/Utility/Stream.h" // for Stream -#include "lldb/Utility/StreamString.h" // for StreamString +#include "lldb/Utility/Stream.h" // for Stream +#include "lldb/Utility/StreamString.h" // for StreamString +#include "lldb/Utility/Timer.h" #include "lldb/lldb-private-enumerations.h" // for InstructionType:... #include "lldb/lldb-private-interfaces.h" // for DisassemblerCrea... #include "lldb/lldb-private-types.h" // for RegisterInfo diff --git a/contrib/llvm/tools/lldb/source/Core/FormatEntity.cpp b/contrib/llvm/tools/lldb/source/Core/FormatEntity.cpp index e3c346f79d6b..6002efe9244d 100644 --- a/contrib/llvm/tools/lldb/source/Core/FormatEntity.cpp +++ b/contrib/llvm/tools/lldb/source/Core/FormatEntity.cpp @@ -14,8 +14,7 @@ #include "lldb/Core/ArchSpec.h" // for ArchSpec #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" -#include "lldb/Core/RegisterValue.h" // for RegisterValue -#include "lldb/Core/StructuredData.h" // for StructuredData::O... +#include "lldb/Core/RegisterValue.h" // for RegisterValue #include "lldb/Core/ValueObject.h" #include "lldb/Core/ValueObjectVariable.h" #include "lldb/DataFormatters/DataVisualization.h" @@ -50,9 +49,10 @@ #include "lldb/Utility/SharingPtr.h" // for SharingPtr #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" -#include "lldb/Utility/StringList.h" // for StringList -#include "lldb/lldb-defines.h" // for LLDB_INVALID_ADDRESS -#include "lldb/lldb-forward.h" // for ValueObjectSP +#include "lldb/Utility/StringList.h" // for StringList +#include "lldb/Utility/StructuredData.h" // for StructuredData::O... +#include "lldb/lldb-defines.h" // for LLDB_INVALID_ADDRESS +#include "lldb/lldb-forward.h" // for ValueObjectSP #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Triple.h" // for Triple, Triple::O... diff --git a/contrib/llvm/tools/lldb/source/Core/Mangled.cpp b/contrib/llvm/tools/lldb/source/Core/Mangled.cpp index 4dac0b8f3bf1..211a0c32cee7 100644 --- a/contrib/llvm/tools/lldb/source/Core/Mangled.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Mangled.cpp @@ -27,12 +27,12 @@ #include <cxxabi.h> #endif -#include "lldb/Core/Timer.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Logging.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/Timer.h" #include "lldb/lldb-enumerations.h" // for LanguageType #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" diff --git a/contrib/llvm/tools/lldb/source/Core/Module.cpp b/contrib/llvm/tools/lldb/source/Core/Module.cpp index 1b510d2ff7b2..aaae4700db35 100644 --- a/contrib/llvm/tools/lldb/source/Core/Module.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Module.cpp @@ -17,7 +17,6 @@ #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/SearchFilter.h" // for SearchFilt... #include "lldb/Core/Section.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Interpreter/CommandInterpreter.h" @@ -45,6 +44,7 @@ #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" // for Stream #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" #if defined(LLVM_ON_WIN32) #include "lldb/Host/windows/PosixApi.h" // for PATH_MAX diff --git a/contrib/llvm/tools/lldb/source/Host/common/Host.cpp b/contrib/llvm/tools/lldb/source/Host/common/Host.cpp index af0b57248922..29e5991d31aa 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/Host.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/Host.cpp @@ -58,6 +58,7 @@ #include "lldb/Host/Predicate.h" #include "lldb/Host/ProcessLauncher.h" #include "lldb/Host/ThreadLauncher.h" +#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h" #include "lldb/Target/FileAction.h" #include "lldb/Target/ProcessLaunchInfo.h" #include "lldb/Target/UnixSignals.h" @@ -73,6 +74,7 @@ #include "llvm/Support/FileSystem.h" #if defined(_WIN32) +#include "lldb/Host/windows/ConnectionGenericFileWindows.h" #include "lldb/Host/windows/ProcessLauncherWindows.h" #else #include "lldb/Host/posix/ProcessLauncherPosixFork.h" @@ -624,6 +626,14 @@ const UnixSignalsSP &Host::GetUnixSignals() { return s_unix_signals_sp; } +std::unique_ptr<Connection> Host::CreateDefaultConnection(llvm::StringRef url) { +#if defined(_WIN32) + if (url.startswith("file://")) + return std::unique_ptr<Connection>(new ConnectionGenericFile()); +#endif + return std::unique_ptr<Connection>(new ConnectionFileDescriptor()); +} + #if defined(LLVM_ON_UNIX) WaitStatus WaitStatus::Decode(int wstatus) { if (WIFEXITED(wstatus)) diff --git a/contrib/llvm/tools/lldb/source/Host/common/Symbols.cpp b/contrib/llvm/tools/lldb/source/Host/common/Symbols.cpp index fe29b9e78990..e7bdf084d385 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/Symbols.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/Symbols.cpp @@ -11,7 +11,6 @@ #include "lldb/Core/ArchSpec.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" -#include "lldb/Core/Timer.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBuffer.h" @@ -19,6 +18,7 @@ #include "lldb/Utility/Log.h" #include "lldb/Utility/SafeMachO.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" #include "lldb/Utility/UUID.h" #include "llvm/Support/FileSystem.h" diff --git a/contrib/llvm/tools/lldb/source/Host/freebsd/Host.cpp b/contrib/llvm/tools/lldb/source/Host/freebsd/Host.cpp index bd547bbeb9c5..037dfc7f5e03 100644 --- a/contrib/llvm/tools/lldb/source/Host/freebsd/Host.cpp +++ b/contrib/llvm/tools/lldb/source/Host/freebsd/Host.cpp @@ -27,22 +27,19 @@ // Other libraries and framework includes // Project includes #include "lldb/Core/Module.h" -#include "lldb/Core/StreamFile.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" +#include "lldb/Utility/CleanUp.h" +#include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/NameMatches.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" -#include "lldb/Utility/CleanUp.h" -#include "lldb/Utility/DataBufferHeap.h" -#include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/NameMatches.h" - #include "llvm/Support/Host.h" extern "C" { diff --git a/contrib/llvm/tools/lldb/source/Host/netbsd/Host.cpp b/contrib/llvm/tools/lldb/source/Host/netbsd/Host.cpp index bbe34a83d999..d927f95f0675 100644 --- a/contrib/llvm/tools/lldb/source/Host/netbsd/Host.cpp +++ b/contrib/llvm/tools/lldb/source/Host/netbsd/Host.cpp @@ -26,22 +26,19 @@ // Other libraries and framework includes // Project includes #include "lldb/Core/Module.h" -#include "lldb/Core/StreamFile.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" +#include "lldb/Utility/CleanUp.h" +#include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/NameMatches.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" -#include "lldb/Utility/CleanUp.h" -#include "lldb/Utility/DataBufferHeap.h" -#include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/NameMatches.h" - #include "llvm/Support/Host.h" extern "C" { diff --git a/contrib/llvm/tools/lldb/source/Host/openbsd/Host.cpp b/contrib/llvm/tools/lldb/source/Host/openbsd/Host.cpp index 7e4a64fbd9ae..0535256b9aa1 100644 --- a/contrib/llvm/tools/lldb/source/Host/openbsd/Host.cpp +++ b/contrib/llvm/tools/lldb/source/Host/openbsd/Host.cpp @@ -23,22 +23,19 @@ // Other libraries and framework includes // Project includes #include "lldb/Core/Module.h" -#include "lldb/Core/StreamFile.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" +#include "lldb/Utility/CleanUp.h" +#include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/NameMatches.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" -#include "lldb/Utility/CleanUp.h" -#include "lldb/Utility/DataBufferHeap.h" -#include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/NameMatches.h" - #include "llvm/Support/Host.h" extern "C" { diff --git a/contrib/llvm/tools/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp b/contrib/llvm/tools/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp index c3b237a87302..6b0f069c35a9 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp @@ -16,10 +16,10 @@ #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h" #include "lldb/Host/Config.h" -#include "lldb/Host/IOObject.h" #include "lldb/Host/Socket.h" #include "lldb/Host/SocketAddress.h" #include "lldb/Utility/SelectHelper.h" +#include "lldb/Utility/Timeout.h" // C Includes #include <errno.h> @@ -42,13 +42,12 @@ #include "llvm/ADT/SmallVector.h" #endif // Project includes -#include "lldb/Core/Communication.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/Host.h" #include "lldb/Host/Socket.h" #include "lldb/Host/common/TCPSocket.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Initialization/SystemInitializerCommon.cpp b/contrib/llvm/tools/lldb/source/Initialization/SystemInitializerCommon.cpp index a548a96cc4f1..29a3fb83e555 100644 --- a/contrib/llvm/tools/lldb/source/Initialization/SystemInitializerCommon.cpp +++ b/contrib/llvm/tools/lldb/source/Initialization/SystemInitializerCommon.cpp @@ -17,10 +17,10 @@ #include "Plugins/ObjectFile/ELF/ObjectFileELF.h" //#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h" #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Timer.h" #if defined(__APPLE__) #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h" diff --git a/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp b/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp index a1d8eded09f5..075f2e7b7bd1 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp @@ -45,9 +45,9 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Core/State.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/Timer.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/Timer.h" #ifndef LLDB_DISABLE_LIBEDIT #include "lldb/Host/Editline.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp index 06b1c7054c1f..fd5ee6ede4c3 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp @@ -1326,7 +1326,7 @@ size_t ABIMacOSX_arm::GetRedZoneSize() const { return 0; } //------------------------------------------------------------------ ABISP -ABIMacOSX_arm::CreateInstance(const ArchSpec &arch) { +ABIMacOSX_arm::CreateInstance(ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch(); const llvm::Triple::VendorType vendor_type = arch.GetTriple().getVendor(); @@ -1335,7 +1335,7 @@ ABIMacOSX_arm::CreateInstance(const ArchSpec &arch) { if ((arch_type == llvm::Triple::arm) || (arch_type == llvm::Triple::thumb)) { if (!g_abi_sp) - g_abi_sp.reset(new ABIMacOSX_arm); + g_abi_sp.reset(new ABIMacOSX_arm(process_sp)); return g_abi_sp; } } @@ -1546,16 +1546,14 @@ bool ABIMacOSX_arm::GetArgumentValues(Thread &thread, ValueList &values) const { return true; } -bool ABIMacOSX_arm::IsArmv7kProcess(Thread *thread) const { +bool ABIMacOSX_arm::IsArmv7kProcess() const { bool is_armv7k = false; - if (thread) { - ProcessSP process_sp(thread->GetProcess()); - if (process_sp) { - const ArchSpec &arch(process_sp->GetTarget().GetArchitecture()); - const ArchSpec::Core system_core = arch.GetCore(); - if (system_core == ArchSpec::eCore_arm_armv7k) { - is_armv7k = true; - } + ProcessSP process_sp(GetProcessSP()); + if (process_sp) { + const ArchSpec &arch(process_sp->GetTarget().GetArchitecture()); + const ArchSpec::Core system_core = arch.GetCore(); + if (system_core == ArchSpec::eCore_arm_armv7k) { + is_armv7k = true; } } return is_armv7k; @@ -1588,7 +1586,7 @@ ValueObjectSP ABIMacOSX_arm::GetReturnValueObjectImpl( default: return return_valobj_sp; case 128: - if (IsArmv7kProcess(&thread)) { + if (IsArmv7kProcess()) { // "A composite type not larger than 16 bytes is returned in r0-r3. The // format is // as if the result had been stored in memory at a word-aligned address @@ -1755,8 +1753,7 @@ Status ABIMacOSX_arm::SetReturnValueObject(lldb::StackFrameSP &frame_sp, set_it_simple = true; } } - } else if (num_bytes <= 16 && - IsArmv7kProcess(frame_sp->GetThread().get())) { + } else if (num_bytes <= 16 && IsArmv7kProcess()) { // "A composite type not larger than 16 bytes is returned in r0-r3. The // format is // as if the result had been stored in memory at a word-aligned address diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h index 5aa817c20ec2..d3c20e1e618f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h @@ -66,7 +66,7 @@ public: const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; - bool IsArmv7kProcess(lldb_private::Thread *thread) const; + bool IsArmv7kProcess() const; //------------------------------------------------------------------ // Static Functions @@ -76,7 +76,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -94,7 +94,7 @@ protected: lldb_private::CompilerType &ast_type) const override; private: - ABIMacOSX_arm() : lldb_private::ABI() { + ABIMacOSX_arm(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp index a545dfc837da..e301b21d542a 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp @@ -1666,7 +1666,7 @@ size_t ABIMacOSX_arm64::GetRedZoneSize() const { return 128; } //------------------------------------------------------------------ ABISP -ABIMacOSX_arm64::CreateInstance(const ArchSpec &arch) { +ABIMacOSX_arm64::CreateInstance(ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch(); const llvm::Triple::VendorType vendor_type = arch.GetTriple().getVendor(); @@ -1674,7 +1674,7 @@ ABIMacOSX_arm64::CreateInstance(const ArchSpec &arch) { if (vendor_type == llvm::Triple::Apple) { if (arch_type == llvm::Triple::aarch64) { if (!g_abi_sp) - g_abi_sp.reset(new ABIMacOSX_arm64); + g_abi_sp.reset(new ABIMacOSX_arm64(process_sp)); return g_abi_sp; } } diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h index 589e2ea468ef..2dd7337542db 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h @@ -78,7 +78,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); //------------------------------------------------------------------ // PluginInterface protocol @@ -102,7 +102,7 @@ protected: lldb_private::CompilerType &ast_type) const override; private: - ABIMacOSX_arm64() : lldb_private::ABI() { + ABIMacOSX_arm64(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp index c393ac9c916b..716a73b854b3 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp @@ -713,13 +713,13 @@ size_t ABIMacOSX_i386::GetRedZoneSize() const { return 0; } //------------------------------------------------------------------ ABISP -ABIMacOSX_i386::CreateInstance(const ArchSpec &arch) { +ABIMacOSX_i386::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; if ((arch.GetTriple().getArch() == llvm::Triple::x86) && (arch.GetTriple().isMacOSX() || arch.GetTriple().isiOS() || arch.GetTriple().isWatchOS())) { if (!g_abi_sp) - g_abi_sp.reset(new ABIMacOSX_i386); + g_abi_sp.reset(new ABIMacOSX_i386(process_sp)); return g_abi_sp; } return ABISP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h index 88fb6ffd7a40..e026e3248672 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h @@ -81,7 +81,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); //------------------------------------------------------------------ // PluginInterface protocol @@ -101,7 +101,7 @@ protected: bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: - ABIMacOSX_i386() : lldb_private::ABI() { + ABIMacOSX_i386(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp index 614c6e893806..882d5cd23e58 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp @@ -1327,7 +1327,7 @@ size_t ABISysV_arm::GetRedZoneSize() const { return 0; } //------------------------------------------------------------------ ABISP -ABISysV_arm::CreateInstance(const ArchSpec &arch) { +ABISysV_arm::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch(); const llvm::Triple::VendorType vendor_type = arch.GetTriple().getVendor(); @@ -1336,7 +1336,7 @@ ABISysV_arm::CreateInstance(const ArchSpec &arch) { if ((arch_type == llvm::Triple::arm) || (arch_type == llvm::Triple::thumb)) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_arm); + g_abi_sp.reset(new ABISysV_arm(process_sp)); return g_abi_sp; } } diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h index 81f1277419a6..f046968c213d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h @@ -76,7 +76,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -94,7 +94,7 @@ protected: lldb_private::CompilerType &ast_type) const override; private: - ABISysV_arm() : lldb_private::ABI() { + ABISysV_arm(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp index ce8f8a65e3e3..f91ed851a3e5 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp @@ -1670,7 +1670,7 @@ size_t ABISysV_arm64::GetRedZoneSize() const { return 128; } //------------------------------------------------------------------ ABISP -ABISysV_arm64::CreateInstance(const ArchSpec &arch) { +ABISysV_arm64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch(); const llvm::Triple::VendorType vendor_type = arch.GetTriple().getVendor(); @@ -1678,7 +1678,7 @@ ABISysV_arm64::CreateInstance(const ArchSpec &arch) { if (vendor_type != llvm::Triple::Apple) { if (arch_type == llvm::Triple::aarch64) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_arm64); + g_abi_sp.reset(new ABISysV_arm64(process_sp)); return g_abi_sp; } } diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h index c048e8634ae5..8d23c2419bab 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h @@ -83,7 +83,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -101,7 +101,7 @@ protected: lldb_private::CompilerType &ast_type) const override; private: - ABISysV_arm64() : lldb_private::ABI() { + ABISysV_arm64(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp index 425bf2ce0bf6..74274f08b24f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp @@ -1019,11 +1019,11 @@ size_t ABISysV_hexagon::GetRedZoneSize() const { return 0; } //------------------------------------------------------------------ ABISP -ABISysV_hexagon::CreateInstance(const ArchSpec &arch) { +ABISysV_hexagon::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; if (arch.GetTriple().getArch() == llvm::Triple::hexagon) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_hexagon); + g_abi_sp.reset(new ABISysV_hexagon(process_sp)); return g_abi_sp; } return ABISP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h index 5f808291eac0..5a6809371d9f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h @@ -84,7 +84,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -106,7 +106,7 @@ protected: bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: - ABISysV_hexagon() : lldb_private::ABI() { + ABISysV_hexagon(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp index cb3644d46af4..63da5a77b48f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp @@ -203,12 +203,12 @@ ABISysV_i386::GetRegisterInfoArray(uint32_t &count) { //------------------------------------------------------------------ ABISP -ABISysV_i386::CreateInstance(const ArchSpec &arch) { +ABISysV_i386::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; if ((arch.GetTriple().getArch() == llvm::Triple::x86) && arch.GetTriple().isOSLinux()) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_i386); + g_abi_sp.reset(new ABISysV_i386(process_sp)); return g_abi_sp; } return ABISP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h index 038bf656b1f1..4dce54c4f073 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h @@ -89,7 +89,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); //------------------------------------------------------------------ // PluginInterface protocol @@ -109,7 +109,7 @@ protected: bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: - ABISysV_i386() : lldb_private::ABI() { + ABISysV_i386(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp index a77252a20499..95e2a7b0afeb 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp @@ -559,13 +559,13 @@ size_t ABISysV_mips::GetRedZoneSize() const { return 0; } //------------------------------------------------------------------ ABISP -ABISysV_mips::CreateInstance(const ArchSpec &arch) { +ABISysV_mips::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch(); if ((arch_type == llvm::Triple::mips) || (arch_type == llvm::Triple::mipsel)) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_mips); + g_abi_sp.reset(new ABISysV_mips(process_sp)); return g_abi_sp; } return ABISP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h index 980553c506bd..0de8e7751fce 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h @@ -74,7 +74,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -96,7 +96,7 @@ protected: bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: - ABISysV_mips() : lldb_private::ABI() { + ABISysV_mips(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp index baa478ea1106..749e170fa17d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp @@ -559,13 +559,13 @@ size_t ABISysV_mips64::GetRedZoneSize() const { return 0; } //------------------------------------------------------------------ ABISP -ABISysV_mips64::CreateInstance(const ArchSpec &arch) { +ABISysV_mips64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch(); if ((arch_type == llvm::Triple::mips64) || (arch_type == llvm::Triple::mips64el)) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_mips64); + g_abi_sp.reset(new ABISysV_mips64(process_sp)); return g_abi_sp; } return ABISP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h index ac7d9b871946..6258c08e35f9 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h @@ -87,7 +87,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -109,7 +109,7 @@ protected: bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: - ABISysV_mips64() : lldb_private::ABI() { + ABISysV_mips64(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp index 00adfe1be82d..06a8ce932fda 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp @@ -223,11 +223,11 @@ size_t ABISysV_ppc::GetRedZoneSize() const { return 224; } //------------------------------------------------------------------ ABISP -ABISysV_ppc::CreateInstance(const ArchSpec &arch) { +ABISysV_ppc::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; if (arch.GetTriple().getArch() == llvm::Triple::ppc) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_ppc); + g_abi_sp.reset(new ABISysV_ppc(process_sp)); return g_abi_sp; } return ABISP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h index 8cb9bf24881f..df3ebe83faf8 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h @@ -83,7 +83,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -105,7 +105,7 @@ protected: bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: - ABISysV_ppc() : lldb_private::ABI() { + ABISysV_ppc(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp index 449990d71304..c090f01ccb1c 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp @@ -223,11 +223,11 @@ size_t ABISysV_ppc64::GetRedZoneSize() const { return 224; } //------------------------------------------------------------------ ABISP -ABISysV_ppc64::CreateInstance(const ArchSpec &arch) { +ABISysV_ppc64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; if (arch.GetTriple().getArch() == llvm::Triple::ppc64) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_ppc64); + g_abi_sp.reset(new ABISysV_ppc64(process_sp)); return g_abi_sp; } return ABISP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h index 29237a68fc9e..21608a5c1cdd 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h @@ -83,7 +83,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -105,7 +105,7 @@ protected: bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: - ABISysV_ppc64() : lldb_private::ABI() { + ABISysV_ppc64(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp index 7f76d49bfb0f..967e407188fa 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp @@ -205,11 +205,11 @@ size_t ABISysV_s390x::GetRedZoneSize() const { return 0; } //------------------------------------------------------------------ ABISP -ABISysV_s390x::CreateInstance(const ArchSpec &arch) { +ABISysV_s390x::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; if (arch.GetTriple().getArch() == llvm::Triple::systemz) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_s390x); + g_abi_sp.reset(new ABISysV_s390x(process_sp)); return g_abi_sp; } return ABISP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h index e233a900e395..5e3d20d7898b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h @@ -77,7 +77,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -99,7 +99,7 @@ protected: bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: - ABISysV_s390x() : lldb_private::ABI() { + ABISysV_s390x(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp index deccca8c29e9..10bbae566491 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp @@ -1093,11 +1093,11 @@ size_t ABISysV_x86_64::GetRedZoneSize() const { return 128; } //------------------------------------------------------------------ ABISP -ABISysV_x86_64::CreateInstance(const ArchSpec &arch) { +ABISysV_x86_64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; if (arch.GetTriple().getArch() == llvm::Triple::x86_64) { if (!g_abi_sp) - g_abi_sp.reset(new ABISysV_x86_64); + g_abi_sp.reset(new ABISysV_x86_64(process_sp)); return g_abi_sp; } return ABISP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h index 8d420e88167c..5b67e8656d36 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h @@ -85,7 +85,7 @@ public: static void Terminate(); - static lldb::ABISP CreateInstance(const lldb_private::ArchSpec &arch); + static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); @@ -107,7 +107,7 @@ protected: bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: - ABISysV_x86_64() : lldb_private::ABI() { + ABISysV_x86_64(lldb::ProcessSP process_sp) : lldb_private::ABI(process_sp) { // Call CreateInstance instead. } }; diff --git a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.h b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.h index 9fd21c06f30c..e9af5a6cdc74 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.h +++ b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/ASan/ASanRuntime.h @@ -14,9 +14,9 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Target/InstrumentationRuntime.h" #include "lldb/Target/Process.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.h b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.h index 87440a2489e6..516d9fef5e8e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.h +++ b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.h @@ -10,9 +10,9 @@ #ifndef liblldb_MainThreadCheckerRuntime_h_ #define liblldb_MainThreadCheckerRuntime_h_ -#include "lldb/Core/StructuredData.h" #include "lldb/Target/ABI.h" #include "lldb/Target/InstrumentationRuntime.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.h b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.h index 2a10582b65d2..dc737d22a67a 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.h +++ b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/TSan/TSanRuntime.h @@ -14,9 +14,9 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Target/ABI.h" #include "lldb/Target/InstrumentationRuntime.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.h b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.h index 0c478bd57e82..8f138fc12073 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.h +++ b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/UBSan/UBSanRuntime.h @@ -10,9 +10,9 @@ #ifndef liblldb_UndefinedBehaviorSanitizerRuntime_h_ #define liblldb_UndefinedBehaviorSanitizerRuntime_h_ -#include "lldb/Core/StructuredData.h" #include "lldb/Target/ABI.h" #include "lldb/Target/InstrumentationRuntime.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/Cocoa.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/Cocoa.cpp index 6aaf66cbb486..2ba005e02ad4 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/Cocoa.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/Cocoa.cpp @@ -517,11 +517,11 @@ bool lldb_private::formatters::NSNumberSummaryProvider( bool is_preserved_number = cfinfoa & 0x8; if (is_preserved_number) { - lldbassert(!"We should handle preserved numbers!"); + lldbassert(!static_cast<bool>("We should handle preserved numbers!")); return false; } - type_code = (TypeCodes)(cfinfoa & 0x7); + type_code = static_cast<TypeCodes>(cfinfoa & 0x7); } else { uint8_t data_type = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + ptr_size, 1, diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSSet.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSSet.cpp index b6f6ff7af19d..2f3398775169 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSSet.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSSet.cpp @@ -13,6 +13,7 @@ // Project includes #include "NSSet.h" +#include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.h" #include "lldb/Core/ValueObject.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/DataFormatters/FormattersHelpers.h" @@ -84,11 +85,12 @@ private: std::vector<SetItemDescriptor> m_children; }; -class NSSetMSyntheticFrontEnd : public SyntheticChildrenFrontEnd { +template <typename D32, typename D64> +class GenericNSSetMSyntheticFrontEnd : public SyntheticChildrenFrontEnd { public: - NSSetMSyntheticFrontEnd(lldb::ValueObjectSP valobj_sp); + GenericNSSetMSyntheticFrontEnd(lldb::ValueObjectSP valobj_sp); - ~NSSetMSyntheticFrontEnd() override; + ~GenericNSSetMSyntheticFrontEnd() override; size_t CalculateNumChildren() override; @@ -101,32 +103,57 @@ public: size_t GetIndexOfChildWithName(const ConstString &name) override; private: + + struct SetItemDescriptor { + lldb::addr_t item_ptr; + lldb::ValueObjectSP valobj_sp; + }; + + ExecutionContextRef m_exe_ctx_ref; + uint8_t m_ptr_size; + D32 *m_data_32; + D64 *m_data_64; + std::vector<SetItemDescriptor> m_children; +}; + +namespace Foundation1300 { struct DataDescriptor_32 { uint32_t _used : 26; uint32_t _size; uint32_t _mutations; uint32_t _objs_addr; }; - + struct DataDescriptor_64 { uint64_t _used : 58; uint64_t _size; uint64_t _mutations; uint64_t _objs_addr; }; - - struct SetItemDescriptor { - lldb::addr_t item_ptr; - lldb::ValueObjectSP valobj_sp; + + using NSSetMSyntheticFrontEnd = + GenericNSSetMSyntheticFrontEnd<DataDescriptor_32, DataDescriptor_64>; +} + +namespace Foundation1400 { + struct DataDescriptor_32 { + uint32_t _used : 26; + uint32_t _size; + uint32_t _objs_addr; + uint32_t _mutations; }; - - ExecutionContextRef m_exe_ctx_ref; - uint8_t m_ptr_size; - DataDescriptor_32 *m_data_32; - DataDescriptor_64 *m_data_64; - std::vector<SetItemDescriptor> m_children; -}; - + + struct DataDescriptor_64 { + uint64_t _used : 58; + uint64_t _size; + uint64_t _objs_addr; + uint64_t _mutations; + }; + + using NSSetMSyntheticFrontEnd = + GenericNSSetMSyntheticFrontEnd<DataDescriptor_32, DataDescriptor_64>; +} + class NSSetCodeRunningSyntheticFrontEnd : public SyntheticChildrenFrontEnd { public: NSSetCodeRunningSyntheticFrontEnd(lldb::ValueObjectSP valobj_sp); @@ -283,7 +310,12 @@ lldb_private::formatters::NSSetSyntheticFrontEndCreator( if (!strcmp(class_name, "__NSSetI")) { return (new NSSetISyntheticFrontEnd(valobj_sp)); } else if (!strcmp(class_name, "__NSSetM")) { - return (new NSSetMSyntheticFrontEnd(valobj_sp)); + AppleObjCRuntime *apple_runtime = + llvm::dyn_cast_or_null<AppleObjCRuntime>(runtime); + if (apple_runtime && apple_runtime->GetFoundationVersion() >= 1400) + return (new Foundation1400::NSSetMSyntheticFrontEnd(valobj_sp)); + else + return (new Foundation1300::NSSetMSyntheticFrontEnd(valobj_sp)); } else { auto &map(NSSet_Additionals::GetAdditionalSynthetics()); auto iter = map.find(class_name_cs), end = map.end(); @@ -442,7 +474,9 @@ lldb_private::formatters::NSSetISyntheticFrontEnd::GetChildAtIndex(size_t idx) { return set_item.valobj_sp; } -lldb_private::formatters::NSSetMSyntheticFrontEnd::NSSetMSyntheticFrontEnd( +template <typename D32, typename D64> +lldb_private::formatters:: + GenericNSSetMSyntheticFrontEnd<D32, D64>::GenericNSSetMSyntheticFrontEnd( lldb::ValueObjectSP valobj_sp) : SyntheticChildrenFrontEnd(*valobj_sp), m_exe_ctx_ref(), m_ptr_size(8), m_data_32(nullptr), m_data_64(nullptr) { @@ -450,15 +484,19 @@ lldb_private::formatters::NSSetMSyntheticFrontEnd::NSSetMSyntheticFrontEnd( Update(); } -lldb_private::formatters::NSSetMSyntheticFrontEnd::~NSSetMSyntheticFrontEnd() { +template <typename D32, typename D64> +lldb_private::formatters:: + GenericNSSetMSyntheticFrontEnd<D32, D64>::~GenericNSSetMSyntheticFrontEnd() { delete m_data_32; m_data_32 = nullptr; delete m_data_64; m_data_64 = nullptr; } +template <typename D32, typename D64> size_t -lldb_private::formatters::NSSetMSyntheticFrontEnd::GetIndexOfChildWithName( +lldb_private::formatters:: + GenericNSSetMSyntheticFrontEnd<D32, D64>::GetIndexOfChildWithName( const ConstString &name) { const char *item_name = name.GetCString(); uint32_t idx = ExtractIndexFromString(item_name); @@ -467,14 +505,19 @@ lldb_private::formatters::NSSetMSyntheticFrontEnd::GetIndexOfChildWithName( return idx; } +template <typename D32, typename D64> size_t -lldb_private::formatters::NSSetMSyntheticFrontEnd::CalculateNumChildren() { +lldb_private::formatters:: + GenericNSSetMSyntheticFrontEnd<D32, D64>::CalculateNumChildren() { if (!m_data_32 && !m_data_64) return 0; return (m_data_32 ? m_data_32->_used : m_data_64->_used); } -bool lldb_private::formatters::NSSetMSyntheticFrontEnd::Update() { +template <typename D32, typename D64> +bool +lldb_private::formatters:: + GenericNSSetMSyntheticFrontEnd<D32, D64>::Update() { m_children.clear(); ValueObjectSP valobj_sp = m_backend.GetSP(); m_ptr_size = 0; @@ -500,12 +543,12 @@ bool lldb_private::formatters::NSSetMSyntheticFrontEnd::Update() { m_ptr_size = process_sp->GetAddressByteSize(); uint64_t data_location = valobj_sp->GetAddressOf() + m_ptr_size; if (m_ptr_size == 4) { - m_data_32 = new DataDescriptor_32(); - process_sp->ReadMemory(data_location, m_data_32, sizeof(DataDescriptor_32), + m_data_32 = new D32(); + process_sp->ReadMemory(data_location, m_data_32, sizeof(D32), error); } else { - m_data_64 = new DataDescriptor_64(); - process_sp->ReadMemory(data_location, m_data_64, sizeof(DataDescriptor_64), + m_data_64 = new D64(); + process_sp->ReadMemory(data_location, m_data_64, sizeof(D64), error); } if (error.Fail()) @@ -513,12 +556,17 @@ bool lldb_private::formatters::NSSetMSyntheticFrontEnd::Update() { return false; } -bool lldb_private::formatters::NSSetMSyntheticFrontEnd::MightHaveChildren() { +template <typename D32, typename D64> +bool +lldb_private::formatters:: + GenericNSSetMSyntheticFrontEnd<D32, D64>::MightHaveChildren() { return true; } +template <typename D32, typename D64> lldb::ValueObjectSP -lldb_private::formatters::NSSetMSyntheticFrontEnd::GetChildAtIndex(size_t idx) { +lldb_private::formatters:: + GenericNSSetMSyntheticFrontEnd<D32, D64>::GetChildAtIndex(size_t idx) { lldb::addr_t m_objs_addr = (m_data_32 ? m_data_32->_objs_addr : m_data_64->_objs_addr); diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp index f15bcaa13844..2a7735959a91 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp @@ -30,7 +30,6 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Core/Scalar.h" #include "lldb/Core/Section.h" -#include "lldb/Core/Timer.h" #include "lldb/Core/ValueObjectVariable.h" #include "lldb/Expression/DiagnosticManager.h" #include "lldb/Expression/FunctionCaller.h" @@ -55,6 +54,7 @@ #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" #include "AppleObjCClassDescriptorV2.h" #include "AppleObjCDeclVendor.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp b/contrib/llvm/tools/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp index 8a388a667372..25bfce7a2b83 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp @@ -31,11 +31,11 @@ typedef struct ar_hdr { #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/FileSystem.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/DataBufferLLVM.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/Timer.h" #include "llvm/Support/MemoryBuffer.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp b/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp index 20e9a930b486..3b33cf1601fb 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp @@ -19,7 +19,6 @@ #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" -#include "lldb/Core/Timer.h" #include "lldb/Symbol/DWARFCallFrameInfo.h" #include "lldb/Symbol/SymbolContext.h" #include "lldb/Target/SectionLoadList.h" @@ -28,6 +27,7 @@ #include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/Timer.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/StringRef.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.cpp b/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.cpp index 055a8219f154..06406c6f1655 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.cpp @@ -20,7 +20,6 @@ #include "lldb/Core/RangeMap.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/Host.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/Platform.h" @@ -32,6 +31,7 @@ #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" #include "lldb/Utility/UUID.h" #ifndef __APPLE__ diff --git a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp index 14bf0784dc2c..588f3f7aec64 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp @@ -22,7 +22,6 @@ #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/RegisterValue.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Core/ValueObjectVariable.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/ScriptInterpreter.h" @@ -35,6 +34,7 @@ #include "lldb/Target/ThreadList.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/StructuredData.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.h b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.h index 1eec30ef38c7..2e1680410962 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.h +++ b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.h @@ -16,8 +16,8 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Target/OperatingSystem.h" +#include "lldb/Utility/StructuredData.h" class DynamicRegisterInfo; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp index 0bd90dbf7620..1a4511a82230 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp @@ -15,11 +15,11 @@ // Project includes #include "lldb/Core/ArchSpec.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/StructuredData.h" #include "lldb/DataFormatters/FormatManager.h" #include "lldb/Host/StringConvert.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/StringExtractor.h" +#include "lldb/Utility/StructuredData.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.h b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.h index a30bfa1e1f16..228acfbed4ee 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.h @@ -17,8 +17,8 @@ // Other libraries and framework includes // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Utility/ConstString.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private.h" class DynamicRegisterInfo { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp index bce77d7e0a32..bd73a29e0871 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp @@ -297,6 +297,14 @@ void RegisterContextLLDB::InitializeNonZerothFrame() { return; } + ExecutionContext exe_ctx(m_thread.shared_from_this()); + Process *process = exe_ctx.GetProcessPtr(); + // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs + // this will strip bit zero in case we read a PC from memory or from the LR. + ABI *abi = process->GetABI().get(); + if (abi) + pc = abi->FixCodeAddress(pc); + if (log) { UnwindLogMsg("pc = 0x%" PRIx64, pc); addr_t reg_val; @@ -321,14 +329,6 @@ void RegisterContextLLDB::InitializeNonZerothFrame() { } } - ExecutionContext exe_ctx(m_thread.shared_from_this()); - Process *process = exe_ctx.GetProcessPtr(); - // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs - // this will strip bit zero in case we read a PC from memory or from the LR. - ABI *abi = process->GetABI().get(); - if (abi) - pc = abi->FixCodeAddress(pc); - const bool allow_section_end = true; m_current_pc.SetLoadAddress(pc, &process->GetTarget(), allow_section_end); @@ -2054,11 +2054,6 @@ bool RegisterContextLLDB::ReadPC(addr_t &pc) { // unwind past that frame to help // find the bug. - if (m_all_registers_available == false && above_trap_handler == false && - (pc == 0 || pc == 1)) { - return false; - } - ProcessSP process_sp (m_thread.GetProcess()); if (process_sp) { @@ -2066,6 +2061,12 @@ bool RegisterContextLLDB::ReadPC(addr_t &pc) { if (abi) pc = abi->FixCodeAddress(pc); } + + if (m_all_registers_available == false && above_trap_handler == false && + (pc == 0 || pc == 1)) { + return false; + } + return true; } else { return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h index 6306651da7a1..a38110faaec6 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h @@ -23,9 +23,9 @@ // Other libraries and framework includes // Project includes #include "lldb/Core/ArchSpec.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Target/Process.h" #include "lldb/Utility/StreamGDBRemote.h" +#include "lldb/Utility/StructuredData.h" #include "llvm/ADT/Optional.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp index d34a79453fed..7523260c13e4 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp @@ -1250,9 +1250,9 @@ GDBRemoteCommunicationServerLLGS::Handle_jTraceRead( lldb::user_id_t uid = LLDB_INVALID_UID; - size_t byte_count = std::numeric_limits<size_t>::max(); + uint64_t byte_count = std::numeric_limits<uint64_t>::max(); lldb::tid_t tid = LLDB_INVALID_THREAD_ID; - size_t offset = std::numeric_limits<size_t>::max(); + uint64_t offset = std::numeric_limits<uint64_t>::max(); auto json_object = StructuredData::ParseJSON(packet.Peek()); @@ -1286,8 +1286,8 @@ GDBRemoteCommunicationServerLLGS::Handle_jTraceRead( if (error.Fail()) return SendErrorResponse(error.GetError()); - for (size_t i = 0; i < buf.size(); ++i) - response.PutHex8(buf[i]); + for (auto i : buf) + response.PutHex8(i); StreamGDBRemote escaped_response; escaped_response.PutEscapedBytes(response.GetData(), response.GetSize()); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp index 73e3732df3ef..977c34c2a69b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp @@ -22,7 +22,6 @@ #include "llvm/Support/FileSystem.h" #include "llvm/Support/Threading.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Host/Config.h" #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/Host.h" @@ -35,6 +34,7 @@ #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamGDBRemote.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/Utility/UriParser.h" // Project includes diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp index f3c7e77d9daa..98b64510f59f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp @@ -35,7 +35,6 @@ #include "lldb/Core/PluginManager.h" #include "lldb/Core/State.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/Timer.h" #include "lldb/Core/Value.h" #include "lldb/DataFormatters/FormatManager.h" #include "lldb/Host/ConnectionFileDescriptor.h" @@ -66,6 +65,7 @@ #include "lldb/Utility/CleanUp.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" // Project includes #include "GDBRemoteRegisterContext.h" @@ -599,7 +599,7 @@ void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) { // gets called in DidAttach, when the target architecture (and // consequently the ABI we'll get from // the process) may be wrong. - ABISP abi_to_use = ABI::FindPlugin(arch_to_use); + ABISP abi_to_use = ABI::FindPlugin(shared_from_this(), arch_to_use); AugmentRegisterInfoViaABI(reg_info, reg_name, abi_to_use); @@ -4421,7 +4421,7 @@ bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { // that context we haven't // set the Target's architecture yet, so the ABI is also potentially // incorrect. - ABISP abi_to_use_sp = ABI::FindPlugin(arch_to_use); + ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use); if (feature_node) { ParseRegisters(feature_node, target_info, this->m_register_info, abi_to_use_sp, cur_reg_num, reg_offset); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h index d7a4e961b540..54a472d7332e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h @@ -24,7 +24,6 @@ #include "lldb/Core/Broadcaster.h" #include "lldb/Core/LoadedModuleInfoList.h" #include "lldb/Core/ModuleSpec.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Core/ThreadSafeValue.h" #include "lldb/Host/HostThread.h" #include "lldb/Target/Process.h" @@ -35,6 +34,7 @@ #include "lldb/Utility/StreamString.h" #include "lldb/Utility/StringExtractor.h" #include "lldb/Utility/StringList.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-private-forward.h" #include "GDBRemoteCommunicationClient.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h index 27caf42fc4a5..1a5b60aea288 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ThreadGDBRemote.h @@ -16,9 +16,9 @@ // Other libraries and framework includes // Project includes -#include "lldb/Core/StructuredData.h" #include "lldb/Target/Process.h" #include "lldb/Target/Thread.h" +#include "lldb/Utility/StructuredData.h" class StringExtractor; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h b/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h index e613e3d6aa6c..beeb64782367 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h @@ -21,10 +21,10 @@ // Project includes #include "lldb/Utility/Flags.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Host/File.h" #include "lldb/Interpreter/OptionValue.h" #include "lldb/Utility/ConstString.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/lldb-defines.h" #include "llvm/ADT/ArrayRef.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp b/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp index d6d695fc2e74..b7fbd7347d08 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp @@ -33,7 +33,6 @@ #include "lldb/Core/Communication.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" -#include "lldb/Core/Timer.h" #include "lldb/Core/ValueObject.h" #include "lldb/DataFormatters/TypeSummary.h" #include "lldb/Host/ConnectionFileDescriptor.h" @@ -44,6 +43,7 @@ #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlan.h" +#include "lldb/Utility/Timer.h" #if defined(_WIN32) #include "lldb/Host/windows/ConnectionGenericFileWindows.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp index fc97a76de59b..79b2acc4b4f3 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp @@ -13,13 +13,13 @@ #include "lldb/Core/DumpDataExtractor.h" #include "lldb/Core/Mangled.h" #include "lldb/Core/Module.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/StringConvert.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/LineTable.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" #include "DWARFDIECollection.h" #include "DWARFDebugAbbrev.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp index e923225f1d98..13c2d8726821 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp @@ -14,9 +14,9 @@ #include <algorithm> -#include "lldb/Core/Timer.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/Timer.h" #include "DWARFCompileUnit.h" #include "DWARFDebugInfo.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp index 67d8828c4516..694d34fc211c 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp @@ -14,9 +14,9 @@ #include "lldb/Core/FileSpecList.h" #include "lldb/Core/Module.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/Host.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Timer.h" #include "LogChannelDWARF.h" #include "SymbolFileDWARF.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnames.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnames.cpp index 04bc2f497075..766899c497b0 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnames.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnames.cpp @@ -9,8 +9,8 @@ #include "DWARFDebugPubnames.h" -#include "lldb/Core/Timer.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/Timer.h" #include "DWARFCompileUnit.h" #include "DWARFDIECollection.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp index 252a9807a3b5..ef18c2b5d3ba 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp @@ -21,10 +21,10 @@ #include "lldb/Core/Scalar.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/Timer.h" #include "lldb/Core/Value.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp index ad009a02a2aa..eabff86a5428 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp @@ -22,12 +22,12 @@ #include "lldb/Core/Section.h" #include "lldb/Host/FileSystem.h" #include "lldb/Utility/RegularExpression.h" +#include "lldb/Utility/Timer.h" //#define DEBUG_OSO_DMAP // DO NOT CHECKIN WITH THIS NOT COMMENTED OUT #if defined(DEBUG_OSO_DMAP) #include "lldb/Core/StreamFile.h" #endif -#include "lldb/Core/Timer.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/LineTable.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.cpp index 094e48cf00e1..dbc1b9ee5470 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.cpp @@ -10,7 +10,6 @@ #include "SymbolFileSymtab.h" #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" -#include "lldb/Core/Timer.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/Function.h" #include "lldb/Symbol/ObjectFile.h" @@ -19,6 +18,7 @@ #include "lldb/Symbol/Symtab.h" #include "lldb/Symbol/TypeList.h" #include "lldb/Utility/RegularExpression.h" +#include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp index 5a377d7b04f7..f952696ab21d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp @@ -15,11 +15,11 @@ #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/Host.h" #include "lldb/Host/Symbols.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp b/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp index 9aad2e1e70e2..9d79a411faad 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp @@ -452,6 +452,33 @@ bool x86AssemblyInspectionEngine::lea_rsp_pattern_p(int &amount) { return false; } +// lea -0x28(%ebp), %esp +// (32-bit and 64-bit variants, 8-bit and 32-bit displacement) +bool x86AssemblyInspectionEngine::lea_rbp_rsp_pattern_p(int &amount) { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + + // Check opcode + if (*p != 0x8d) + return false; + ++p; + + // 8 bit displacement + if (*p == 0x65) { + amount = (int8_t)p[1]; + return true; + } + + // 32 bit displacement + if (*p == 0xa5) { + amount = (int32_t)extract_4(p + 1); + return true; + } + + return false; +} + // popq %rbx // popl %ebx bool x86AssemblyInspectionEngine::pop_reg_p(int ®no) { @@ -843,6 +870,12 @@ bool x86AssemblyInspectionEngine::GetNonCallSiteUnwindPlanFromAssembly( in_epilogue = true; } + else if (lea_rbp_rsp_pattern_p(stack_offset) && + row->GetCFAValue().GetRegisterNumber() == m_lldb_fp_regnum) { + current_sp_bytes_offset_from_cfa = + row->GetCFAValue().GetOffset() - stack_offset; + } + else if (ret_pattern_p() && prologue_completed_row.get()) { // Reinstate the saved prologue setup for any instructions // that come after the ret instruction diff --git a/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h b/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h index 1c84c89aee83..2e7875966cb6 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h +++ b/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h @@ -102,6 +102,7 @@ private: bool sub_rsp_pattern_p(int &amount); bool add_rsp_pattern_p(int &amount); bool lea_rsp_pattern_p(int &amount); + bool lea_rbp_rsp_pattern_p(int &amount); bool push_reg_p(int ®no); bool pop_reg_p(int ®no); bool pop_rbp_pattern_p(); diff --git a/contrib/llvm/tools/lldb/source/Symbol/DWARFCallFrameInfo.cpp b/contrib/llvm/tools/lldb/source/Symbol/DWARFCallFrameInfo.cpp index 015ecd856aa8..9b1f8c694ccf 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/DWARFCallFrameInfo.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/DWARFCallFrameInfo.cpp @@ -14,7 +14,6 @@ #include "lldb/Core/ArchSpec.h" #include "lldb/Core/Module.h" #include "lldb/Core/Section.h" -#include "lldb/Core/Timer.h" #include "lldb/Core/dwarf.h" #include "lldb/Host/Host.h" #include "lldb/Symbol/DWARFCallFrameInfo.h" @@ -23,6 +22,7 @@ #include "lldb/Target/RegisterContext.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; @@ -151,17 +151,8 @@ GetGNUEHPointer(const DataExtractor &DE, offset_t *offset_ptr, } DWARFCallFrameInfo::DWARFCallFrameInfo(ObjectFile &objfile, - SectionSP §ion_sp, - lldb::RegisterKind reg_kind, - bool is_eh_frame) - : m_objfile(objfile), m_section_sp(section_sp), - m_reg_kind(reg_kind), // The flavor of registers that the CFI data uses - // (enum RegisterKind) - m_flags(), m_cie_map(), m_cfi_data(), m_cfi_data_initialized(false), - m_fde_index(), m_fde_index_initialized(false), - m_is_eh_frame(is_eh_frame) {} - -DWARFCallFrameInfo::~DWARFCallFrameInfo() {} + SectionSP §ion_sp, Type type) + : m_objfile(objfile), m_section_sp(section_sp), m_type(type) {} bool DWARFCallFrameInfo::GetUnwindPlan(Address addr, UnwindPlan &unwind_plan) { FDEEntryMap::Entry fde_entry; @@ -268,14 +259,20 @@ DWARFCallFrameInfo::ParseCIE(const dw_offset_t cie_offset) { cie_id = m_cfi_data.GetU32(&offset); end_offset = cie_offset + length + 4; } - if (length > 0 && ((!m_is_eh_frame && cie_id == UINT32_MAX) || - (m_is_eh_frame && cie_id == 0ul))) { + if (length > 0 && ((m_type == DWARF && cie_id == UINT32_MAX) || + (m_type == EH && cie_id == 0ul))) { size_t i; // cie.offset = cie_offset; // cie.length = length; // cie.cieID = cieID; cie_sp->ptr_encoding = DW_EH_PE_absptr; // default cie_sp->version = m_cfi_data.GetU8(&offset); + if (cie_sp->version > CFI_VERSION4) { + Host::SystemLog(Host::eSystemLogError, + "CIE parse error: CFI version %d is not supported\n", + cie_sp->version); + return nullptr; + } for (i = 0; i < CFI_AUG_MAX_SIZE; ++i) { cie_sp->augmentation[i] = m_cfi_data.GetU8(&offset); @@ -294,11 +291,23 @@ DWARFCallFrameInfo::ParseCIE(const dw_offset_t cie_offset) { "CIE parse error: CIE augmentation string was too large " "for the fixed sized buffer of %d bytes.\n", CFI_AUG_MAX_SIZE); - return cie_sp; + return nullptr; } + + // m_cfi_data uses address size from target architecture of the process + // may ignore these fields? + if (m_type == DWARF && cie_sp->version >= CFI_VERSION4) { + cie_sp->address_size = m_cfi_data.GetU8(&offset); + cie_sp->segment_size = m_cfi_data.GetU8(&offset); + } + cie_sp->code_align = (uint32_t)m_cfi_data.GetULEB128(&offset); cie_sp->data_align = (int32_t)m_cfi_data.GetSLEB128(&offset); - cie_sp->return_addr_reg_num = m_cfi_data.GetU8(&offset); + + cie_sp->return_addr_reg_num = + m_type == DWARF && cie_sp->version >= CFI_VERSION3 + ? static_cast<uint32_t>(m_cfi_data.GetULEB128(&offset)) + : m_cfi_data.GetU8(&offset); if (cie_sp->augmentation[0]) { // Get the length of the eh_frame augmentation data @@ -461,11 +470,33 @@ void DWARFCallFrameInfo::GetFDEIndex() { m_fde_index_initialized = true; return; } + + // An FDE entry contains CIE_pointer in debug_frame in same place as cie_id + // in eh_frame. CIE_pointer is an offset into the .debug_frame section. + // So, variable cie_offset should be equal to cie_id for debug_frame. + // FDE entries with cie_id == 0 shouldn't be ignored for it. + if ((cie_id == 0 && m_type == EH) || cie_id == UINT32_MAX || len == 0) { + auto cie_sp = ParseCIE(current_entry); + if (!cie_sp) { + // Cannot parse, the reason is already logged + m_fde_index.Clear(); + m_fde_index_initialized = true; + return; + } + + m_cie_map[current_entry] = std::move(cie_sp); + offset = next_entry; + continue; + } + + if (m_type == DWARF) + cie_offset = cie_id; + if (cie_offset > m_cfi_data.GetByteSize()) { - Host::SystemLog( - Host::eSystemLogError, - "error: Invalid cie offset of 0x%x found in cie/fde at 0x%x\n", - cie_offset, current_entry); + Host::SystemLog(Host::eSystemLogError, + "error: Invalid cie offset of 0x%x " + "found in cie/fde at 0x%x\n", + cie_offset, current_entry); // Don't trust anything in this eh_frame section if we find blatantly // invalid data. m_fde_index.Clear(); @@ -473,12 +504,6 @@ void DWARFCallFrameInfo::GetFDEIndex() { return; } - if (cie_id == 0 || cie_id == UINT32_MAX || len == 0) { - m_cie_map[current_entry] = ParseCIE(current_entry); - offset = next_entry; - continue; - } - const CIE *cie = GetCIE(cie_offset); if (cie) { const lldb::addr_t pc_rel_addr = m_section_sp->GetFileAddress(); @@ -531,12 +556,13 @@ bool DWARFCallFrameInfo::FDEToUnwindPlan(dw_offset_t dwarf_offset, cie_offset = m_cfi_data.GetU32(&offset); } - assert(cie_offset != 0 && cie_offset != UINT32_MAX); + // FDE entries with zeroth cie_offset may occur for debug_frame. + assert(!(m_type == EH && 0 == cie_offset) && cie_offset != UINT32_MAX); // Translate the CIE_id from the eh_frame format, which // is relative to the FDE offset, into a __eh_frame section // offset - if (m_is_eh_frame) { + if (m_type == EH) { unwind_plan.SetSourceName("eh_frame CFI"); cie_offset = current_entry + (is_64bit ? 12 : 4) - cie_offset; unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolNo); @@ -611,7 +637,7 @@ bool DWARFCallFrameInfo::FDEToUnwindPlan(dw_offset_t dwarf_offset, *cie_initial_row = cie->initial_row; UnwindPlan::RowSP row(cie_initial_row); - unwind_plan.SetRegisterKind(m_reg_kind); + unwind_plan.SetRegisterKind(GetRegisterKind()); unwind_plan.SetReturnAddressRegister(cie->return_addr_reg_num); std::vector<UnwindPlan::RowSP> stack; diff --git a/contrib/llvm/tools/lldb/source/Symbol/FuncUnwinders.cpp b/contrib/llvm/tools/lldb/source/Symbol/FuncUnwinders.cpp index 3b94e250dac7..b9f50cd1b12f 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/FuncUnwinders.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/FuncUnwinders.cpp @@ -39,7 +39,9 @@ FuncUnwinders::FuncUnwinders(UnwindTable &unwind_table, AddressRange range) m_unwind_plan_arch_default_sp(), m_unwind_plan_arch_default_at_func_entry_sp(), m_tried_unwind_plan_assembly(false), m_tried_unwind_plan_eh_frame(false), + m_tried_unwind_plan_debug_frame(false), m_tried_unwind_plan_eh_frame_augmented(false), + m_tried_unwind_plan_debug_frame_augmented(false), m_tried_unwind_plan_compact_unwind(false), m_tried_unwind_plan_arm_unwind(false), m_tried_unwind_fast(false), m_tried_unwind_arch_default(false), @@ -56,17 +58,14 @@ UnwindPlanSP FuncUnwinders::GetUnwindPlanAtCallSite(Target &target, int current_offset) { std::lock_guard<std::recursive_mutex> guard(m_mutex); - UnwindPlanSP unwind_plan_sp = GetEHFrameUnwindPlan(target, current_offset); - if (unwind_plan_sp) - return unwind_plan_sp; - - unwind_plan_sp = GetCompactUnwindUnwindPlan(target, current_offset); - if (unwind_plan_sp) - return unwind_plan_sp; - - unwind_plan_sp = GetArmUnwindUnwindPlan(target, current_offset); - if (unwind_plan_sp) - return unwind_plan_sp; + if (UnwindPlanSP plan_sp = GetEHFrameUnwindPlan(target, current_offset)) + return plan_sp; + if (UnwindPlanSP plan_sp = GetDebugFrameUnwindPlan(target, current_offset)) + return plan_sp; + if (UnwindPlanSP plan_sp = GetCompactUnwindUnwindPlan(target, current_offset)) + return plan_sp; + if (UnwindPlanSP plan_sp = GetArmUnwindUnwindPlan(target, current_offset)) + return plan_sp; return nullptr; } @@ -121,6 +120,29 @@ UnwindPlanSP FuncUnwinders::GetEHFrameUnwindPlan(Target &target, return m_unwind_plan_eh_frame_sp; } +UnwindPlanSP FuncUnwinders::GetDebugFrameUnwindPlan(Target &target, + int current_offset) { + std::lock_guard<std::recursive_mutex> guard(m_mutex); + if (m_unwind_plan_debug_frame_sp || m_tried_unwind_plan_debug_frame) + return m_unwind_plan_debug_frame_sp; + + m_tried_unwind_plan_debug_frame = true; + if (m_range.GetBaseAddress().IsValid()) { + Address current_pc(m_range.GetBaseAddress()); + if (current_offset != -1) + current_pc.SetOffset(current_pc.GetOffset() + current_offset); + DWARFCallFrameInfo *debug_frame = m_unwind_table.GetDebugFrameInfo(); + if (debug_frame) { + m_unwind_plan_debug_frame_sp.reset( + new UnwindPlan(lldb::eRegisterKindGeneric)); + if (!debug_frame->GetUnwindPlan(current_pc, + *m_unwind_plan_debug_frame_sp)) + m_unwind_plan_debug_frame_sp.reset(); + } + } + return m_unwind_plan_debug_frame_sp; +} + UnwindPlanSP FuncUnwinders::GetArmUnwindUnwindPlan(Target &target, int current_offset) { std::lock_guard<std::recursive_mutex> guard(m_mutex); @@ -187,6 +209,48 @@ UnwindPlanSP FuncUnwinders::GetEHFrameAugmentedUnwindPlan(Target &target, return m_unwind_plan_eh_frame_augmented_sp; } +UnwindPlanSP +FuncUnwinders::GetDebugFrameAugmentedUnwindPlan(Target &target, Thread &thread, + int current_offset) { + std::lock_guard<std::recursive_mutex> guard(m_mutex); + if (m_unwind_plan_debug_frame_augmented_sp.get() || + m_tried_unwind_plan_debug_frame_augmented) + return m_unwind_plan_debug_frame_augmented_sp; + + // Only supported on x86 architectures where we get debug_frame from the + // compiler that describes the prologue instructions perfectly, and sometimes + // the epilogue instructions too. + if (target.GetArchitecture().GetCore() != ArchSpec::eCore_x86_32_i386 && + target.GetArchitecture().GetCore() != ArchSpec::eCore_x86_64_x86_64 && + target.GetArchitecture().GetCore() != ArchSpec::eCore_x86_64_x86_64h) { + m_tried_unwind_plan_debug_frame_augmented = true; + return m_unwind_plan_debug_frame_augmented_sp; + } + + m_tried_unwind_plan_debug_frame_augmented = true; + + UnwindPlanSP debug_frame_plan = + GetDebugFrameUnwindPlan(target, current_offset); + if (!debug_frame_plan) + return m_unwind_plan_debug_frame_augmented_sp; + + m_unwind_plan_debug_frame_augmented_sp.reset( + new UnwindPlan(*debug_frame_plan)); + + // Augment the debug_frame instructions with epilogue descriptions if + // necessary so the UnwindPlan can be used at any instruction in the function. + + UnwindAssemblySP assembly_profiler_sp(GetUnwindAssemblyProfiler(target)); + if (assembly_profiler_sp) { + if (!assembly_profiler_sp->AugmentUnwindPlanFromCallSite( + m_range, thread, *m_unwind_plan_debug_frame_augmented_sp)) { + m_unwind_plan_debug_frame_augmented_sp.reset(); + } + } else + m_unwind_plan_debug_frame_augmented_sp.reset(); + return m_unwind_plan_debug_frame_augmented_sp; +} + UnwindPlanSP FuncUnwinders::GetAssemblyUnwindPlan(Target &target, Thread &thread, int current_offset) { @@ -248,6 +312,8 @@ UnwindPlanSP FuncUnwinders::GetUnwindPlanAtNonCallSite(Target &target, Thread &thread, int current_offset) { UnwindPlanSP eh_frame_sp = GetEHFrameUnwindPlan(target, current_offset); + if (!eh_frame_sp) + eh_frame_sp = GetDebugFrameUnwindPlan(target, current_offset); UnwindPlanSP arch_default_at_entry_sp = GetUnwindPlanArchitectureDefaultAtFunctionEntry(thread); UnwindPlanSP arch_default_sp = GetUnwindPlanArchitectureDefault(thread); @@ -255,28 +321,22 @@ UnwindPlanSP FuncUnwinders::GetUnwindPlanAtNonCallSite(Target &target, GetAssemblyUnwindPlan(target, thread, current_offset); // This point of this code is to detect when a function is using a - // non-standard ABI, and the eh_frame - // correctly describes that alternate ABI. This is addressing a specific - // situation on x86_64 linux - // systems where one function in a library pushes a value on the stack and - // jumps to another function. - // So using an assembly instruction based unwind will not work when you're in - // the second function - - // the stack has been modified in a non-ABI way. But we have eh_frame that - // correctly describes how to - // unwind from this location. So we're looking to see if the initial pc - // register save location from - // the eh_frame is different from the assembly unwind, the arch default - // unwind, and the arch default at - // initial function entry. + // non-standard ABI, and the eh_frame correctly describes that alternate ABI. + // This is addressing a specific situation on x86_64 linux systems where one + // function in a library pushes a value on the stack and jumps to another + // function. So using an assembly instruction based unwind will not work when + // you're in the second function - the stack has been modified in a non-ABI + // way. But we have eh_frame that correctly describes how to unwind from this + // location. So we're looking to see if the initial pc register save location + // from the eh_frame is different from the assembly unwind, the arch default + // unwind, and the arch default at initial function entry. // // We may have eh_frame that describes the entire function -- or we may have - // eh_frame that only describes - // the unwind after the prologue has executed -- so we need to check both the - // arch default (once the prologue - // has executed) and the arch default at initial function entry. And we may - // be running on a target where - // we have only some of the assembly/arch default unwind plans available. + // eh_frame that only describes the unwind after the prologue has executed -- + // so we need to check both the arch default (once the prologue has executed) + // and the arch default at initial function entry. And we may be running on a + // target where we have only some of the assembly/arch default unwind plans + // available. if (CompareUnwindPlansForIdenticalInitialPCLocation( thread, eh_frame_sp, arch_default_at_entry_sp) == eLazyBoolNo && @@ -287,11 +347,12 @@ UnwindPlanSP FuncUnwinders::GetUnwindPlanAtNonCallSite(Target &target, return eh_frame_sp; } - UnwindPlanSP eh_frame_augmented_sp = - GetEHFrameAugmentedUnwindPlan(target, thread, current_offset); - if (eh_frame_augmented_sp) { - return eh_frame_augmented_sp; - } + if (UnwindPlanSP plan_sp = + GetEHFrameAugmentedUnwindPlan(target, thread, current_offset)) + return plan_sp; + if (UnwindPlanSP plan_sp = + GetDebugFrameAugmentedUnwindPlan(target, thread, current_offset)) + return plan_sp; return assembly_sp; } diff --git a/contrib/llvm/tools/lldb/source/Symbol/ObjectFile.cpp b/contrib/llvm/tools/lldb/source/Symbol/ObjectFile.cpp index c970de6fef06..fd4180862c15 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/ObjectFile.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/ObjectFile.cpp @@ -13,7 +13,6 @@ #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" -#include "lldb/Core/Timer.h" #include "lldb/Symbol/ObjectContainer.h" #include "lldb/Symbol/SymbolFile.h" #include "lldb/Target/Process.h" @@ -25,6 +24,7 @@ #include "lldb/Utility/DataBufferLLVM.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/RegularExpression.h" +#include "lldb/Utility/Timer.h" #include "lldb/lldb-private.h" using namespace lldb; diff --git a/contrib/llvm/tools/lldb/source/Symbol/Symtab.cpp b/contrib/llvm/tools/lldb/source/Symbol/Symtab.cpp index 3eec3e706185..3e2c965509d3 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/Symtab.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/Symtab.cpp @@ -13,15 +13,15 @@ #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" #include "Plugins/Language/ObjC/ObjCLanguage.h" #include "lldb/Core/Module.h" -#include "lldb/Core/Section.h" #include "lldb/Core/STLUtils.h" -#include "lldb/Core/Timer.h" +#include "lldb/Core/Section.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Symbol/SymbolContext.h" #include "lldb/Symbol/Symtab.h" #include "lldb/Utility/RegularExpression.h" #include "lldb/Utility/Stream.h" +#include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Symbol/UnwindTable.cpp b/contrib/llvm/tools/lldb/source/Symbol/UnwindTable.cpp index 336f0c3e04a7..405d57754ea5 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/UnwindTable.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/UnwindTable.cpp @@ -44,38 +44,64 @@ void UnwindTable::Initialize() { if (m_initialized) // check again once we've acquired the lock return; + m_initialized = true; SectionList *sl = m_object_file.GetSectionList(); - if (sl) { - SectionSP sect = sl->FindSectionByType(eSectionTypeEHFrame, true); - if (sect.get()) { - m_eh_frame_up.reset(new DWARFCallFrameInfo(m_object_file, sect, - eRegisterKindEHFrame, true)); - } - sect = sl->FindSectionByType(eSectionTypeCompactUnwind, true); - if (sect.get()) { - m_compact_unwind_up.reset(new CompactUnwindInfo(m_object_file, sect)); - } - sect = sl->FindSectionByType(eSectionTypeARMexidx, true); - if (sect.get()) { - SectionSP sect_extab = sl->FindSectionByType(eSectionTypeARMextab, true); - if (sect_extab.get()) { - m_arm_unwind_up.reset( - new ArmUnwindInfo(m_object_file, sect, sect_extab)); - } - } + if (!sl) + return; + + SectionSP sect = sl->FindSectionByType(eSectionTypeEHFrame, true); + if (sect.get()) { + m_eh_frame_up.reset( + new DWARFCallFrameInfo(m_object_file, sect, DWARFCallFrameInfo::EH)); } - m_initialized = true; + sect = sl->FindSectionByType(eSectionTypeDWARFDebugFrame, true); + if (sect) { + m_debug_frame_up.reset( + new DWARFCallFrameInfo(m_object_file, sect, DWARFCallFrameInfo::DWARF)); + } + + sect = sl->FindSectionByType(eSectionTypeCompactUnwind, true); + if (sect) { + m_compact_unwind_up.reset(new CompactUnwindInfo(m_object_file, sect)); + } + + sect = sl->FindSectionByType(eSectionTypeARMexidx, true); + if (sect) { + SectionSP sect_extab = sl->FindSectionByType(eSectionTypeARMextab, true); + if (sect_extab.get()) { + m_arm_unwind_up.reset(new ArmUnwindInfo(m_object_file, sect, sect_extab)); + } + } } UnwindTable::~UnwindTable() {} +llvm::Optional<AddressRange> UnwindTable::GetAddressRange(const Address &addr, + SymbolContext &sc) { + AddressRange range; + + // First check the symbol context + if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0, + false, range) && + range.GetBaseAddress().IsValid()) + return range; + + // Does the eh_frame unwind info has a function bounds for this addr? + if (m_eh_frame_up && m_eh_frame_up->GetAddressRange(addr, range)) + return range; + + // Try debug_frame as well + if (m_debug_frame_up && m_debug_frame_up->GetAddressRange(addr, range)) + return range; + + return llvm::None; +} + FuncUnwindersSP UnwindTable::GetFuncUnwindersContainingAddress(const Address &addr, SymbolContext &sc) { - FuncUnwindersSP no_unwind_found; - Initialize(); std::lock_guard<std::mutex> guard(m_mutex); @@ -96,23 +122,14 @@ UnwindTable::GetFuncUnwindersContainingAddress(const Address &addr, return pos->second; } - AddressRange range; - if (!sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0, - false, range) || - !range.GetBaseAddress().IsValid()) { - // Does the eh_frame unwind info has a function bounds for this addr? - if (m_eh_frame_up == nullptr || - !m_eh_frame_up->GetAddressRange(addr, range)) { - return no_unwind_found; - } - } + auto range_or = GetAddressRange(addr, sc); + if (!range_or) + return nullptr; - FuncUnwindersSP func_unwinder_sp(new FuncUnwinders(*this, range)); + FuncUnwindersSP func_unwinder_sp(new FuncUnwinders(*this, *range_or)); m_unwinds.insert(insert_pos, - std::make_pair(range.GetBaseAddress().GetFileAddress(), + std::make_pair(range_or->GetBaseAddress().GetFileAddress(), func_unwinder_sp)); - // StreamFile s(stdout, false); - // Dump (s); return func_unwinder_sp; } @@ -121,26 +138,16 @@ UnwindTable::GetFuncUnwindersContainingAddress(const Address &addr, // UnwindTable. This is intended for use by target modules show-unwind where we // want to create // new UnwindPlans, not re-use existing ones. - FuncUnwindersSP UnwindTable::GetUncachedFuncUnwindersContainingAddress(const Address &addr, SymbolContext &sc) { - FuncUnwindersSP no_unwind_found; Initialize(); - AddressRange range; - if (!sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0, - false, range) || - !range.GetBaseAddress().IsValid()) { - // Does the eh_frame unwind info has a function bounds for this addr? - if (m_eh_frame_up == nullptr || - !m_eh_frame_up->GetAddressRange(addr, range)) { - return no_unwind_found; - } - } + auto range_or = GetAddressRange(addr, sc); + if (!range_or) + return nullptr; - FuncUnwindersSP func_unwinder_sp(new FuncUnwinders(*this, range)); - return func_unwinder_sp; + return std::make_shared<FuncUnwinders>(*this, *range_or); } void UnwindTable::Dump(Stream &s) { @@ -161,6 +168,11 @@ DWARFCallFrameInfo *UnwindTable::GetEHFrameInfo() { return m_eh_frame_up.get(); } +DWARFCallFrameInfo *UnwindTable::GetDebugFrameInfo() { + Initialize(); + return m_debug_frame_up.get(); +} + CompactUnwindInfo *UnwindTable::GetCompactUnwindInfo() { Initialize(); return m_compact_unwind_up.get(); diff --git a/contrib/llvm/tools/lldb/source/Symbol/Variable.cpp b/contrib/llvm/tools/lldb/source/Symbol/Variable.cpp index fd19a0994966..ff32aa731465 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/Variable.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/Variable.cpp @@ -160,7 +160,7 @@ void Variable::Dump(Stream *s, bool show_context) const { if (m_owner_scope) { ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule()); if (module_sp) - abi = ABI::FindPlugin(module_sp->GetArchitecture()).get(); + abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture()).get(); } m_location.GetDescription(s, lldb::eDescriptionLevelBrief, loclist_base_addr, abi); @@ -471,7 +471,7 @@ bool Variable::DumpLocationForAddress(Stream *s, const Address &address) { if (m_owner_scope) { ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule()); if (module_sp) - abi = ABI::FindPlugin(module_sp->GetArchitecture()).get(); + abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture()).get(); } const addr_t file_addr = address.GetFileAddress(); diff --git a/contrib/llvm/tools/lldb/source/Target/ABI.cpp b/contrib/llvm/tools/lldb/source/Target/ABI.cpp index 87363a3b8aeb..72f58be5a3d4 100644 --- a/contrib/llvm/tools/lldb/source/Target/ABI.cpp +++ b/contrib/llvm/tools/lldb/source/Target/ABI.cpp @@ -25,7 +25,7 @@ using namespace lldb; using namespace lldb_private; ABISP -ABI::FindPlugin(const ArchSpec &arch) { +ABI::FindPlugin(lldb::ProcessSP process_sp, const ArchSpec &arch) { ABISP abi_sp; ABICreateInstance create_callback; @@ -33,7 +33,7 @@ ABI::FindPlugin(const ArchSpec &arch) { (create_callback = PluginManager::GetABICreateCallbackAtIndex(idx)) != nullptr; ++idx) { - abi_sp = create_callback(arch); + abi_sp = create_callback(process_sp, arch); if (abi_sp) return abi_sp; @@ -42,8 +42,6 @@ ABI::FindPlugin(const ArchSpec &arch) { return abi_sp; } -ABI::ABI() = default; - ABI::~ABI() = default; bool ABI::GetRegisterInfoByName(const ConstString &name, RegisterInfo &info) { diff --git a/contrib/llvm/tools/lldb/source/Target/ObjCLanguageRuntime.cpp b/contrib/llvm/tools/lldb/source/Target/ObjCLanguageRuntime.cpp index 165c75a0952b..d3cc7c019dce 100644 --- a/contrib/llvm/tools/lldb/source/Target/ObjCLanguageRuntime.cpp +++ b/contrib/llvm/tools/lldb/source/Target/ObjCLanguageRuntime.cpp @@ -11,7 +11,6 @@ #include "lldb/Core/MappedHash.h" #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" -#include "lldb/Core/Timer.h" #include "lldb/Core/ValueObject.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/SymbolContext.h" @@ -21,6 +20,7 @@ #include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Timer.h" #include "llvm/ADT/StringRef.h" diff --git a/contrib/llvm/tools/lldb/source/Target/Platform.cpp b/contrib/llvm/tools/lldb/source/Target/Platform.cpp index cfd971e9de62..498facf8e0d0 100644 --- a/contrib/llvm/tools/lldb/source/Target/Platform.cpp +++ b/contrib/llvm/tools/lldb/source/Target/Platform.cpp @@ -25,7 +25,6 @@ #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" @@ -42,6 +41,7 @@ #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" +#include "lldb/Utility/StructuredData.h" #include "llvm/Support/FileSystem.h" diff --git a/contrib/llvm/tools/lldb/source/Target/Process.cpp b/contrib/llvm/tools/lldb/source/Target/Process.cpp index c6ad536cee10..6cbe289ef26b 100644 --- a/contrib/llvm/tools/lldb/source/Target/Process.cpp +++ b/contrib/llvm/tools/lldb/source/Target/Process.cpp @@ -1735,7 +1735,7 @@ addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; } const lldb::ABISP &Process::GetABI() { if (!m_abi_sp) - m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture()); + m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture()); return m_abi_sp; } diff --git a/contrib/llvm/tools/lldb/source/Target/Target.cpp b/contrib/llvm/tools/lldb/source/Target/Target.cpp index 5c46a024be60..4632ada26ed3 100644 --- a/contrib/llvm/tools/lldb/source/Target/Target.cpp +++ b/contrib/llvm/tools/lldb/source/Target/Target.cpp @@ -30,7 +30,6 @@ #include "lldb/Core/SourceManager.h" #include "lldb/Core/State.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/Timer.h" #include "lldb/Core/ValueObject.h" #include "lldb/Expression/REPL.h" #include "lldb/Expression/UserExpression.h" @@ -58,6 +57,7 @@ #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" +#include "lldb/Utility/Timer.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Target/TargetList.cpp b/contrib/llvm/tools/lldb/source/Target/TargetList.cpp index 43e1227ba205..5c652aced39f 100644 --- a/contrib/llvm/tools/lldb/source/Target/TargetList.cpp +++ b/contrib/llvm/tools/lldb/source/Target/TargetList.cpp @@ -15,7 +15,6 @@ #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/State.h" -#include "lldb/Core/Timer.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Interpreter/CommandInterpreter.h" @@ -24,6 +23,7 @@ #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" #include "lldb/Utility/TildeExpressionResolver.h" +#include "lldb/Utility/Timer.h" // Other libraries and framework includes #include "llvm/ADT/SmallString.h" diff --git a/contrib/llvm/tools/lldb/source/Target/ThreadSpec.cpp b/contrib/llvm/tools/lldb/source/Target/ThreadSpec.cpp index f769d1a775af..444a5a5b262a 100644 --- a/contrib/llvm/tools/lldb/source/Target/ThreadSpec.cpp +++ b/contrib/llvm/tools/lldb/source/Target/ThreadSpec.cpp @@ -11,9 +11,9 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Target/Thread.h" -#include "lldb/Core/StructuredData.h" #include "lldb/Target/ThreadSpec.h" +#include "lldb/Target/Thread.h" +#include "lldb/Utility/StructuredData.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Utility/Connection.cpp b/contrib/llvm/tools/lldb/source/Utility/Connection.cpp new file mode 100644 index 000000000000..9f6114f6ed5d --- /dev/null +++ b/contrib/llvm/tools/lldb/source/Utility/Connection.cpp @@ -0,0 +1,14 @@ +//===-- Connection.cpp ------------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "lldb/Utility/Connection.h" + +using namespace lldb_private; + +Connection::~Connection() = default; diff --git a/contrib/llvm/tools/lldb/source/Host/common/IOObject.cpp b/contrib/llvm/tools/lldb/source/Utility/IOObject.cpp index 6f7de442be1d..df7929c4f911 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/IOObject.cpp +++ b/contrib/llvm/tools/lldb/source/Utility/IOObject.cpp @@ -7,8 +7,9 @@ // //===----------------------------------------------------------------------===// -#include "lldb/Host/IOObject.h" +#include "lldb/Utility/IOObject.h" using namespace lldb_private; const IOObject::WaitableHandle IOObject::kInvalidHandleValue = -1; +IOObject::~IOObject() = default; diff --git a/contrib/llvm/tools/lldb/source/Utility/JSON.cpp b/contrib/llvm/tools/lldb/source/Utility/JSON.cpp index cb23f140cbfe..1520bc7c47ec 100644 --- a/contrib/llvm/tools/lldb/source/Utility/JSON.cpp +++ b/contrib/llvm/tools/lldb/source/Utility/JSON.cpp @@ -191,7 +191,7 @@ JSONValue::SP JSONArray::GetObject(Index i) { JSONArray::Size JSONArray::GetNumElements() { return m_elements.size(); } -JSONParser::JSONParser(const char *cstr) : StringExtractor(cstr) {} +JSONParser::JSONParser(llvm::StringRef data) : StringExtractor(data) {} JSONParser::Token JSONParser::GetToken(std::string &value) { StreamString error; diff --git a/contrib/llvm/tools/lldb/source/Core/StructuredData.cpp b/contrib/llvm/tools/lldb/source/Utility/StructuredData.cpp index b03665ed3485..9fc05354cfd3 100644 --- a/contrib/llvm/tools/lldb/source/Core/StructuredData.cpp +++ b/contrib/llvm/tools/lldb/source/Utility/StructuredData.cpp @@ -7,28 +7,18 @@ // //===----------------------------------------------------------------------===// -#include "lldb/Core/StructuredData.h" - -#include "lldb/Host/File.h" -#include "lldb/Host/StringConvert.h" +#include "lldb/Utility/StructuredData.h" #include "lldb/Utility/DataBuffer.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/JSON.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" // for Stream #include "lldb/Utility/StreamString.h" -#include "lldb/lldb-enumerations.h" // for FilePermissions::eFilePermiss... -#include "lldb/lldb-forward.h" // for DataBufferSP - #include "llvm/ADT/STLExtras.h" // for make_unique - -#include <limits> // for numeric_limits - -#include <errno.h> +#include <cerrno> +#include <cstdlib> #include <inttypes.h> -#include <stdio.h> // for printf -#include <stdlib.h> -#include <sys/types.h> // for off_t +#include <limits> // for numeric_limits using namespace lldb_private; @@ -43,36 +33,20 @@ StructuredData::ObjectSP StructuredData::ParseJSONFromFile(const FileSpec &input_spec, Status &error) { StructuredData::ObjectSP return_sp; if (!input_spec.Exists()) { - error.SetErrorStringWithFormat("input file %s does not exist.", - input_spec.GetPath().c_str()); + error.SetErrorStringWithFormatv("input file {0} does not exist.", + input_spec); return return_sp; } - File input_file(nullptr, File::OpenOptions::eOpenOptionRead, - lldb::eFilePermissionsUserRead); - std::string input_path = input_spec.GetPath(); - error = - input_file.Open(input_path.c_str(), File::OpenOptions::eOpenOptionRead, - lldb::eFilePermissionsUserRead); - - if (!error.Success()) { - error.SetErrorStringWithFormat("could not open input file: %s - %s.", - input_spec.GetPath().c_str(), - error.AsCString()); + auto buffer_or_error = llvm::MemoryBuffer::getFile(input_spec.GetPath()); + if (!buffer_or_error) { + error.SetErrorStringWithFormatv("could not open input file: {0} - {1}.", + input_spec.GetPath(), + buffer_or_error.getError().message()); return return_sp; } - lldb::DataBufferSP input_data; - size_t num_bytes = std::numeric_limits<size_t>::max(); - off_t offset = 0; - error = input_file.Read(num_bytes, offset, true, input_data); - if (!error.Success()) { - error.SetErrorStringWithFormat("could not read input file: %s - %s.", - input_spec.GetPath().c_str(), - error.AsCString()); - return return_sp; - } - JSONParser json_parser((char *)input_data->GetBytes()); + JSONParser json_parser(buffer_or_error.get()->getBuffer()); return_sp = ParseJSONValue(json_parser); return return_sp; } @@ -146,16 +120,14 @@ static StructuredData::ObjectSP ParseJSONValue(JSONParser &json_parser) { return ParseJSONArray(json_parser); case JSONParser::Token::Integer: { - bool success = false; - uint64_t uval = StringConvert::ToUInt64(value.c_str(), 0, 0, &success); - if (success) + uint64_t uval; + if (llvm::to_integer(value, uval, 0)) return std::make_shared<StructuredData::Integer>(uval); } break; case JSONParser::Token::Float: { - bool success = false; - double val = StringConvert::ToDouble(value.c_str(), 0.0, &success); - if (success) + double val; + if (llvm::to_float(value, val)) return std::make_shared<StructuredData::Float>(val); } break; @@ -219,7 +191,7 @@ StructuredData::Object::GetObjectForDotSeparatedPath(llvm::StringRef path) { void StructuredData::Object::DumpToStdout(bool pretty_print) const { StreamString stream; Dump(stream, pretty_print); - printf("%s\n", stream.GetData()); + llvm::outs() << stream.GetString(); } void StructuredData::Array::Dump(Stream &s, bool pretty_print) const { diff --git a/contrib/llvm/tools/lldb/source/Core/Timer.cpp b/contrib/llvm/tools/lldb/source/Utility/Timer.cpp index 59c3e13a717e..fe7787458fa6 100644 --- a/contrib/llvm/tools/lldb/source/Core/Timer.cpp +++ b/contrib/llvm/tools/lldb/source/Utility/Timer.cpp @@ -6,11 +6,8 @@ // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// -#include "lldb/Core/Timer.h" - -#include "lldb/Host/Host.h" +#include "lldb/Utility/Timer.h" #include "lldb/Utility/Stream.h" -#include "lldb/lldb-types.h" // for thread_key_t #include <algorithm> #include <map> diff --git a/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.h b/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.h index 207bb4d973a5..7d1a5695a364 100644 --- a/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.h +++ b/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.h @@ -9,8 +9,8 @@ #ifndef lldb_server_Acceptor_h_ #define lldb_server_Acceptor_h_ -#include "lldb/Core/Connection.h" #include "lldb/Host/Socket.h" +#include "lldb/Utility/Connection.h" #include "lldb/Utility/Status.h" #include <functional> diff --git a/contrib/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp b/contrib/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp index 22bc6f7043ee..528247c2dbc3 100644 --- a/contrib/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp +++ b/contrib/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp @@ -125,6 +125,7 @@ static const char *GetBlockName(unsigned BlockID, return "FULL_LTO_GLOBALVAL_SUMMARY_BLOCK"; case bitc::MODULE_STRTAB_BLOCK_ID: return "MODULE_STRTAB_BLOCK"; case bitc::STRTAB_BLOCK_ID: return "STRTAB_BLOCK"; + case bitc::SYMTAB_BLOCK_ID: return "SYMTAB_BLOCK"; } } @@ -393,6 +394,11 @@ static const char *GetCodeName(unsigned CodeID, unsigned BlockID, default: return nullptr; case bitc::STRTAB_BLOB: return "BLOB"; } + case bitc::SYMTAB_BLOCK_ID: + switch(CodeID) { + default: return nullptr; + case bitc::SYMTAB_BLOB: return "BLOB"; + } } #undef STRINGIFY_CODE } diff --git a/contrib/llvm/tools/llvm-lto2/llvm-lto2.cpp b/contrib/llvm/tools/llvm-lto2/llvm-lto2.cpp index bbfece517c80..5426e040cd7c 100644 --- a/contrib/llvm/tools/llvm-lto2/llvm-lto2.cpp +++ b/contrib/llvm/tools/llvm-lto2/llvm-lto2.cpp @@ -16,9 +16,10 @@ // //===----------------------------------------------------------------------===// -#include "llvm/LTO/Caching.h" +#include "llvm/Bitcode/BitcodeReader.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/IR/DiagnosticPrinter.h" +#include "llvm/LTO/Caching.h" #include "llvm/LTO/LTO.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" @@ -298,6 +299,17 @@ static int run(int argc, char **argv) { static int dumpSymtab(int argc, char **argv) { for (StringRef F : make_range(argv + 1, argv + argc)) { std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F); + BitcodeFileContents BFC = check(getBitcodeFileContents(*MB), F); + + if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) { + auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>( + BFC.Symtab.data()); + outs() << "version: " << Hdr->Version << '\n'; + if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion) + outs() << "producer: " << Hdr->Producer.get(BFC.StrtabForSymtab) + << '\n'; + } + std::unique_ptr<InputFile> Input = check(InputFile::create(MB->getMemBufferRef()), F); diff --git a/contrib/llvm/tools/llvm-nm/llvm-nm.cpp b/contrib/llvm/tools/llvm-nm/llvm-nm.cpp index 513e1b87558f..ea47891250f7 100644 --- a/contrib/llvm/tools/llvm-nm/llvm-nm.cpp +++ b/contrib/llvm/tools/llvm-nm/llvm-nm.cpp @@ -18,6 +18,7 @@ #include "llvm/ADT/StringSwitch.h" #include "llvm/BinaryFormat/COFF.h" +#include "llvm/Demangle/Demangle.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalAlias.h" #include "llvm/IR/GlobalVariable.h" @@ -124,6 +125,10 @@ cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered")); cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort), cl::Grouping); +cl::opt<bool> Demangle("demangle", cl::desc("Demangle C++ symbol names")); +cl::alias DemangleC("C", cl::desc("Alias for --demangle"), cl::aliasopt(Demangle), + cl::Grouping); + cl::opt<bool> ReverseSort("reverse-sort", cl::desc("Sort in reverse order")); cl::alias ReverseSortr("r", cl::desc("Alias for --reverse-sort"), cl::aliasopt(ReverseSort), cl::Grouping); @@ -659,6 +664,24 @@ static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) { outs() << Str; } +static Optional<std::string> demangle(StringRef Name, bool StripUnderscore) { + if (StripUnderscore && Name.size() > 0 && Name[0] == '_') + Name = Name.substr(1); + + if (!Name.startswith("_Z")) + return None; + + int Status; + char *Undecorated = + itaniumDemangle(Name.str().c_str(), nullptr, nullptr, &Status); + if (Status != 0) + return None; + + std::string S(Undecorated); + free(Undecorated); + return S; +} + static bool symbolIsDefined(const NMSymbol &Sym) { return Sym.TypeChar != 'U' && Sym.TypeChar != 'w' && Sym.TypeChar != 'v'; } @@ -724,6 +747,12 @@ static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName, for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end(); I != E; ++I) { uint32_t SymFlags; + std::string Name = I->Name.str(); + MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); + if (Demangle) { + if (Optional<std::string> Opt = demangle(I->Name, MachO)) + Name = *Opt; + } if (I->Sym.getRawDataRefImpl().p) SymFlags = I->Sym.getFlags(); else @@ -745,9 +774,10 @@ static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName, outs() << CurrentFilename << ": "; } } - if ((JustSymbolName || (UndefinedOnly && isa<MachOObjectFile>(Obj) && - OutputFormat != darwin)) && OutputFormat != posix) { - outs() << I->Name << "\n"; + if ((JustSymbolName || + (UndefinedOnly && MachO && OutputFormat != darwin)) && + OutputFormat != posix) { + outs() << Name << "\n"; continue; } @@ -767,7 +797,6 @@ static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName, } } - MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); // Otherwise, print the symbol address and size. if (symbolIsDefined(*I)) { if (Obj.isIR()) @@ -789,7 +818,7 @@ static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName, darwinPrintSymbol(Obj, I, SymbolAddrStr, printBlanks, printDashes, printFormat); } else if (OutputFormat == posix) { - outs() << I->Name << " " << I->TypeChar << " "; + outs() << Name << " " << I->TypeChar << " "; if (MachO) outs() << SymbolAddrStr << " " << "0" /* SymbolSizeStr */ << "\n"; else @@ -804,7 +833,7 @@ static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName, outs() << I->TypeChar; if (I->TypeChar == '-' && MachO) darwinPrintStab(MachO, I); - outs() << " " << I->Name; + outs() << " " << Name; if (I->TypeChar == 'I' && MachO) { outs() << " (indirect for "; if (I->Sym.getRawDataRefImpl().p) { @@ -818,7 +847,7 @@ static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName, } outs() << "\n"; } else if (OutputFormat == sysv) { - std::string PaddedName(I->Name); + std::string PaddedName(Name); while (PaddedName.length() < 20) PaddedName += " "; outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar diff --git a/contrib/llvm/tools/llvm-objdump/llvm-objdump.cpp b/contrib/llvm/tools/llvm-objdump/llvm-objdump.cpp index 6a9151570908..be5635a3d4c6 100644 --- a/contrib/llvm/tools/llvm-objdump/llvm-objdump.cpp +++ b/contrib/llvm/tools/llvm-objdump/llvm-objdump.cpp @@ -41,6 +41,7 @@ #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/MachO.h" #include "llvm/Object/ObjectFile.h" +#include "llvm/Object/Wasm.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" @@ -886,6 +887,18 @@ static void printRelocationTargetName(const MachOObjectFile *O, fmt << S; } +static std::error_code getRelocationValueString(const WasmObjectFile *Obj, + const RelocationRef &RelRef, + SmallVectorImpl<char> &Result) { + const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef); + std::string fmtbuf; + raw_string_ostream fmt(fmtbuf); + fmt << Rel.Index << (Rel.Addend < 0 ? "" : "+") << Rel.Addend; + fmt.flush(); + Result.append(fmtbuf.begin(), fmtbuf.end()); + return std::error_code(); +} + static std::error_code getRelocationValueString(const MachOObjectFile *Obj, const RelocationRef &RelRef, SmallVectorImpl<char> &Result) { @@ -1071,8 +1084,11 @@ static std::error_code getRelocationValueString(const RelocationRef &Rel, return getRelocationValueString(ELF, Rel, Result); if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) return getRelocationValueString(COFF, Rel, Result); - auto *MachO = cast<MachOObjectFile>(Obj); - return getRelocationValueString(MachO, Rel, Result); + if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj)) + return getRelocationValueString(Wasm, Rel, Result); + if (auto *MachO = dyn_cast<MachOObjectFile>(Obj)) + return getRelocationValueString(MachO, Rel, Result); + llvm_unreachable("unknown object file format"); } /// @brief Indicates whether this relocation should hidden when listing diff --git a/contrib/llvm/tools/llvm-pdbutil/DumpOutputStyle.cpp b/contrib/llvm/tools/llvm-pdbutil/DumpOutputStyle.cpp index f76635f9e511..a1f919b4dd06 100644 --- a/contrib/llvm/tools/llvm-pdbutil/DumpOutputStyle.cpp +++ b/contrib/llvm/tools/llvm-pdbutil/DumpOutputStyle.cpp @@ -37,6 +37,7 @@ #include "llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h" #include "llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h" #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h" +#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h" #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h" #include "llvm/DebugInfo/MSF/MappedBlockStream.h" #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h" @@ -116,12 +117,14 @@ Error DumpOutputStyle::dump() { return EC; } - if (opts::dump::DumpTypes || opts::dump::DumpTypeExtras) { + if (opts::dump::DumpTypes || !opts::dump::DumpTypeIndex.empty() || + opts::dump::DumpTypeExtras) { if (auto EC = dumpTpiStream(StreamTPI)) return EC; } - if (opts::dump::DumpIds || opts::dump::DumpIdExtras) { + if (opts::dump::DumpIds || !opts::dump::DumpIdIndex.empty() || + opts::dump::DumpIdExtras) { if (auto EC = dumpTpiStream(StreamIPI)) return EC; } @@ -620,6 +623,76 @@ Error DumpOutputStyle::dumpStringTable() { return Error::success(); } +static void buildDepSet(LazyRandomTypeCollection &Types, + ArrayRef<TypeIndex> Indices, + std::map<TypeIndex, CVType> &DepSet) { + SmallVector<TypeIndex, 4> DepList; + for (const auto &I : Indices) { + TypeIndex TI(I); + if (DepSet.find(TI) != DepSet.end() || TI.isSimple() || TI.isNoneType()) + continue; + + CVType Type = Types.getType(TI); + DepSet[TI] = Type; + codeview::discoverTypeIndices(Type, DepList); + buildDepSet(Types, DepList, DepSet); + } +} + +static void dumpFullTypeStream(LinePrinter &Printer, + LazyRandomTypeCollection &Types, + TpiStream &Stream, bool Bytes, bool Extras) { + Printer.formatLine("Showing {0:N} records", Stream.getNumTypeRecords()); + uint32_t Width = + NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords()); + + MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types, + Stream.getHashValues()); + + if (auto EC = codeview::visitTypeStream(Types, V)) { + Printer.formatLine("An error occurred dumping type records: {0}", + toString(std::move(EC))); + } +} + +static void dumpPartialTypeStream(LinePrinter &Printer, + LazyRandomTypeCollection &Types, + TpiStream &Stream, ArrayRef<TypeIndex> TiList, + bool Bytes, bool Extras, bool Deps) { + uint32_t Width = + NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords()); + + MinimalTypeDumpVisitor V(Printer, Width + 2, Bytes, Extras, Types, + Stream.getHashValues()); + + if (opts::dump::DumpTypeDependents) { + // If we need to dump all dependents, then iterate each index and find + // all dependents, adding them to a map ordered by TypeIndex. + std::map<TypeIndex, CVType> DepSet; + buildDepSet(Types, TiList, DepSet); + + Printer.formatLine( + "Showing {0:N} records and their dependents ({1:N} records total)", + TiList.size(), DepSet.size()); + + for (auto &Dep : DepSet) { + if (auto EC = codeview::visitTypeRecord(Dep.second, Dep.first, V)) + Printer.formatLine("An error occurred dumping type record {0}: {1}", + Dep.first, toString(std::move(EC))); + } + } else { + Printer.formatLine("Showing {0:N} records.", TiList.size()); + + for (const auto &I : TiList) { + TypeIndex TI(I); + CVType Type = Types.getType(TI); + if (auto EC = codeview::visitTypeRecord(Type, TI, V)) + Printer.formatLine("An error occurred dumping type record {0}: {1}", TI, + toString(std::move(EC))); + } + } +} + Error DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx) { assert(StreamIdx == StreamTPI || StreamIdx == StreamIPI); @@ -659,27 +732,13 @@ Error DumpOutputStyle::dumpTpiStream(uint32_t StreamIdx) { auto &Types = Err(initializeTypes(StreamIdx)); - if (DumpTypes) { - P.formatLine("Showing {0:N} records", Stream.getNumTypeRecords()); - uint32_t Width = - NumDigits(TypeIndex::FirstNonSimpleIndex + Stream.getNumTypeRecords()); - - MinimalTypeDumpVisitor V(P, Width + 2, DumpBytes, DumpExtras, Types, - Stream.getHashValues()); - - if (Indices.empty()) { - if (auto EC = codeview::visitTypeStream(Types, V)) { - P.formatLine("An error occurred dumping type records: {0}", - toString(std::move(EC))); - } - } else { - for (const auto &I : Indices) { - TypeIndex TI(I); - CVType Type = Types.getType(TI); - if (auto EC = codeview::visitTypeRecord(Type, TI, V)) - P.formatLine("An error occurred dumping type record {0}: {1}", TI, - toString(std::move(EC))); - } + if (DumpTypes || !Indices.empty()) { + if (Indices.empty()) + dumpFullTypeStream(P, Types, Stream, DumpBytes, DumpExtras); + else { + std::vector<TypeIndex> TiList(Indices.begin(), Indices.end()); + dumpPartialTypeStream(P, Types, Stream, TiList, DumpBytes, DumpExtras, + opts::dump::DumpTypeDependents); } } @@ -775,7 +834,8 @@ Error DumpOutputStyle::dumpModuleSyms() { Pipeline.addCallbackToPipeline(Deserializer); Pipeline.addCallbackToPipeline(Dumper); CVSymbolVisitor Visitor(Pipeline); - if (auto EC = Visitor.visitSymbolStream(ModS.getSymbolArray())) { + auto SS = ModS.getSymbolsSubstream(); + if (auto EC = Visitor.visitSymbolStream(ModS.getSymbolArray(), SS.Offset)) { P.formatLine("Error while processing symbol records. {0}", toString(std::move(EC))); continue; @@ -804,13 +864,14 @@ Error DumpOutputStyle::dumpPublics() { Pipeline.addCallbackToPipeline(Deserializer); Pipeline.addCallbackToPipeline(Dumper); CVSymbolVisitor Visitor(Pipeline); + auto ExpectedSymbols = Publics.getSymbolArray(); if (!ExpectedSymbols) { P.formatLine("Could not read public symbol record stream"); return Error::success(); } - if (auto EC = Visitor.visitSymbolStream(*ExpectedSymbols)) + if (auto EC = Visitor.visitSymbolStream(*ExpectedSymbols, 0)) P.formatLine("Error while processing public symbol records. {0}", toString(std::move(EC))); diff --git a/contrib/llvm/tools/llvm-pdbutil/DumpOutputStyle.h b/contrib/llvm/tools/llvm-pdbutil/DumpOutputStyle.h index 296a6c14942e..4c52289f052e 100644 --- a/contrib/llvm/tools/llvm-pdbutil/DumpOutputStyle.h +++ b/contrib/llvm/tools/llvm-pdbutil/DumpOutputStyle.h @@ -37,8 +37,6 @@ private: Error dumpFileSummary(); Error dumpStreamSummary(); - Error dumpBlockRanges(); - Error dumpStreamBytes(); Error dumpStringTable(); Error dumpLines(); Error dumpInlineeLines(); diff --git a/contrib/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.cpp b/contrib/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.cpp index 7f5412d59885..ab7045ca4492 100644 --- a/contrib/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.cpp +++ b/contrib/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.cpp @@ -367,11 +367,17 @@ static std::string formatGaps(uint32_t IndentLevel, } Error MinimalSymbolDumper::visitSymbolBegin(codeview::CVSymbol &Record) { + return visitSymbolBegin(Record, 0); +} + +Error MinimalSymbolDumper::visitSymbolBegin(codeview::CVSymbol &Record, + uint32_t Offset) { // formatLine puts the newline at the beginning, so we use formatLine here // to start a new line, and then individual visit methods use format to // append to the existing line. - P.formatLine("- {0} [size = {1}]", getSymbolKindName(Record.Type), - Record.length()); + P.formatLine("{0} | {1} [size = {2}]", + fmt_align(Offset, AlignStyle::Right, 6), + getSymbolKindName(Record.Type), Record.length()); P.Indent(); return Error::success(); } @@ -394,28 +400,28 @@ std::string MinimalSymbolDumper::typeIndex(TypeIndex TI) const { Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, BlockSym &Block) { P.format(" `{0}`", Block.Name); - AutoIndent Indent(P); - P.formatLine("parent = {0}, addr = {1}", Block.Parent, + AutoIndent Indent(P, 7); + P.formatLine("parent = {0}, end = {1}", Block.Parent, Block.End); + P.formatLine("code size = {0}, addr = {1}", Block.CodeSize, formatSegmentOffset(Block.Segment, Block.CodeOffset)); - P.formatLine("code size = {0}, end = {1}", Block.CodeSize, Block.End); return Error::success(); } Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Thunk32Sym &Thunk) { P.format(" `{0}`", Thunk.Name); - AutoIndent Indent(P); - P.formatLine("parent = {0}, addr = {1}", Thunk.Parent, - formatSegmentOffset(Thunk.Segment, Thunk.Offset)); - P.formatLine("kind = {0}, size = {1}, end = {2}, next = {3}", - formatThunkOrdinal(Thunk.Thunk), Thunk.Length, Thunk.End, + AutoIndent Indent(P, 7); + P.formatLine("parent = {0}, end = {1}, next = {2}", Thunk.Parent, Thunk.End, Thunk.Next); + P.formatLine("kind = {0}, size = {1}, addr = {2}", + formatThunkOrdinal(Thunk.Thunk), Thunk.Length, + formatSegmentOffset(Thunk.Segment, Thunk.Offset)); return Error::success(); } Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, TrampolineSym &Tramp) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("type = {0}, size = {1}, source = {2}, target = {3}", formatTrampolineType(Tramp.Type), Tramp.Size, formatSegmentOffset(Tramp.ThunkSection, Tramp.ThunkOffset), @@ -427,7 +433,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, SectionSym &Section) { P.format(" `{0}`", Section.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("length = {0}, alignment = {1}, rva = {2}, section # = {3}, " "characteristics = {4}", Section.Length, Section.Alignment, Section.Rva, @@ -437,7 +443,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, CoffGroupSym &CG) { P.format(" `{0}`", CG.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("length = {0}, addr = {1}, characteristics = {2}", CG.Size, formatSegmentOffset(CG.Segment, CG.Offset), CG.Characteristics); return Error::success(); @@ -446,7 +452,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, CoffGroupSym &CG) { Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, BPRelativeSym &BPRel) { P.format(" `{0}`", BPRel.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("type = {0}, offset = {1}", typeIndex(BPRel.Type), BPRel.Offset); return Error::success(); } @@ -459,7 +465,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, CallSiteInfoSym &CSI) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("type = {0}, addr = {1}", typeIndex(CSI.Type), formatSegmentOffset(CSI.Segment, CSI.CodeOffset)); return Error::success(); @@ -467,6 +473,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, EnvBlockSym &EnvBlock) { + AutoIndent Indent(P, 7); for (const auto &Entry : EnvBlock.Fields) { P.formatLine("- {0}", Entry); } @@ -475,7 +482,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, FileStaticSym &FS) { P.format(" `{0}`", FS.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("type = {0}, file name offset = {1}, flags = {2}", typeIndex(FS.Index), FS.ModFilenameOffset, formatLocalSymFlags(P.getIndentLevel() + 9, FS.Flags)); @@ -484,7 +491,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, FileStaticSym &FS) { Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, ExportSym &Export) { P.format(" `{0}`", Export.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("ordinal = {0}, flags = {1}", Export.Ordinal, formatExportFlags(P.getIndentLevel() + 9, Export.Flags)); return Error::success(); @@ -492,7 +499,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, ExportSym &Export) { Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Compile2Sym &Compile2) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); SourceLanguage Lang = static_cast<SourceLanguage>( Compile2.Flags & CompileSym2Flags::SourceLanguageMask); P.formatLine("machine = {0}, ver = {1}, language = {2}", @@ -512,7 +519,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Compile3Sym &Compile3) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); SourceLanguage Lang = static_cast<SourceLanguage>( Compile3.Flags & CompileSym3Flags::SourceLanguageMask); P.formatLine("machine = {0}, Ver = {1}, language = {2}", @@ -531,7 +538,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, ConstantSym &Constant) { P.format(" `{0}`", Constant.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("type = {0}, value = {1}", typeIndex(Constant.Type), Constant.Value.toString(10)); return Error::success(); @@ -539,7 +546,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, DataSym &Data) { P.format(" `{0}`", Data.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("type = {0}, addr = {1}", typeIndex(Data.Type), formatSegmentOffset(Data.Segment, Data.DataOffset)); return Error::success(); @@ -553,7 +560,7 @@ Error MinimalSymbolDumper::visitKnownRecord( Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, DefRangeFramePointerRelSym &Def) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("offset = {0}, range = {1}", Def.Offset, formatRange(Def.Range)); P.formatLine("gaps = {2}", Def.Offset, formatGaps(P.getIndentLevel() + 9, Def.Gaps)); @@ -562,7 +569,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, DefRangeRegisterRelSym &Def) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("register = {0}, base ptr = {1}, offset in parent = {2}, has " "spilled udt = {3}", uint16_t(Def.Hdr.Register), int32_t(Def.Hdr.BasePointerOffset), @@ -574,7 +581,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord( CVSymbol &CVR, DefRangeRegisterSym &DefRangeRegister) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("register = {0}, may have no name = {1}, range start = " "{2}, length = {3}", uint16_t(DefRangeRegister.Hdr.Register), @@ -589,7 +596,7 @@ Error MinimalSymbolDumper::visitKnownRecord( Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, DefRangeSubfieldRegisterSym &Def) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); bool NoName = !!(Def.Hdr.MayHaveNoName == 0); P.formatLine("register = {0}, may have no name = {1}, offset in parent = {2}", uint16_t(Def.Hdr.Register), NoName, @@ -601,7 +608,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, DefRangeSubfieldSym &Def) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("program = {0}, offset in parent = {1}, range = {2}", Def.Program, Def.OffsetInParent, formatRange(Def.Range)); P.formatLine("gaps = {0}", formatGaps(P.getIndentLevel() + 9, Def.Gaps)); @@ -609,7 +616,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, } Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, DefRangeSym &Def) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("program = {0}, range = {1}", Def.Program, formatRange(Def.Range)); P.formatLine("gaps = {0}", formatGaps(P.getIndentLevel() + 9, Def.Gaps)); @@ -617,7 +624,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, DefRangeSym &Def) { } Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, FrameCookieSym &FC) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("code offset = {0}, Register = {1}, kind = {2}, flags = {3}", FC.CodeOffset, FC.Register, formatCookieKind(FC.CookieKind), FC.Flags); @@ -625,7 +632,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, FrameCookieSym &FC) { } Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, FrameProcSym &FP) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("size = {0}, padding size = {1}, offset to padding = {2}", FP.TotalFrameBytes, FP.PaddingFrameBytes, FP.OffsetToPadding); P.formatLine("bytes of callee saved registers = {0}, exception handler addr " @@ -640,7 +647,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, FrameProcSym &FP) { Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, HeapAllocationSiteSym &HAS) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("type = {0}, addr = {1} call size = {2}", typeIndex(HAS.Type), formatSegmentOffset(HAS.Segment, HAS.CodeOffset), HAS.CallInstructionSize); @@ -648,7 +655,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, } Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, InlineSiteSym &IS) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); auto Bytes = makeArrayRef(IS.AnnotationData); StringRef Annotations(reinterpret_cast<const char *>(Bytes.begin()), Bytes.size()); @@ -662,7 +669,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, InlineSiteSym &IS) { Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, RegisterSym &Register) { P.format(" `{0}`", Register.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("register = {0}, type = {1}", formatRegisterId(Register.Register), typeIndex(Register.Index)); return Error::success(); @@ -671,7 +678,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, PublicSym32 &Public) { P.format(" `{0}`", Public.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("flags = {0}, addr = {1}", formatPublicSymFlags(P.getIndentLevel() + 9, Public.Flags), formatSegmentOffset(Public.Segment, Public.Offset)); @@ -680,7 +687,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, ProcRefSym &PR) { P.format(" `{0}`", PR.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("module = {0}, sum name = {1}, offset = {2}", PR.Module, PR.SumName, PR.SymOffset); return Error::success(); @@ -689,7 +696,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, ProcRefSym &PR) { Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, LabelSym &Label) { P.format(" `{0}` (addr = {1})", Label.Name, formatSegmentOffset(Label.Segment, Label.CodeOffset)); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("flags = {0}", formatProcSymFlags(P.getIndentLevel() + 9, Label.Flags)); return Error::success(); @@ -697,7 +704,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, LabelSym &Label) { Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, LocalSym &Local) { P.format(" `{0}`", Local.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); std::string FlagStr = formatLocalSymFlags(P.getIndentLevel() + 9, Local.Flags); @@ -713,10 +720,11 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, ProcSym &Proc) { P.format(" `{0}`", Proc.Name); - AutoIndent Indent(P); - P.formatLine("parent = {0}, addr = {1}, code size = {2}, end = {3}", - Proc.Parent, formatSegmentOffset(Proc.Segment, Proc.CodeOffset), - Proc.CodeSize, Proc.End); + AutoIndent Indent(P, 7); + P.formatLine("parent = {0}, end = {1}, addr = {2}, code size = {3}", + Proc.Parent, Proc.End, + formatSegmentOffset(Proc.Segment, Proc.CodeOffset), + Proc.CodeSize); P.formatLine("debug start = {0}, debug end = {1}, flags = {2}", Proc.DbgStart, Proc.DbgEnd, formatProcSymFlags(P.getIndentLevel() + 9, Proc.Flags)); @@ -729,7 +737,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, } Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, CallerSym &Caller) { - AutoIndent Indent(P); + AutoIndent Indent(P, 7); for (const auto &I : Caller.Indices) { P.formatLine("callee: {0}", typeIndex(I)); } @@ -739,7 +747,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, CallerSym &Caller) { Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, RegRelativeSym &RegRel) { P.format(" `{0}`", RegRel.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("type = {0}, register = {1}, offset = {2}", typeIndex(RegRel.Type), formatRegisterId(RegRel.Register), RegRel.Offset); @@ -749,7 +757,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, ThreadLocalDataSym &Data) { P.format(" `{0}`", Data.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("type = {0}, addr = {1}", typeIndex(Data.Type), formatSegmentOffset(Data.Segment, Data.DataOffset)); return Error::success(); @@ -757,7 +765,7 @@ Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, Error MinimalSymbolDumper::visitKnownRecord(CVSymbol &CVR, UDTSym &UDT) { P.format(" `{0}`", UDT.Name); - AutoIndent Indent(P); + AutoIndent Indent(P, 7); P.formatLine("original type = {0}", UDT.Type); return Error::success(); } diff --git a/contrib/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.h b/contrib/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.h index 451f2da6fd1d..5e30959ea9c0 100644 --- a/contrib/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.h +++ b/contrib/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.h @@ -27,6 +27,7 @@ public: : P(P), Types(Types) {} Error visitSymbolBegin(codeview::CVSymbol &Record) override; + Error visitSymbolBegin(codeview::CVSymbol &Record, uint32_t Offset) override; Error visitSymbolEnd(codeview::CVSymbol &Record) override; #define SYMBOL_RECORD(EnumName, EnumVal, Name) \ diff --git a/contrib/llvm/tools/llvm-pdbutil/MinimalTypeDumper.cpp b/contrib/llvm/tools/llvm-pdbutil/MinimalTypeDumper.cpp index 22d3a4557c52..1af53e35ed11 100644 --- a/contrib/llvm/tools/llvm-pdbutil/MinimalTypeDumper.cpp +++ b/contrib/llvm/tools/llvm-pdbutil/MinimalTypeDumper.cpp @@ -377,7 +377,7 @@ Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR, Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR, MemberFunctionRecord &MF) { P.formatLine("return type = {0}, # args = {1}, param list = {2}", - MF.ParameterCount, MF.ArgumentList, MF.ReturnType); + MF.ReturnType, MF.ParameterCount, MF.ArgumentList); P.formatLine("class type = {0}, this type = {1}, this adjust = {2}", MF.ClassType, MF.ThisType, MF.ThisPointerAdjustment); P.formatLine("calling conv = {0}, options = {1}", diff --git a/contrib/llvm/tools/llvm-pdbutil/PdbYaml.cpp b/contrib/llvm/tools/llvm-pdbutil/PdbYaml.cpp index b4a41fbfdb8f..315ae2e6711f 100644 --- a/contrib/llvm/tools/llvm-pdbutil/PdbYaml.cpp +++ b/contrib/llvm/tools/llvm-pdbutil/PdbYaml.cpp @@ -30,8 +30,6 @@ using namespace llvm::pdb; using namespace llvm::pdb::yaml; using namespace llvm::yaml; -LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(uint32_t) -LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::StringRef) LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::pdb::yaml::NamedStreamMapping) LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::pdb::yaml::PdbDbiModuleInfo) LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::pdb::yaml::StreamBlockList) diff --git a/contrib/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp b/contrib/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp index 4a176fb13590..ad11ad498000 100644 --- a/contrib/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp +++ b/contrib/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp @@ -419,6 +419,13 @@ cl::list<uint32_t> DumpIdIndex( cl::desc("only dump ids with the specified hexadecimal type index"), cl::cat(TypeOptions), cl::sub(DumpSubcommand)); +cl::opt<bool> DumpTypeDependents( + "dependents", + cl::desc("In conjunection with -type-index and -id-index, dumps the entire " + "dependency graph for the specified index instead of " + "just the single record with the specified index"), + cl::cat(TypeOptions), cl::sub(DumpSubcommand)); + // SYMBOL OPTIONS cl::opt<bool> DumpPublics("publics", cl::desc("dump Publics stream data"), cl::cat(SymbolOptions), cl::sub(DumpSubcommand)); diff --git a/contrib/llvm/tools/llvm-pdbutil/llvm-pdbutil.h b/contrib/llvm/tools/llvm-pdbutil/llvm-pdbutil.h index 837d8ebbaf9e..9ee5866bbeff 100644 --- a/contrib/llvm/tools/llvm-pdbutil/llvm-pdbutil.h +++ b/contrib/llvm/tools/llvm-pdbutil/llvm-pdbutil.h @@ -135,6 +135,7 @@ extern llvm::cl::opt<bool> DumpTypes; extern llvm::cl::opt<bool> DumpTypeData; extern llvm::cl::opt<bool> DumpTypeExtras; extern llvm::cl::list<uint32_t> DumpTypeIndex; +extern llvm::cl::opt<bool> DumpTypeDependents; extern llvm::cl::opt<bool> DumpIds; extern llvm::cl::opt<bool> DumpIdData; diff --git a/contrib/llvm/tools/llvm-readobj/COFFDumper.cpp b/contrib/llvm/tools/llvm-readobj/COFFDumper.cpp index daa7a643a72f..e5ff3e4186de 100644 --- a/contrib/llvm/tools/llvm-readobj/COFFDumper.cpp +++ b/contrib/llvm/tools/llvm-readobj/COFFDumper.cpp @@ -335,6 +335,7 @@ static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = { LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM ), + LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386 ), @@ -678,6 +679,7 @@ void COFFDumper::printDOSHeader(const dos_header *DH) { template <class PEHeader> void COFFDumper::printPEHeader(const PEHeader *Hdr) { DictScope D(W, "ImageOptionalHeader"); + W.printHex ("Magic", Hdr->Magic); W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion); W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion); W.printNumber("SizeOfCode", Hdr->SizeOfCode); diff --git a/contrib/llvm/tools/llvm-readobj/WasmDumper.cpp b/contrib/llvm/tools/llvm-readobj/WasmDumper.cpp index 21614297e467..14603f8a2b09 100644 --- a/contrib/llvm/tools/llvm-readobj/WasmDumper.cpp +++ b/contrib/llvm/tools/llvm-readobj/WasmDumper.cpp @@ -183,6 +183,7 @@ void WasmDumper::printSymbol(const SymbolRef &Sym) { WasmSymbol Symbol = Obj->getWasmSymbol(Sym.getRawDataRefImpl()); W.printString("Name", Symbol.Name); W.printEnum("Type", static_cast<unsigned>(Symbol.Type), makeArrayRef(WasmSymbolTypes)); + W.printHex("Flags", Symbol.Flags); } } diff --git a/contrib/llvm/tools/opt/opt.cpp b/contrib/llvm/tools/opt/opt.cpp index 9d489ab5a2d2..24cce58047f1 100644 --- a/contrib/llvm/tools/opt/opt.cpp +++ b/contrib/llvm/tools/opt/opt.cpp @@ -242,6 +242,11 @@ static cl::opt<bool> PassRemarksWithHotness( cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden); +static cl::opt<unsigned> PassRemarksHotnessThreshold( + "pass-remarks-hotness-threshold", + cl::desc("Minimum profile count required for an optimization remark to be output"), + cl::Hidden); + static cl::opt<std::string> RemarksFilename("pass-remarks-output", cl::desc("YAML output filename for pass remarks"), @@ -420,7 +425,10 @@ int main(int argc, char **argv) { Context.enableDebugTypeODRUniquing(); if (PassRemarksWithHotness) - Context.setDiagnosticHotnessRequested(true); + Context.setDiagnosticsHotnessRequested(true); + + if (PassRemarksHotnessThreshold) + Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold); std::unique_ptr<tool_output_file> YamlFile; if (RemarksFilename != "") { |